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