Skip to main content

rustc_pattern_analysis/
errors.rs

1use rustc_errors::{Diag, EmissionGuarantee, Subdiagnostic};
2use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
3use rustc_middle::ty::Ty;
4use rustc_span::Span;
5
6use crate::rustc::{RustcPatCtxt, WitnessPat};
7
8#[derive(const _: () =
    {
        impl rustc_errors::Subdiagnostic for Uncovered {
            fn add_to_diag<__G>(self, diag: &mut rustc_errors::Diag<'_, __G>)
                where __G: rustc_errors::EmissionGuarantee {
                match self {
                    Uncovered {
                        span: __binding_0,
                        count: __binding_1,
                        witness_1: __binding_2,
                        witness_2: __binding_3,
                        witness_3: __binding_4,
                        remainder: __binding_5 } => {
                        diag.store_args();
                        diag.arg("count", __binding_1);
                        diag.arg("witness_1", __binding_2);
                        diag.arg("witness_2", __binding_3);
                        diag.arg("witness_3", __binding_4);
                        diag.arg("remainder", __binding_5);
                        let __message =
                            diag.eagerly_translate(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$count ->\n        [1] pattern `{$witness_1}`\n        [2] patterns `{$witness_1}` and `{$witness_2}`\n        [3] patterns `{$witness_1}`, `{$witness_2}` and `{$witness_3}`\n        *[other] patterns `{$witness_1}`, `{$witness_2}`, `{$witness_3}` and {$remainder} more\n    } not covered")));
                        diag.span_label(__binding_0, __message);
                        diag.restore_args();
                    }
                }
            }
        }
    };Subdiagnostic)]
9#[label(
10    "{$count ->
11        [1] pattern `{$witness_1}`
12        [2] patterns `{$witness_1}` and `{$witness_2}`
13        [3] patterns `{$witness_1}`, `{$witness_2}` and `{$witness_3}`
14        *[other] patterns `{$witness_1}`, `{$witness_2}`, `{$witness_3}` and {$remainder} more
15    } not covered"
16)]
17pub struct Uncovered {
18    #[primary_span]
19    span: Span,
20    count: usize,
21    witness_1: String, // a printed pattern
22    witness_2: String, // a printed pattern
23    witness_3: String, // a printed pattern
24    remainder: usize,
25}
26
27impl Uncovered {
28    pub fn new<'p, 'tcx>(
29        span: Span,
30        cx: &RustcPatCtxt<'p, 'tcx>,
31        witnesses: Vec<WitnessPat<'p, 'tcx>>,
32    ) -> Self
33    where
34        'tcx: 'p,
35    {
36        let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap());
37        Self {
38            span,
39            count: witnesses.len(),
40            // Substitute dummy values if witnesses is smaller than 3. These will never be read.
41            witness_2: witnesses.get(1).map(|w| cx.print_witness_pat(w)).unwrap_or_default(),
42            witness_3: witnesses.get(2).map(|w| cx.print_witness_pat(w)).unwrap_or_default(),
43            witness_1,
44            remainder: witnesses.len().saturating_sub(3),
45        }
46    }
47}
48
49#[derive(const _: () =
    {
        impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
            OverlappingRangeEndpoints {
            #[track_caller]
            fn decorate_lint<'__b>(self,
                diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
                match self {
                    OverlappingRangeEndpoints {
                        range: __binding_0, overlap: __binding_1 } => {
                        diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("multiple patterns overlap on their endpoints")));
                        diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("you likely meant to write mutually exclusive ranges")));
                        ;
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("... with this range")));
                        for __binding_1 in __binding_1 {
                            diag.subdiagnostic(__binding_1);
                        }
                        diag
                    }
                };
            }
        }
    };LintDiagnostic)]
50#[diag("multiple patterns overlap on their endpoints")]
51#[note("you likely meant to write mutually exclusive ranges")]
52pub struct OverlappingRangeEndpoints {
53    #[label("... with this range")]
54    pub range: Span,
55    #[subdiagnostic]
56    pub overlap: Vec<Overlap>,
57}
58
59pub struct Overlap {
60    pub span: Span,
61    pub range: String, // a printed pattern
62}
63
64impl Subdiagnostic for Overlap {
65    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
66        let Overlap { span, range } = self;
67
68        // FIXME(mejrs) unfortunately `#[derive(LintDiagnostic)]`
69        // does not support `#[subdiagnostic(eager)]`...
70        let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this range overlaps on `{0}`...",
                range))
    })format!("this range overlaps on `{range}`...");
