rustc_pattern_analysis/
lints.rs

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