Skip to main content

rue_options/
manifest.rs

1use std::{collections::BTreeMap, ops::Range};
2
3use rue_diagnostic::{DiagnosticKind, ForbiddenBy, Lint, LintLevel, LintLevels, LintName};
4use serde::{Deserialize, Serialize};
5use toml::Spanned;
6
7#[derive(Debug, Default, Clone, Serialize, Deserialize)]
8pub struct Manifest {
9    pub compiler: CompilerSection,
10    #[serde(default)]
11    pub formatter: FormatOptions,
12    /// Overrides for the level of each lint or lint group, keyed by name. The span of each name is
13    /// kept so that problems with it can be reported where it's written.
14    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
15    pub lints: BTreeMap<Spanned<String>, LintLevel>,
16}
17
18/// A name in the `[lints]` section of a manifest that doesn't refer to a known lint or group.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct UnknownLint {
21    pub name: String,
22    /// The span of the name in the manifest, including any quotes.
23    pub span: Range<usize>,
24}
25
26/// An entry in the `[lints]` section of a manifest that tries to change the level of a lint that
27/// a group forbids, such as `unused_binding = "allow"` alongside `unused = "forbid"`.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct ForbiddenLint {
30    pub name: LintName,
31    /// The first lint that the entry couldn't change.
32    pub lint: Lint,
33    pub level: LintLevel,
34    /// The span of the name in the manifest, including any quotes.
35    pub span: Range<usize>,
36}
37
38impl ForbiddenLint {
39    pub fn kind(&self) -> DiagnosticKind {
40        self.name
41            .forbidden_override(self.lint, self.level, ForbiddenBy::Manifest)
42    }
43}
44
45/// The problems found while applying the `[lints]` section of a manifest.
46#[derive(Debug, Default, Clone, PartialEq, Eq)]
47pub struct LintProblems {
48    /// Names that don't refer to a known lint or group, which are ignored.
49    pub unknown: Vec<UnknownLint>,
50    /// Entries that try to change the level of a forbidden lint, which are errors.
51    pub forbidden: Vec<ForbiddenLint>,
52}
53
54impl Manifest {
55    /// Applies the `[lints]` section to the given lint levels, and returns any problems with it. A
56    /// lint's own level takes precedence over the level of any group it's in, unless the group
57    /// forbids it.
58    pub fn apply_lints(&self, levels: &mut LintLevels) -> LintProblems {
59        let mut overrides = Vec::new();
60        let mut spans = Vec::new();
61        let mut problems = LintProblems::default();
62
63        for (name, &level) in &self.lints {
64            if let Some(lint) = LintName::from_name(name.get_ref()) {
65                overrides.push((lint, level));
66                spans.push((lint, name.span()));
67            } else {
68                problems.unknown.push(UnknownLint {
69                    name: name.get_ref().clone(),
70                    span: name.span(),
71                });
72            }
73        }
74
75        for (name, lint, level) in levels.apply(&overrides) {
76            // Each name appears once, since they're the keys of a table
77            let span = spans
78                .iter()
79                .find(|(other, _)| *other == name)
80                .map(|(_, span)| span.clone())
81                .unwrap_or_default();
82
83            problems.forbidden.push(ForbiddenLint {
84                name,
85                lint,
86                level,
87                span,
88            });
89        }
90
91        problems
92    }
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96#[serde(default)]
97pub struct CompilerSection {
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub version: Option<String>,
100    pub entrypoint: String,
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub std: Option<bool>,
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub dist_dir: Option<String>,
105}
106
107impl Default for CompilerSection {
108    fn default() -> Self {
109        Self {
110            version: Some(env!("CARGO_PKG_VERSION").to_string()),
111            entrypoint: "puzzles".to_string(),
112            std: None,
113            dist_dir: None,
114        }
115    }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct FormatOptions {
121    pub max_width: usize,
122    pub indent_width: usize,
123}
124
125impl Default for FormatOptions {
126    fn default() -> Self {
127        Self {
128            max_width: 100,
129            indent_width: 4,
130        }
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn parses_lints_section() {
140        let manifest: Manifest = toml::from_str(
141            r#"
142            [compiler]
143            entrypoint = "puzzles"
144
145            [lints]
146            unused_binding = "allow"
147            unused_function = "warn"
148            unnecessary_cast = "deny"
149            not_a_lint = "deny"
150            "#,
151        )
152        .unwrap();
153
154        let mut levels = LintLevels::default();
155        let unknown = manifest
156            .apply_lints(&mut levels)
157            .unknown
158            .into_iter()
159            .map(|lint| lint.name)
160            .collect::<Vec<_>>();
161
162        assert_eq!(unknown, vec!["not_a_lint".to_string()]);
163        assert_eq!(levels.get(Lint::UnusedBinding), LintLevel::Allow);
164        assert_eq!(levels.get(Lint::UnusedFunction), LintLevel::Warn);
165        assert_eq!(levels.get(Lint::UnnecessaryCast), LintLevel::Deny);
166        assert_eq!(
167            levels.get(Lint::UnusedParameter),
168            Lint::UnusedParameter.default_level()
169        );
170    }
171
172    #[test]
173    fn lints_override_their_groups() {
174        // Keys are sorted, so `unused` comes after the lints in it regardless of where it's written
175        let manifest: Manifest = toml::from_str(
176            r#"
177            [compiler]
178            entrypoint = "puzzles"
179
180            [lints]
181            unused_binding = "allow"
182            unused = "deny"
183            unused_import = "warn"
184            "#,
185        )
186        .unwrap();
187
188        let mut levels = LintLevels::default();
189        assert_eq!(manifest.apply_lints(&mut levels), LintProblems::default());
190        assert_eq!(levels.get(Lint::UnusedBinding), LintLevel::Allow);
191        assert_eq!(levels.get(Lint::UnusedImport), LintLevel::Warn);
192        assert_eq!(levels.get(Lint::UnusedFunction), LintLevel::Deny);
193        assert_eq!(levels.get(Lint::UnusedValue), LintLevel::Deny);
194        assert_eq!(
195            levels.get(Lint::UnnecessaryCast),
196            Lint::UnnecessaryCast.default_level()
197        );
198    }
199
200    #[test]
201    fn lints_cannot_override_forbidden_groups() {
202        let text = "[compiler]\n\n[lints]\nunused = \"forbid\"\nunused_binding = \"allow\"\nunused_import = \"forbid\"\n";
203        let manifest: Manifest = toml::from_str(text).unwrap();
204
205        let mut levels = LintLevels::default();
206        let problems = manifest.apply_lints(&mut levels);
207
208        assert_eq!(
209            problems.forbidden,
210            vec![ForbiddenLint {
211                name: LintName::Lint(Lint::UnusedBinding),
212                lint: Lint::UnusedBinding,
213                level: LintLevel::Allow,
214                span: text.find("unused_binding").unwrap()
215                    ..text.find("unused_binding").unwrap() + "unused_binding".len(),
216            }]
217        );
218        assert_eq!(
219            problems.forbidden[0].kind().to_string(),
220            "Cannot set lint `unused_binding` to `allow`, since it's forbidden by `Rue.toml`"
221        );
222        assert!(problems.unknown.is_empty());
223        assert_eq!(levels.get(Lint::UnusedBinding), LintLevel::Forbid);
224        assert_eq!(levels.get(Lint::UnusedImport), LintLevel::Forbid);
225
226        // A lint can still forbid itself when its group sets a different level
227        let manifest: Manifest = toml::from_str(
228            "[compiler]\n\n[lints]\nunused = \"allow\"\nunused_binding = \"forbid\"\n",
229        )
230        .unwrap();
231
232        let mut levels = LintLevels::default();
233        assert_eq!(manifest.apply_lints(&mut levels), LintProblems::default());
234        assert_eq!(levels.get(Lint::UnusedBinding), LintLevel::Forbid);
235        assert_eq!(levels.get(Lint::UnusedImport), LintLevel::Allow);
236    }
237
238    #[test]
239    fn rejects_unknown_lint_level() {
240        let result = toml::from_str::<Manifest>(
241            r#"
242            [compiler]
243            entrypoint = "puzzles"
244
245            [lints]
246            unused_binding = "expect"
247            "#,
248        );
249
250        assert!(result.is_err());
251    }
252
253    #[test]
254    fn invalid_lint_levels_list_the_valid_ones() {
255        for (value, message) in [
256            (
257                "\"expect\"",
258                "Unknown lint level `expect`, expected `allow`, `warn`, `deny` or `forbid`",
259            ),
260            (
261                "1",
262                "expected a lint level (`allow`, `warn`, `deny` or `forbid`)",
263            ),
264        ] {
265            let error = toml::from_str::<Manifest>(&format!(
266                "[compiler]\n\n[lints]\nunused_binding = {value}\n"
267            ))
268            .unwrap_err();
269
270            assert!(error.message().contains(message), "{}", error.message());
271        }
272    }
273
274    #[test]
275    fn missing_settings_use_their_defaults() {
276        let manifest: Manifest = toml::from_str("[compiler]\n").unwrap();
277
278        assert_eq!(manifest.compiler.entrypoint, "puzzles");
279        assert_eq!(
280            manifest.compiler.version.as_deref(),
281            Some(env!("CARGO_PKG_VERSION"))
282        );
283        assert_eq!(manifest.compiler.std, None);
284        assert_eq!(manifest.compiler.dist_dir, None);
285        assert_eq!(manifest.formatter, FormatOptions::default());
286        assert!(manifest.lints.is_empty());
287
288        // Each formatter setting can be given on its own
289        let manifest: Manifest =
290            toml::from_str("[compiler]\n\n[formatter]\nindent_width = 2\n").unwrap();
291
292        assert_eq!(
293            manifest.formatter,
294            FormatOptions {
295                max_width: 100,
296                indent_width: 2,
297            }
298        );
299    }
300
301    #[test]
302    fn compiler_section_is_required() {
303        let error = toml::from_str::<Manifest>("[formatter]\nmax_width = 80\n").unwrap_err();
304
305        assert!(
306            error.message().contains("missing field `compiler`"),
307            "{}",
308            error.message()
309        );
310    }
311
312    #[test]
313    fn default_manifest_round_trips() {
314        let text = toml::to_string(&Manifest::default()).unwrap();
315        let manifest: Manifest = toml::from_str(&text).unwrap();
316
317        assert_eq!(
318            text,
319            format!(
320                "[compiler]\nversion = \"{}\"\nentrypoint = \"puzzles\"\n\n[formatter]\nmax_width = 100\nindent_width = 4\n",
321                env!("CARGO_PKG_VERSION")
322            )
323        );
324        assert_eq!(toml::to_string(&manifest).unwrap(), text);
325    }
326
327    #[test]
328    fn omits_empty_lints_section() {
329        let manifest = Manifest::default();
330        let text = toml::to_string(&manifest).unwrap();
331        assert!(!text.contains("[lints]"));
332    }
333
334    #[test]
335    fn unknown_group_names_are_reported_like_lints() {
336        let text = "[compiler]\n\n[lints]\nunuse = \"deny\"\nunused = \"allow\"\n";
337        let manifest: Manifest = toml::from_str(text).unwrap();
338
339        let mut levels = LintLevels::default();
340        let unknown = manifest.apply_lints(&mut levels).unknown;
341
342        assert_eq!(
343            unknown,
344            vec![UnknownLint {
345                name: "unuse".to_string(),
346                span: text.find("unuse ").unwrap()..text.find("unuse ").unwrap() + 5,
347            }]
348        );
349        assert_eq!(levels.get(Lint::UnusedBinding), LintLevel::Allow);
350    }
351
352    #[test]
353    fn unknown_lints_have_spans_in_any_table_layout() {
354        for text in [
355            "[lints] # project lints\ntypo = \"allow\"\n",
356            "lints = { typo = \"allow\" }\n",
357            "lints.typo = \"allow\"\n",
358            "[lints]\n\"typo\" = \"allow\"\n",
359        ] {
360            let manifest: Manifest = toml::from_str(&format!("{text}[compiler]\n")).unwrap();
361
362            let unknown = manifest.apply_lints(&mut LintLevels::default()).unknown;
363
364            assert_eq!(unknown.len(), 1, "{text}");
365            assert_eq!(unknown[0].name, "typo");
366        }
367
368        let text = "[compiler]\n\n[lints]\nunused_binding = \"allow\"\n\"typo\" = \"deny\"\n";
369        let manifest: Manifest = toml::from_str(text).unwrap();
370        let unknown = manifest.apply_lints(&mut LintLevels::default()).unknown;
371
372        assert_eq!(&text[unknown[0].span.clone()], "\"typo\"");
373    }
374}