71        diag.span_label(span, message);
72    }
73}
74
75#[derive(const _: () =
    {
        impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
            ExclusiveRangeMissingMax {
            #[track_caller]
            fn decorate_lint<'__b>(self,
                diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
                match self {
                    ExclusiveRangeMissingMax {
                        first_range: __binding_0,
                        suggestion: __binding_1,
                        max: __binding_2 } => {
                        diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("exclusive range missing `{$max}`")));
                        ;
                        let __code_0 =
                            [::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("{0}", __binding_1))
                                            })].into_iter();
                        diag.arg("suggestion", __binding_1);
                        diag.arg("max", __binding_2);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this range doesn't match `{$max}` because `..` is an exclusive range")));
                        diag.span_suggestions_with_style(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("use an inclusive range instead")),
                            __code_0, rustc_errors::Applicability::MaybeIncorrect,
                            rustc_errors::SuggestionStyle::ShowCode);
                        diag
                    }
                };
            }
        }
    };LintDiagnostic)]
76#[diag("exclusive range missing `{$max}`")]
77pub struct ExclusiveRangeMissingMax {
78    #[label("this range doesn't match `{$max}` because `..` is an exclusive range")]
79    #[suggestion(
80        "use an inclusive range instead",
81        code = "{suggestion}",
82        applicability = "maybe-incorrect"
83    )]
84    /// This is an exclusive range that looks like `lo..max` (i.e. doesn't match `max`).
85    pub first_range: Span,
86    /// Suggest `lo..=max` instead.
87    pub suggestion: String,
88    pub max: String, // a printed pattern
89}
90
91#[derive(const _: () =
    {
        impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
            ExclusiveRangeMissingGap {
            #[track_caller]
            fn decorate_lint<'__b>(self,
                diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
                match self {
                    ExclusiveRangeMissingGap {
                        first_range: __binding_0,
                        gap: __binding_1,
                        suggestion: __binding_2,
                        gap_with: __binding_3 } => {
                        diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("multiple ranges are one apart")));
                        ;
                        let __code_1 =
                            [::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("{0}", __binding_2))
                                            })].into_iter();
                        diag.arg("gap", __binding_1);
                        diag.arg("suggestion", __binding_2);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this range doesn't match `{$gap}` because `..` is an exclusive range")));
                        diag.span_suggestions_with_style(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("use an inclusive range instead")),
                            __code_1, rustc_errors::Applicability::MaybeIncorrect,
                            rustc_errors::SuggestionStyle::ShowCode);
                        for __binding_3 in __binding_3 {
                            diag.subdiagnostic(__binding_3);
                        }
                        diag
                    }
                };
            }
        }
    };LintDiagnostic)]
92#[diag("multiple ranges are one apart")]
93pub struct ExclusiveRangeMissingGap {
94    #[label("this range doesn't match `{$gap}` because `..` is an exclusive range")]
95    #[suggestion(
96        "use an inclusive range instead",
97        code = "{suggestion}",
98        applicability = "maybe-incorrect"
99    )]
100    /// This is an exclusive range that looks like `lo..gap` (i.e. doesn't match `gap`).
101    pub first_range: Span,
102    pub gap: String, // a printed pattern
103    /// Suggest `lo..=gap` instead.
104    pub suggestion: String,
105    #[subdiagnostic]
106    /// All these ranges skipped over `gap` which we think is probably a mistake.
107    pub gap_with: Vec<GappedRange>,
108}
109
110pub struct GappedRange {
111    pub span: Span,
112    pub gap: String,         // a printed pattern
113    pub first_range: String, // a printed pattern
114}
115
116impl Subdiagnostic for GappedRange {
117    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
118        let GappedRange { span, gap, first_range } = self;
119
120        // FIXME(mejrs) unfortunately `#[derive(LintDiagnostic)]`
121        // does not support `#[subdiagnostic(eager)]`...
122        let message = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this could appear to continue range `{0}`, but `{1}` isn\'t matched by either of them",
                first_range, gap))
    })format!(
123            "this could appear to continue range `{first_range}`, but `{gap}` isn't matched by \
124            either of them"
125        );
126        diag.span_label(span, message);
127    }
128}
129
130#[derive(const _: () =
    {
        impl<'__a, 'tcx> rustc_errors::LintDiagnostic<'__a, ()> for
            NonExhaustiveOmittedPattern<'tcx> {
            #[track_caller]
            fn decorate_lint<'__b>(self,
                diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
                match self {
                    NonExhaustiveOmittedPattern {
                        scrut_ty: __binding_0, uncovered: __binding_1 } => {
                        diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("some variants are not matched explicitly")));
                        diag.help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("ensure that all variants are matched explicitly by adding the suggested match arms")));
                        diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the matched value is of type `{$scrut_ty}` and the `non_exhaustive_omitted_patterns` attribute was found")));
                        ;
                        diag.arg("scrut_ty", __binding_0);
                        diag.subdiagnostic(__binding_1);
                        diag
                    }
                };
            }
        }
    };LintDiagnostic)]
