cargo/util/
lints.rs

1use crate::core::{Edition, Feature, Features, Manifest, Package};
2use crate::{CargoResult, GlobalContext};
3use annotate_snippets::{Level, Snippet};
4use cargo_util_schemas::manifest::{TomlLintLevel, TomlToolLints};
5use pathdiff::diff_paths;
6use std::fmt::Display;
7use std::ops::Range;
8use std::path::Path;
9
10const LINT_GROUPS: &[LintGroup] = &[TEST_DUMMY_UNSTABLE];
11pub const LINTS: &[Lint] = &[IM_A_TEAPOT, UNKNOWN_LINTS];
12
13pub fn analyze_cargo_lints_table(
14    pkg: &Package,
15    path: &Path,
16    pkg_lints: &TomlToolLints,
17    ws_contents: &str,
18    ws_document: &toml::Spanned<toml::de::DeTable<'static>>,
19    ws_path: &Path,
20    gctx: &GlobalContext,
21) -> CargoResult<()> {
22    let mut error_count = 0;
23    let manifest = pkg.manifest();
24    let manifest_path = rel_cwd_manifest_path(path, gctx);
25    let ws_path = rel_cwd_manifest_path(ws_path, gctx);
26    let mut unknown_lints = Vec::new();
27    for lint_name in pkg_lints.keys().map(|name| name) {
28        let Some((name, default_level, edition_lint_opts, feature_gate)) =
29            find_lint_or_group(lint_name)
30        else {
31            unknown_lints.push(lint_name);
32            continue;
33        };
34
35        let (_, reason, _) = level_priority(
36            name,
37            *default_level,
38            *edition_lint_opts,
39            pkg_lints,
40            manifest.edition(),
41        );
42
43        // Only run analysis on user-specified lints
44        if !reason.is_user_specified() {
45            continue;
46        }
47
48        // Only run this on lints that are gated by a feature
49        if let Some(feature_gate) = feature_gate {
50            verify_feature_enabled(
51                name,
52                feature_gate,
53                manifest,
54                &manifest_path,
55                ws_contents,
56                ws_document,
57                &ws_path,
58                &mut error_count,
59                gctx,
60            )?;
61        }
62    }
63
64    output_unknown_lints(
65        unknown_lints,
66        manifest,
67        &manifest_path,
68        pkg_lints,
69        ws_contents,
70        ws_document,
71        &ws_path,
72        &mut error_count,
73        gctx,
74    )?;
75
76    if error_count > 0 {
77        Err(anyhow::anyhow!(
78            "encountered {error_count} errors(s) while verifying lints",
79        ))
80    } else {
81        Ok(())
82    }
83}
84
85fn find_lint_or_group<'a>(
86    name: &str,
87) -> Option<(
88    &'static str,
89    &LintLevel,
90    &Option<(Edition, LintLevel)>,
91    &Option<&'static Feature>,
92)> {
93    if let Some(lint) = LINTS.iter().find(|l| l.name == name) {
94        Some((
95            lint.name,
96            &lint.default_level,
97            &lint.edition_lint_opts,
98            &lint.feature_gate,
99        ))
100    } else if let Some(group) = LINT_GROUPS.iter().find(|g| g.name == name) {
101        Some((
102            group.name,
103            &group.default_level,
104            &group.edition_lint_opts,
105            &group.feature_gate,
106        ))
107    } else {
108        None
109    }
110}
111
112fn verify_feature_enabled(
113    lint_name: &str,
114    feature_gate: &Feature,
115    manifest: &Manifest,
116    manifest_path: &str,
117    ws_contents: &str,
118    ws_document: &toml::Spanned<toml::de::DeTable<'static>>,
119    ws_path: &str,
120    error_count: &mut usize,
121    gctx: &GlobalContext,
122) -> CargoResult<()> {
123    if !manifest.unstable_features().is_enabled(feature_gate) {
124        let dash_feature_name = feature_gate.name().replace("_", "-");
125        let title = format!("use of unstable lint `{}`", lint_name);
126        let label = format!(
127            "this is behind `{}`, which is not enabled",
128            dash_feature_name
129        );
130        let second_title = format!("`cargo::{}` was inherited", lint_name);
131        let help = format!(
132            "consider adding `cargo-features = [\"{}\"]` to the top of the manifest",
133            dash_feature_name
134        );
135
136        let message = if let Some(span) =
137            get_span(manifest.document(), &["lints", "cargo", lint_name], false)
138        {
139            Level::Error
140                .title(&title)
141                .snippet(
142                    Snippet::source(manifest.contents())
143                        .origin(&manifest_path)
144                        .annotation(Level::Error.span(span).label(&label))
145                        .fold(true),
146                )
147                .footer(Level::Help.title(&help))
148        } else {
149            let lint_span = get_span(
150                ws_document,
151                &["workspace", "lints", "cargo", lint_name],
152                false,
153            )
154            .unwrap_or_else(|| {
155                panic!("could not find `cargo::{lint_name}` in `[lints]`, or `[workspace.lints]` ")
156            });
157
158            let inherited_note = if let (Some(inherit_span_key), Some(inherit_span_value)) = (
159                get_span(manifest.document(), &["lints", "workspace"], false),
160                get_span(manifest.document(), &["lints", "workspace"], true),
161            ) {
162                Level::Note.title(&second_title).snippet(
163                    Snippet::source(manifest.contents())
164                        .origin(&manifest_path)
165                        .annotation(
166                            Level::Note.span(inherit_span_key.start..inherit_span_value.end),
167                        )
168                        .fold(true),
169                )
170            } else {
171                Level::Note.title(&second_title)
172            };
173
174            Level::Error
175                .title(&title)
176                .snippet(
177                    Snippet::source(ws_contents)
178                        .origin(&ws_path)
179                        .annotation(Level::Error.span(lint_span).label(&label))
180                        .fold(true),
181                )
182                .footer(inherited_note)
183                .footer(Level::Help.title(&help))
184        };
185
186        *error_count += 1;
187        gctx.shell().print_message(message)?;
188    }
189    Ok(())
190}
191
192pub fn get_span(
193    document: &toml::Spanned<toml::de::DeTable<'static>>,
194    path: &[&str],
195    get_value: bool,
196) -> Option<Range<usize>> {
197    let mut table = document.get_ref();
198    let mut iter = path.into_iter().peekable();
199    while let Some(key) = iter.next() {
200        let key_s: &str = key.as_ref();
201        let (key, item) = table.get_key_value(key_s)?;
202        if iter.peek().is_none() {
203            return if get_value {
204                Some(item.span())
205            } else {
206                Some(key.span())
207            };
208        }
209        if let Some(next_table) = item.get_ref().as_table() {
210            table = next_table;
211        }
212        if iter.peek().is_some() {
213            if let Some(array) = item.get_ref().as_array() {
214                let next = iter.next().unwrap();
215                return array.iter().find_map(|item| match item.get_ref() {
216                    toml::de::DeValue::String(s) if s == next => Some(item.span()),
217                    _ => None,
218                });
219            }
220        }
221    }
222    None
223}
224
225/// Gets the relative path to a manifest from the current working directory, or
226/// the absolute path of the manifest if a relative path cannot be constructed
227pub fn rel_cwd_manifest_path(path: &Path, gctx: &GlobalContext) -> String {
228    diff_paths(path, gctx.cwd())
229        .unwrap_or_else(|| path.to_path_buf())
230        .display()
231        .to_string()
232}
233
234#[derive(Copy, Clone, Debug)]
235pub struct LintGroup {
236    pub name: &'static str,
237    pub default_level: LintLevel,
238    pub desc: &'static str,
239    pub edition_lint_opts: Option<(Edition, LintLevel)>,
240    pub feature_gate: Option<&'static Feature>,
241}
242
243/// This lint group is only to be used for testing purposes
244const TEST_DUMMY_UNSTABLE: LintGroup = LintGroup {
245    name: "test_dummy_unstable",
246    desc: "test_dummy_unstable is meant to only be used in tests",
247    default_level: LintLevel::Allow,
248    edition_lint_opts: None,
249    feature_gate: Some(Feature::test_dummy_unstable()),
250};
251
252#[derive(Copy, Clone, Debug)]
253pub struct Lint {
254    pub name: &'static str,
255    pub desc: &'static str,
256    pub groups: &'static [LintGroup],
257    pub default_level: LintLevel,
258    pub edition_lint_opts: Option<(Edition, LintLevel)>,
259    pub feature_gate: Option<&'static Feature>,
260    /// This is a markdown formatted string that will be used when generating
261    /// the lint documentation. If docs is `None`, the lint will not be
262    /// documented.
263    pub docs: Option<&'static str>,
264}
265
266impl Lint {
267    pub fn level(
268        &self,
269        pkg_lints: &TomlToolLints,
270        edition: Edition,
271        unstable_features: &Features,
272    ) -> (LintLevel, LintLevelReason) {
273        // We should return `Allow` if a lint is behind a feature, but it is
274        // not enabled, that way the lint does not run.
275        if self
276            .feature_gate
277            .is_some_and(|f| !unstable_features.is_enabled(f))
278        {
279            return (LintLevel::Allow, LintLevelReason::Default);
280        }
281
282        self.groups
283            .iter()
284            .map(|g| {
285                (
286                    g.name,
287                    level_priority(
288                        g.name,
289                        g.default_level,
290                        g.edition_lint_opts,
291                        pkg_lints,
292                        edition,
293                    ),
294                )
295            })
296            .chain(std::iter::once((
297                self.name,
298                level_priority(
299                    self.name,
300                    self.default_level,
301                    self.edition_lint_opts,
302                    pkg_lints,
303                    edition,
304                ),
305            )))
306            .max_by_key(|(n, (l, _, p))| (l == &LintLevel::Forbid, *p, std::cmp::Reverse(*n)))
307            .map(|(_, (l, r, _))| (l, r))
308            .unwrap()
309    }
310}
311
312#[derive(Copy, Clone, Debug, PartialEq)]
313pub enum LintLevel {
314    Allow,
315    Warn,
316    Deny,
317    Forbid,
318}
319
320impl Display for LintLevel {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        match self {
323            LintLevel::Allow => write!(f, "allow"),
324            LintLevel::Warn => write!(f, "warn"),
325            LintLevel::Deny => write!(f, "deny"),
326            LintLevel::Forbid => write!(f, "forbid"),
327        }
328    }
329}
330
331impl LintLevel {
332    pub fn to_diagnostic_level(self) -> Level {
333        match self {
334            LintLevel::Allow => unreachable!("allow does not map to a diagnostic level"),
335            LintLevel::Warn => Level::Warning,
336            LintLevel::Deny => Level::Error,
337            LintLevel::Forbid => Level::Error,
338        }
339    }
340}
341
342impl From<TomlLintLevel> for LintLevel {
343    fn from(toml_lint_level: TomlLintLevel) -> LintLevel {
344        match toml_lint_level {
345            TomlLintLevel::Allow => LintLevel::Allow,
346            TomlLintLevel::Warn => LintLevel::Warn,
347            TomlLintLevel::Deny => LintLevel::Deny,
348            TomlLintLevel::Forbid => LintLevel::Forbid,
349        }
350    }
351}
352
353#[derive(Copy, Clone, Debug, PartialEq, Eq)]
354pub enum LintLevelReason {
355    Default,
356    Edition(Edition),
357    Package,
358}
359
360impl Display for LintLevelReason {
361    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
362        match self {
363            LintLevelReason::Default => write!(f, "by default"),
364            LintLevelReason::Edition(edition) => write!(f, "in edition {}", edition),
365            LintLevelReason::Package => write!(f, "in `[lints]`"),
366        }
367    }
368}
369
370impl LintLevelReason {
371    fn is_user_specified(&self) -> bool {
372        match self {
373            LintLevelReason::Default => false,
374            LintLevelReason::Edition(_) => false,
375            LintLevelReason::Package => true,
376        }
377    }
378}
379
380fn level_priority(
381    name: &str,
382    default_level: LintLevel,
383    edition_lint_opts: Option<(Edition, LintLevel)>,
384    pkg_lints: &TomlToolLints,
385    edition: Edition,
386) -> (LintLevel, LintLevelReason, i8) {
387    let (unspecified_level, reason) = if let Some(level) = edition_lint_opts
388        .filter(|(e, _)| edition >= *e)
389        .map(|(_, l)| l)
390    {
391        (level, LintLevelReason::Edition(edition))
392    } else {
393        (default_level, LintLevelReason::Default)
394    };
395
396    // Don't allow the group to be overridden if the level is `Forbid`
397    if unspecified_level == LintLevel::Forbid {
398        return (unspecified_level, reason, 0);
399    }
400
401    if let Some(defined_level) = pkg_lints.get(name) {
402        (
403            defined_level.level().into(),
404            LintLevelReason::Package,
405            defined_level.priority(),
406        )
407    } else {
408        (unspecified_level, reason, 0)
409    }
410}
411
412/// This lint is only to be used for testing purposes
413const IM_A_TEAPOT: Lint = Lint {
414    name: "im_a_teapot",
415    desc: "`im_a_teapot` is specified",
416    groups: &[TEST_DUMMY_UNSTABLE],
417    default_level: LintLevel::Allow,
418    edition_lint_opts: None,
419    feature_gate: Some(Feature::test_dummy_unstable()),
420    docs: None,
421};
422
423pub fn check_im_a_teapot(
424    pkg: &Package,
425    path: &Path,
426    pkg_lints: &TomlToolLints,
427    error_count: &mut usize,
428    gctx: &GlobalContext,
429) -> CargoResult<()> {
430    let manifest = pkg.manifest();
431    let (lint_level, reason) =
432        IM_A_TEAPOT.level(pkg_lints, manifest.edition(), manifest.unstable_features());
433
434    if lint_level == LintLevel::Allow {
435        return Ok(());
436    }
437
438    if manifest
439        .normalized_toml()
440        .package()
441        .is_some_and(|p| p.im_a_teapot.is_some())
442    {
443        if lint_level == LintLevel::Forbid || lint_level == LintLevel::Deny {
444            *error_count += 1;
445        }
446        let level = lint_level.to_diagnostic_level();
447        let manifest_path = rel_cwd_manifest_path(path, gctx);
448        let emitted_reason = format!(
449            "`cargo::{}` is set to `{lint_level}` {reason}",
450            IM_A_TEAPOT.name
451        );
452
453        let key_span = get_span(manifest.document(), &["package", "im-a-teapot"], false).unwrap();
454        let value_span = get_span(manifest.document(), &["package", "im-a-teapot"], true).unwrap();
455        let message = level
456            .title(IM_A_TEAPOT.desc)
457            .snippet(
458                Snippet::source(manifest.contents())
459                    .origin(&manifest_path)
460                    .annotation(level.span(key_span.start..value_span.end))
461                    .fold(true),
462            )
463            .footer(Level::Note.title(&emitted_reason));
464
465        gctx.shell().print_message(message)?;
466    }
467    Ok(())
468}
469
470const UNKNOWN_LINTS: Lint = Lint {
471    name: "unknown_lints",
472    desc: "unknown lint",
473    groups: &[],
474    default_level: LintLevel::Warn,
475    edition_lint_opts: None,
476    feature_gate: None,
477    docs: Some(
478        r#"
479### What it does
480Checks for unknown lints in the `[lints.cargo]` table
481
482### Why it is bad
483- The lint name could be misspelled, leading to confusion as to why it is
484  not working as expected
485- The unknown lint could end up causing an error if `cargo` decides to make
486  a lint with the same name in the future
487
488### Example
489```toml
490[lints.cargo]
491this-lint-does-not-exist = "warn"
492```
493"#,
494    ),
495};
496
497fn output_unknown_lints(
498    unknown_lints: Vec<&String>,
499    manifest: &Manifest,
500    manifest_path: &str,
501    pkg_lints: &TomlToolLints,
502    ws_contents: &str,
503    ws_document: &toml::Spanned<toml::de::DeTable<'static>>,
504    ws_path: &str,
505    error_count: &mut usize,
506    gctx: &GlobalContext,
507) -> CargoResult<()> {
508    let (lint_level, reason) =
509        UNKNOWN_LINTS.level(pkg_lints, manifest.edition(), manifest.unstable_features());
510    if lint_level == LintLevel::Allow {
511        return Ok(());
512    }
513
514    let level = lint_level.to_diagnostic_level();
515    let mut emitted_source = None;
516    for lint_name in unknown_lints {
517        if lint_level == LintLevel::Forbid || lint_level == LintLevel::Deny {
518            *error_count += 1;
519        }
520        let title = format!("{}: `{lint_name}`", UNKNOWN_LINTS.desc);
521        let second_title = format!("`cargo::{}` was inherited", lint_name);
522        let underscore_lint_name = lint_name.replace("-", "_");
523        let matching = if let Some(lint) = LINTS.iter().find(|l| l.name == underscore_lint_name) {
524            Some((lint.name, "lint"))
525        } else if let Some(group) = LINT_GROUPS.iter().find(|g| g.name == underscore_lint_name) {
526            Some((group.name, "group"))
527        } else {
528            None
529        };
530        let help =
531            matching.map(|(name, kind)| format!("there is a {kind} with a similar name: `{name}`"));
532
533        let mut message = if let Some(span) =
534            get_span(manifest.document(), &["lints", "cargo", lint_name], false)
535        {
536            level.title(&title).snippet(
537                Snippet::source(manifest.contents())
538                    .origin(&manifest_path)
539                    .annotation(Level::Error.span(span))
540                    .fold(true),
541            )
542        } else {
543            let lint_span = get_span(
544                ws_document,
545                &["workspace", "lints", "cargo", lint_name],
546                false,
547            )
548            .unwrap_or_else(|| {
549                panic!("could not find `cargo::{lint_name}` in `[lints]`, or `[workspace.lints]` ")
550            });
551
552            let inherited_note = if let (Some(inherit_span_key), Some(inherit_span_value)) = (
553                get_span(manifest.document(), &["lints", "workspace"], false),
554                get_span(manifest.document(), &["lints", "workspace"], true),
555            ) {
556                Level::Note.title(&second_title).snippet(
557                    Snippet::source(manifest.contents())
558                        .origin(&manifest_path)
559                        .annotation(
560                            Level::Note.span(inherit_span_key.start..inherit_span_value.end),
561                        )
562                        .fold(true),
563                )
564            } else {
565                Level::Note.title(&second_title)
566            };
567
568            level
569                .title(&title)
570                .snippet(
571                    Snippet::source(ws_contents)
572                        .origin(&ws_path)
573                        .annotation(Level::Error.span(lint_span))
574                        .fold(true),
575                )
576                .footer(inherited_note)
577        };
578
579        if emitted_source.is_none() {
580            emitted_source = Some(format!(
581                "`cargo::{}` is set to `{lint_level}` {reason}",
582                UNKNOWN_LINTS.name
583            ));
584            message = message.footer(Level::Note.title(emitted_source.as_ref().unwrap()));
585        }
586
587        if let Some(help) = help.as_ref() {
588            message = message.footer(Level::Help.title(help));
589        }
590
591        gctx.shell().print_message(message)?;
592    }
593
594    Ok(())
595}
596
597#[cfg(test)]
598mod tests {
599    use itertools::Itertools;
600    use snapbox::ToDebug;
601    use std::collections::HashSet;
602
603    #[test]
604    fn ensure_sorted_lints() {
605        // This will be printed out if the fields are not sorted.
606        let location = std::panic::Location::caller();
607        println!("\nTo fix this test, sort `LINTS` in {}\n", location.file(),);
608
609        let actual = super::LINTS
610            .iter()
611            .map(|l| l.name.to_uppercase())
612            .collect::<Vec<_>>();
613
614        let mut expected = actual.clone();
615        expected.sort();
616        snapbox::assert_data_eq!(actual.to_debug(), expected.to_debug());
617    }
618
619    #[test]
620    fn ensure_sorted_lint_groups() {
621        // This will be printed out if the fields are not sorted.
622        let location = std::panic::Location::caller();
623        println!(
624            "\nTo fix this test, sort `LINT_GROUPS` in {}\n",
625            location.file(),
626        );
627        let actual = super::LINT_GROUPS
628            .iter()
629            .map(|l| l.name.to_uppercase())
630            .collect::<Vec<_>>();
631
632        let mut expected = actual.clone();
633        expected.sort();
634        snapbox::assert_data_eq!(actual.to_debug(), expected.to_debug());
635    }
636
637    #[test]
638    fn ensure_updated_lints() {
639        let path = snapbox::utils::current_rs!();
640        let expected = std::fs::read_to_string(&path).unwrap();
641        let expected = expected
642            .lines()
643            .filter_map(|l| {
644                if l.ends_with(": Lint = Lint {") {
645                    Some(
646                        l.chars()
647                            .skip(6)
648                            .take_while(|c| *c != ':')
649                            .collect::<String>(),
650                    )
651                } else {
652                    None
653                }
654            })
655            .collect::<HashSet<_>>();
656        let actual = super::LINTS
657            .iter()
658            .map(|l| l.name.to_uppercase())
659            .collect::<HashSet<_>>();
660        let diff = expected.difference(&actual).sorted().collect::<Vec<_>>();
661
662        let mut need_added = String::new();
663        for name in &diff {
664            need_added.push_str(&format!("{}\n", name));
665        }
666        assert!(
667            diff.is_empty(),
668            "\n`LINTS` did not contain all `Lint`s found in {}\n\
669            Please add the following to `LINTS`:\n\
670            {}",
671            path.display(),
672            need_added
673        );
674    }
675
676    #[test]
677    fn ensure_updated_lint_groups() {
678        let path = snapbox::utils::current_rs!();
679        let expected = std::fs::read_to_string(&path).unwrap();
680        let expected = expected
681            .lines()
682            .filter_map(|l| {
683                if l.ends_with(": LintGroup = LintGroup {") {
684                    Some(
685                        l.chars()
686                            .skip(6)
687                            .take_while(|c| *c != ':')
688                            .collect::<String>(),
689                    )
690                } else {
691                    None
692                }
693            })
694            .collect::<HashSet<_>>();
695        let actual = super::LINT_GROUPS
696            .iter()
697            .map(|l| l.name.to_uppercase())
698            .collect::<HashSet<_>>();
699        let diff = expected.difference(&actual).sorted().collect::<Vec<_>>();
700
701        let mut need_added = String::new();
702        for name in &diff {
703            need_added.push_str(&format!("{}\n", name));
704        }
705        assert!(
706            diff.is_empty(),
707            "\n`LINT_GROUPS` did not contain all `LintGroup`s found in {}\n\
708            Please add the following to `LINT_GROUPS`:\n\
709            {}",
710            path.display(),
711            need_added
712        );
713    }
714}