Skip to main content

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.
13x;#[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 !rcx
67        .tcx
68        .lint_level_spec_at_node(NON_EXHAUSTIVE_OMITTED_PATTERNS, rcx.match_lint_level)
69        .is_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 level_spec =
93                rcx.tcx.lint_level_spec_at_node(NON_EXHAUSTIVE_OMITTED_PATTERNS, arm.arm_data);
94            let level = level_spec.level();
95            if level != rustc_session::lint::Level::Allow {
96                rcx.tcx.dcx().emit_warn(NonExhaustiveOmittedPatternLintOnArm {
97                    span: arm.pat.data().span,
98                    lint_span: level_spec.src.span(),
99                    suggest_lint_on_match: rcx.whole_match_span.map(|span| span.shrink_to_lo()),
100                    lint_level: level.as_str(),
101                    lint_name: "non_exhaustive_omitted_patterns",
102                });
103            }
104        }
105    }
106    Ok(())
107}