131#[diag("some variants are not matched explicitly")]
132#[help("ensure that all variants are matched explicitly by adding the suggested match arms")]
133#[note(
134    "the matched value is of type `{$scrut_ty}` and the `non_exhaustive_omitted_patterns` attribute was found"
135)]
136pub(crate) struct NonExhaustiveOmittedPattern<'tcx> {
137    pub scrut_ty: Ty<'tcx>,
138    #[subdiagnostic]
139    pub uncovered: Uncovered,
140}
141
142#[derive(const _: () =
    {
        impl<'__a> rustc_errors::LintDiagnostic<'__a, ()> for
            NonExhaustiveOmittedPatternLintOnArm {
            #[track_caller]
            fn decorate_lint<'__b>(self,
                diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
                match self {
                    NonExhaustiveOmittedPatternLintOnArm {
                        lint_span: __binding_0,
                        suggest_lint_on_match: __binding_1,
                        lint_level: __binding_2,
                        lint_name: __binding_3 } => {
                        diag.primary_message(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the lint level must be set on the whole match")));
                        diag.help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("it no longer has any effect to set the lint level on an individual match arm")));
                        ;
                        let __code_2 =
                            [::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("#[{0}({1})]\n",
                                                        __binding_2, __binding_3))
                                            })].into_iter();
                        diag.arg("lint_level", __binding_2);
                        diag.arg("lint_name", __binding_3);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("remove this attribute")));
                        if let Some(__binding_1) = __binding_1 {
                            diag.span_suggestions_with_style(__binding_1,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("set the lint level on the whole match")),
                                __code_2, rustc_errors::Applicability::MaybeIncorrect,
                                rustc_errors::SuggestionStyle::ShowCode);
                        }
                        diag
                    }
                };
            }
        }
    };LintDiagnostic)]
143#[diag("the lint level must be set on the whole match")]
144#[help("it no longer has any effect to set the lint level on an individual match arm")]
145pub(crate) struct NonExhaustiveOmittedPatternLintOnArm {
146    #[label("remove this attribute")]
147    pub lint_span: Span,
148    #[suggestion(
149        "set the lint level on the whole match",
150        code = "#[{lint_level}({lint_name})]\n",
151        applicability = "maybe-incorrect"
152    )]
153    pub suggest_lint_on_match: Option<Span>,
154    pub lint_level: &'static str,
155    pub lint_name: &'static str,
156}
157
158#[derive(const _: () =
    {
        impl<'_sess, 'tcx, G> rustc_errors::Diagnostic<'_sess, G> for
            MixedDerefPatternConstructors<'tcx> where
            G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    MixedDerefPatternConstructors {
                        spans: __binding_0,
                        smart_pointer_ty: __binding_1,
                        deref_pattern_label: __binding_2,
                        normal_constructor_label: __binding_3 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("mix of deref patterns and normal constructors")));
                        ;
                        diag.arg("smart_pointer_ty", __binding_1);
                        diag.span(__binding_0.clone());
                        diag.span_label(__binding_2,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("matches on the result of dereferencing `{$smart_pointer_ty}`")));
                        diag.span_label(__binding_3,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("matches directly on `{$smart_pointer_ty}`")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
159#[diag("mix of deref patterns and normal constructors")]
160pub(crate) struct MixedDerefPatternConstructors<'tcx> {
161    #[primary_span]
162    pub spans: Vec<Span>,
163    pub smart_pointer_ty: Ty<'tcx>,
164    #[label("matches on the result of dereferencing `{$smart_pointer_ty}`")]
165    pub deref_pattern_label: Span,
166    #[label("matches directly on `{$smart_pointer_ty}`")]
167    pub normal_constructor_label: Span,
168}