rustc_pattern_analysis/
lints.rs

1use rustc_middle::lint::LevelAndSource;
2use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
3use rustc_span::ErrorGuaranteed;
4use tracing::instrument;
5
6use crate::MatchArm;
7use crate::constructor::Constructor;
8use crate::errors::{NonExhaustiveOmittedPattern, NonExhaustiveOmittedPatternLintOnArm, Uncovered};
9use crate::pat_column::PatternColumn;
10use crate::rustc::{RevealedTy, RustcPatCtxt, WitnessPat};
11
12/// Traverse the patterns to collect any variants of a non_exhaustive enum that fail to be mentioned
13/// in a given column.
14#[instrument(level = "debug", skip(cx), ret)]
15fn collect_nonexhaustive_missing_variants<'p, 'tcx>(
16    cx: &RustcPatCtxt<'p, 'tcx>,
17    column: &PatternColumn<'p, RustcPatCtxt<'p, 'tcx>>,
18) -> Result<Vec<WitnessPat<'p, 'tcx>>, ErrorGuaranteed> {
19    let Some(&ty) = column.head_ty() else {
20        return Ok(Vec::new());
21    };
22
23    let set = column.analyze_ctors(cx, &ty)?;
24    if set.present.is_empty() {
25        // We can't consistently handle the case where no constructors are present (since this would
26        // require digging deep through any type in case there's a non_exhaustive enum somewhere),
27        // so for consistency we refuse to handle the top-level case, where we could handle it.
28        return Ok(Vec::new());
29    }
30
31    let mut witnesses = Vec::new();
32    if cx.is_foreign_non_exhaustive_enum(ty) {
33        witnesses.extend(
34            set.missing
35                .into_iter()
36                // This will list missing visible variants.
37                .filter(|c| !matches!(c, Constructor::Hidden | Constructor::NonExhaustive))
38                .map(|missing_ctor| WitnessPat::wild_from_ctor(cx, missing_ctor, ty)),
39        )
40    }
41
42    // Recurse into the fields.
43    for ctor in set.present {
44        let specialized_columns = column.specialize(cx, &ty, &ctor);
45        let wild_pat = WitnessPat::wild_from_ctor(cx, ctor, ty);
46        for (i, col_i) in specialized_columns.iter().enumerate() {
47            // Compute witnesses for each column.
48            let wits_for_col_i = collect_nonexhaustive_missing_variants(cx, col_i)?;
49            // For each witness, we build a new pattern in the shape of `ctor(_, _, wit, _, _)`,
50            // adding enough wildcards to match `arity`.
51            for wit in wits_for_col_i {
52                let mut pat = wild_pat.clone();
53                pat.fields[i] = wit;
54                witnesses.push(pat);
55            }
56        }
57    }
58    Ok(witnesses)
59}
60
61pub(crate) fn lint_nonexhaustive_missing_variants<'p, 'tcx>(
62    rcx: &RustcPatCtxt<'p, 'tcx>,
63    arms: &[MatchArm<'p, RustcPatCtxt<'p, 'tcx>>],
64    pat_column: &PatternColumn<'p, RustcPatCtxt<'p, 'tcx>>,
65    scrut_ty: RevealedTy<'tcx>,
66) -> Result<(), ErrorGuaranteed> {
67    if !matches!(
68        rcx.tcx.lint_level_at_node(NON_EXHAUSTIVE_OMITTED_PATTERNS, rcx.match_lint_level).level,
69        rustc_session::lint::Level::Allow
70    ) {
71        let witnesses = collect_nonexhaustive_missing_variants(rcx, pat_column)?;
72        if !witnesses.is_empty() {
73            // Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
74            // is not exhaustive enough.
75            //
76            // NB: The partner lint for structs lives in `compiler/rustc_hir_analysis/src/check/pat.rs`.
77            rcx.tcx.emit_node_span_lint(
78                NON_EXHAUSTIVE_OMITTED_PATTERNS,
79                rcx.match_lint_level,
80                rcx.scrut_span,
81                NonExhaustiveOmittedPattern {
82                    scrut_ty: scrut_ty.inner(),
83                    uncovered: Uncovered::new(rcx.scrut_span, rcx, witnesses),
84                },
85            );
86        }
87    } else {
88        // We used to allow putting the `#[allow(non_exhaustive_omitted_patterns)]` on a match
89        // arm. This no longer makes sense so we warn users, to avoid silently breaking their
90        // usage of the lint.
91        for arm in arms {
92            let LevelAndSource { level, src, .. } =
93                rcx.tcx.lint_level_at_node(NON_EXHAUSTIVE_OMITTED_PATTERNS, arm.arm_data);
94            if !matches!(level, rustc_session::lint::Level::Allow) {
95                let decorator = NonExhaustiveOmittedPatternLintOnArm {
96                    lint_span: src.span(),
97                    suggest_lint_on_match: rcx.whole_match_span.map(|span| span.shrink_to_lo()),
98                    lint_level: level.as_str(),
99                    lint_name: "non_exhaustive_omitted_patterns",
100                };
101
102                use rustc_errors::LintDiagnostic;
103                let mut err = rcx.tcx.dcx().struct_span_warn(arm.pat.data().span, "");
104                decorator.decorate_lint(&mut err);
105                err.emit();
106            }
107        }
108    }
109    Ok(())
110}