Skip to main content

rustc_pattern_analysis/
lints.rs

1use rustc_lint_defs::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.
15{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("collect_nonexhaustive_missing_variants",
                                "rustc_pattern_analysis::lints", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_pattern_analysis/src/lints.rs"),
                                ::tracing_core::__macro_support::Option::Some(15u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_pattern_analysis::lints"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("column")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("column");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&column)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                Result<Vec<WitnessPat<'p, 'tcx>>, ErrorGuaranteed> =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let Some(&ty) =
                            column.head_ty() else { return Ok(Vec::new()); };
                        let set = column.analyze_ctors(cx, &ty)?;
                        if set.present.is_empty() { return Ok(Vec::new()); }
                        let mut witnesses = Vec::new();
                        if cx.is_foreign_non_exhaustive_enum(ty) {
                            witnesses.extend(set.missing.into_iter().filter(|c|
                                            !#[allow(non_exhaustive_omitted_patterns)] match c {
                                                    Constructor::Hidden | Constructor::NonExhaustive => true,
                                                    _ => false,
                                                }).map(|missing_ctor|
                                        WitnessPat::wild_from_ctor(cx, missing_ctor, ty)))
                        }
                        for ctor in set.present {
                            let specialized_columns = column.specialize(cx, &ty, &ctor);
                            let wild_pat = WitnessPat::wild_from_ctor(cx, ctor, ty);
                            for (i, col_i) in specialized_columns.iter().enumerate() {
                                let wits_for_col_i =
                                    collect_nonexhaustive_missing_variants(cx, col_i)?;
                                for wit in wits_for_col_i {
                                    let mut pat = wild_pat.clone();
                                    pat.fields[i] = wit;
                                    witnesses.push(pat);
                                }
                            }
                        }
                        Ok(witnesses)
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_pattern_analysis/src/lints.rs:15",
                        "rustc_pattern_analysis::lints", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_pattern_analysis/src/lints.rs"),
                        ::tracing_core::__macro_support::Option::Some(15u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_pattern_analysis::lints"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[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_lint_defs::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}