Skip to main content

rustc_expand/mbe/
diagnostics.rs

1use std::borrow::Cow;
2
3use rustc_ast::token::{self, Token};
4use rustc_ast::tokenstream::TokenStream;
5use rustc_attr_ir::diagnostic::{CustomDiagnostic, Directive, FormatArgs};
6use rustc_data_structures::fx::FxHashSet;
7use rustc_errors::{Applicability, Diag, DiagCtxtHandle, DiagMessage, pluralize};
8use rustc_macros::Subdiagnostic;
9use rustc_parse::parser::{Parser, Recovery, token_descr};
10use rustc_session::parse::ParseSess;
11use rustc_span::source_map::SourceMap;
12use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span};
13use tracing::debug;
14
15use super::macro_rules::{MacroRule, NoopTracker, parser_from_cx};
16use crate::expand::{AstFragmentKind, parse_ast_fragment};
17use crate::mbe::macro_parser::ParseResult::*;
18use crate::mbe::macro_parser::{MatcherLoc, NamedParseResult, TtParser};
19use crate::mbe::macro_rules::{
20    Tracker, WhichMatcher, try_match_macro, try_match_macro_attr, try_match_macro_derive,
21};
22
23pub(super) enum FailedMacro<'a> {
24    Func,
25    Attr(&'a TokenStream),
26    Derive,
27}
28
29pub(super) fn failed_to_match_macro(
30    psess: &ParseSess,
31    sp: Span,
32    def_span: Span,
33    name: Ident,
34    args: FailedMacro<'_>,
35    body: &TokenStream,
36    rules: &[MacroRule],
37    on_unmatched_args: Option<&Directive>,
38) -> (Span, ErrorGuaranteed) {
39    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_expand/src/mbe/diagnostics.rs:39",
                        "rustc_expand::mbe::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_expand/src/mbe/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(39u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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(&format_args!("failed to match macro")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("failed to match macro");
40    let def_head_span = if !def_span.is_dummy() && !psess.source_map().is_imported(def_span) {
41        psess.source_map().guess_head_span(def_span)
42    } else {
43        DUMMY_SP
44    };
45
46    // An error occurred, try the expansion again, tracking the expansion closely for better
47    // diagnostics.
48    let mut tracker = CollectTrackerAndEmitter::new(name, psess.dcx(), sp);
49
50    let try_success_result = match args {
51        FailedMacro::Func => try_match_macro(psess, name, body, rules, &mut tracker),
52        FailedMacro::Attr(attr_args) => {
53            try_match_macro_attr(psess, name, attr_args, body, rules, &mut tracker)
54        }
55        FailedMacro::Derive => try_match_macro_derive(psess, name, body, rules, &mut tracker),
56    };
57
58    if try_success_result.is_ok() {
59        // Nonterminal parser recovery might turn failed matches into successful ones,
60        // but for that it must have emitted an error already
61        if !tracker.dcx.has_errors().is_some() {
    {
        ::core::panicking::panic_fmt(format_args!("Macro matching returned a success on the second try"));
    }
};assert!(
62            tracker.dcx.has_errors().is_some(),
63            "Macro matching returned a success on the second try"
64        );
65    }
66
67    if let Some(result) = tracker.result {
68        // An irrecoverable error occurred and has been emitted.
69        return result;
70    }
71
72    let Some(BestFailure { token, msg: label, remaining_matcher, .. }) = tracker.best_failure
73    else {
74        return (sp, psess.dcx().span_delayed_bug(sp, "failed to match a macro"));
75    };
76
77    let span = token.span.substitute_dummy(sp);
78    let CustomDiagnostic {
79        message: custom_message, label: custom_label, notes: custom_notes, ..
80    } = {
81        on_unmatched_args
82            .map(|directive| directive.eval(None, &FormatArgs { this: name.to_string(), .. }))
83            .unwrap_or_default()
84    };
85
86    let mut err = match custom_message {
87        Some(message) => psess.dcx().struct_span_err(span, message),
88        None => psess.dcx().struct_span_err(span, parse_failure_msg(&token, None)),
89    };
90    err.span_label(span, custom_label.unwrap_or_else(|| label.to_string()));
91    if !def_head_span.is_dummy() {
92        err.span_label(def_head_span, "when calling this macro");
93    }
94
95    annotate_doc_comment(&mut err, psess.source_map(), span);
96
97    if let Some(span) = remaining_matcher.span() {
98        err.span_note(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("while trying to match {0}",
                remaining_matcher))
    })format!("while trying to match {remaining_matcher}"));
99    } else {
100        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("while trying to match {0}",
                remaining_matcher))
    })format!("while trying to match {remaining_matcher}"));
101    }
102    for note in custom_notes {
103        err.note(note);
104    }
105
106    if let MatcherLoc::Token { token: expected_token } = &remaining_matcher
107        && (#[allow(non_exhaustive_omitted_patterns)] match expected_token.kind {
    token::OpenInvisible(_) => true,
    _ => false,
}matches!(expected_token.kind, token::OpenInvisible(_))
108            || #[allow(non_exhaustive_omitted_patterns)] match token.kind {
    token::OpenInvisible(_) => true,
    _ => false,
}matches!(token.kind, token::OpenInvisible(_)))
109    {
110        err.note("captured metavariables except for `:tt`, `:ident` and `:lifetime` cannot be compared to other tokens");
111        err.note("see <https://doc.rust-lang.org/nightly/reference/macros-by-example.html#forwarding-a-matched-fragment> for more information");
112
113        if !def_span.is_dummy() && !psess.source_map().is_imported(def_span) {
114            err.help("try using `:tt` instead in the macro definition");
115        }
116    }
117
118    // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
119    if let FailedMacro::Func = args
120        && let Some((body, comma_span)) = body.add_comma()
121    {
122        for rule in rules {
123            let MacroRule::Func { lhs, .. } = rule else { continue };
124            let parser = parser_from_cx(psess, body.clone(), Recovery::Allowed);
125            let mut tt_parser = TtParser::new();
126
127            if let Success(_) =
128                tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, &mut NoopTracker)
129            {
130                if comma_span.is_dummy() {
131                    err.note("you might be missing a comma");
132                } else {
133                    err.span_suggestion_short(
134                        comma_span,
135                        "missing comma here",
136                        ", ",
137                        Applicability::MachineApplicable,
138                    );
139                }
140            }
141        }
142    }
143    let guar = err.emit();
144    (sp, guar)
145}
146
147/// The tracker used for the slow error path that collects useful info for diagnostics.
148struct CollectTrackerAndEmitter<'dcx, 'matcher> {
149    macro_name: Ident,
150    dcx: DiagCtxtHandle<'dcx>,
151
152    /// The matcher currently being parsed.
153    //
154    // FIXME: Factor out a per-arm `Tracker` so that the `Option` is unnecessary.
155    current: Option<(WhichMatcher, &'matcher [MatcherLoc])>,
156
157    /// Matches of [`MatcherLoc`]s that successfully consumed input from the parser.
158    ///
159    /// This accumulates all calls to [`Tracker::matched_one()`]. It is used to identify all
160    /// competing matches for ambiguity errors.
161    matches: FxHashSet<SuccessfulMatch>,
162
163    remaining_matcher: Option<&'matcher MatcherLoc>,
164    /// Which arm's failure should we report? (the one furthest along)
165    best_failure: Option<BestFailure>,
166    root_span: Span,
167    result: Option<(Span, ErrorGuaranteed)>,
168}
169
170#[derive(#[automatically_derived]
impl ::core::marker::Copy for SuccessfulMatch { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SuccessfulMatch { }
#[automatically_derived]
impl ::core::clone::Clone for SuccessfulMatch {
    #[inline]
    fn clone(&self) -> SuccessfulMatch {
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SuccessfulMatch {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "SuccessfulMatch", "input_pos", &self.input_pos, "loc_index",
            &&self.loc_index)
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SuccessfulMatch { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SuccessfulMatch {
    #[inline]
    fn eq(&self, other: &SuccessfulMatch) -> bool {
        self.input_pos == other.input_pos && self.loc_index == other.loc_index
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SuccessfulMatch {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u32>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for SuccessfulMatch {
    #[inline]
    fn partial_cmp(&self, other: &SuccessfulMatch)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for SuccessfulMatch {
    #[inline]
    fn cmp(&self, other: &SuccessfulMatch) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.input_pos, &other.input_pos) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.loc_index, &other.loc_index),
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::hash::Hash for SuccessfulMatch {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.input_pos, state);
        ::core::hash::Hash::hash(&self.loc_index, state)
    }
}Hash)]
171struct SuccessfulMatch {
172    /// The position in the parser.
173    ///
174    /// As per [`Parser::approx_token_stream_pos()`].
175    input_pos: u32,
176
177    /// The index of the [`MatcherLoc`].
178    loc_index: u32,
179}
180
181struct BestFailure {
182    token: Token,
183
184    /// The matcher in which the failure occurred.
185    matcher: WhichMatcher,
186
187    /// The approximate (parser) position of the failure.
188    ///
189    /// This is relative to [`Self::matcher`].
190    position: u32,
191
192    msg: &'static str,
193    remaining_matcher: MatcherLoc,
194}
195
196impl BestFailure {
197    fn is_better_position(&self, matcher: WhichMatcher, position: u32) -> bool {
198        (matcher, position) > (self.matcher, self.position)
199    }
200}
201
202impl<'dcx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'dcx, 'matcher> {
203    fn prepare(&mut self, which_matcher: WhichMatcher, matcher: &'matcher [MatcherLoc]) {
204        if self.current.is_some() {
205            {
    ::core::panicking::panic_fmt(format_args!("`Self::after_arm()` was not called to clean up context"));
};panic!("`Self::after_arm()` was not called to clean up context");
206        }
207
208        self.current = Some((which_matcher, matcher));
209    }
210
211    fn before_match_loc(&mut self, parser: &TtParser, matcher: &'matcher MatcherLoc) {
212        if self.remaining_matcher.is_none()
213            || (parser.has_no_remaining_items_for_step() && *matcher != MatcherLoc::Eof)
214        {
215            self.remaining_matcher = Some(matcher);
216        }
217    }
218
219    fn matched_one(&mut self, parser: &Parser<'_>, loc_index: usize) {
220        let input_pos = parser.approx_token_stream_pos();
221        let loc_index: u32 = loc_index.try_into().unwrap();
222        let m = SuccessfulMatch { input_pos, loc_index };
223        self.matches.insert(m);
224    }
225
226    fn after_arm(&mut self, result: &NamedParseResult) {
227        match *result {
228            Success(_) => {
229                // Nonterminal parser recovery might turn failed matches into successful ones,
230                // but for that it must have emitted an error already
231                self.dcx.span_delayed_bug(
232                    self.root_span,
233                    "should not collect detailed info for successful macro match",
234                );
235            }
236            Failure => {
237                if self.best_failure.is_none() {
238                    {
    ::core::panicking::panic_fmt(format_args!("A matching failure occurred but `Self::failure()` was not called"));
};panic!("A matching failure occurred but `Self::failure()` was not called");
239                }
240            }
241            Ambiguity => {
242                if self.result.is_none() {
243                    {
    ::core::panicking::panic_fmt(format_args!("An ambiguity error occurred but `Self::ambiguity()` was not called"));
};panic!("An ambiguity error occurred but `Self::ambiguity()` was not called");
244                }
245            }
246            ErrorReported(guar) => self.result = Some((self.root_span, guar)),
247        }
248
249        self.current = None;
250        self.matches.clear();
251    }
252
253    fn failure(&mut self, parser: &Parser<'_>) {
254        let Some((which_matcher, _)) = self.current else {
255            {
    ::core::panicking::panic_fmt(format_args!("`Self::prepare()` was not called to initialize context"));
};panic!("`Self::prepare()` was not called to initialize context");
256        };
257
258        let mut token = parser.token;
259        let approx_position = parser.approx_token_stream_pos();
260        let msg = if token.kind == token::Eof {
261            // FIXME: Can this be factored out of the EOF case?
262            if !token.span.is_dummy() {
263                token.span = token.span.shrink_to_hi();
264            }
265            "missing tokens in macro arguments"
266        } else {
267            "no rules expected this token in macro call"
268        };
269
270        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_expand/src/mbe/diagnostics.rs:270",
                        "rustc_expand::mbe::diagnostics", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_expand/src/mbe/diagnostics.rs"),
                        ::tracing_core::__macro_support::Option::Some(270u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::diagnostics"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("token")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("token");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("msg")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("msg");
                                            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(&format_args!("a new failure of an arm")
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&token)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&msg)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?token, ?msg, "a new failure of an arm");
271
272        if self
273            .best_failure
274            .as_ref()
275            .is_none_or(|failure| failure.is_better_position(which_matcher, approx_position))
276        {
277            self.best_failure = Some(BestFailure {
278                token,
279                matcher: which_matcher,
280                position: approx_position,
281                msg,
282                remaining_matcher: self
283                    .remaining_matcher
284                    .expect("must have collected matcher already")
285                    .clone(),
286            })
287        }
288    }
289
290    fn ambiguity(&mut self, parser: &Parser<'_>) {
291        let Some((_, matcher)) = self.current else {
292            {
    ::core::panicking::panic_fmt(format_args!("`Self::prepare()` was not called to initialize context"));
};panic!("`Self::prepare()` was not called to initialize context");
293        };
294
295        #[expect(
296            rustc::potential_query_instability,
297            reason = "sorting the results deterministically afterwards"
298        )]
299        let (mut bb_locs, mut next_locs) = self
300            .matches
301            .iter()
302            .filter(|m| m.input_pos == parser.approx_token_stream_pos())
303            .partition::<Vec<&SuccessfulMatch>, _>(|m| {
304                let loc = &matcher[m.loc_index as usize];
305                #[allow(non_exhaustive_omitted_patterns)] match loc {
    MatcherLoc::MetaVarDecl { .. } => true,
    _ => false,
}matches!(loc, MatcherLoc::MetaVarDecl { .. })
306            });
307
308        // Use a reasonable and deterministic ordering for data in the error message.
309        bb_locs.sort_unstable_by_key(|m| m.loc_index);
310        next_locs.sort_unstable_by_key(|m| m.loc_index);
311
312        let span = parser.token.span.substitute_dummy(self.root_span);
313
314        if parser.token == token::Eof {
315            let msg = "ambiguity: multiple successful parses".to_string();
316            let guar = self.dcx.span_err(span, msg);
317            self.result = Some((span, guar));
318            return;
319        }
320
321        let nts = bb_locs
322            .into_iter()
323            .map(|m| {
324                let loc = &matcher[m.loc_index as usize];
325                let MatcherLoc::MetaVarDecl { bind, kind, .. } = loc else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
326                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} (\'{1}\')", kind, bind))
    })format!("{kind} ('{bind}')")
327            })
328            .collect::<Vec<String>>()
329            .join(" or ");
330
331        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("local ambiguity when calling macro `{0}`: multiple parsing options: {1}",
                self.macro_name,
                match next_locs.len() {
                    0 =>
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("built-in NTs {0}.", nts))
                            }),
                    n =>
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("built-in NTs {1} or {2} other option{0}.",
                                        if n == 1 { "" } else { "s" }, nts, n))
                            }),
                }))
    })format!(
332            "local ambiguity when calling macro `{}`: multiple parsing options: {}",
333            self.macro_name,
334            match next_locs.len() {
335                0 => format!("built-in NTs {nts}."),
336                n => format!("built-in NTs {nts} or {n} other option{s}.", s = pluralize!(n)),
337            }
338        );
339
340        let guar = self.dcx.span_err(span, msg);
341        self.result = Some((span, guar));
342    }
343
344    fn description() -> &'static str {
345        "detailed"
346    }
347
348    fn recovery() -> Recovery {
349        Recovery::Allowed
350    }
351}
352
353impl<'dcx> CollectTrackerAndEmitter<'dcx, '_> {
354    fn new(macro_name: Ident, dcx: DiagCtxtHandle<'dcx>, root_span: Span) -> Self {
355        Self {
356            macro_name,
357            dcx,
358            current: None,
359            matches: FxHashSet::default(),
360            remaining_matcher: None,
361            best_failure: None,
362            root_span,
363            result: None,
364        }
365    }
366}
367
368pub(super) fn emit_frag_parse_err(
369    mut e: Diag<'_>,
370    parser: &mut Parser<'_>,
371    orig_parser: &mut Parser<'_>,
372    site_span: Span,
373    arm_span: Span,
374    kind: AstFragmentKind,
375    bindings: &[MacroRule],
376    matched_rule_bindings: &[MatcherLoc],
377) -> ErrorGuaranteed {
378    // FIXME(davidtwco): avoid depending on the error message text
379    if parser.token == token::Eof
380        && let DiagMessage::Str(message) = &e.messages[0].0
381        && message.ends_with(", found `<eof>`")
382    {
383        let msg = &e.messages[0];
384        e.messages[0] = (
385            DiagMessage::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("macro expansion ends with an incomplete expression: {0}",
                message.replace(", found `<eof>`", "")))
    })format!(
386                "macro expansion ends with an incomplete expression: {}",
387                message.replace(", found `<eof>`", ""),
388            )),
389            msg.1,
390        );
391        if !e.span.is_dummy() {
392            // early end of macro arm (#52866)
393            e.replace_span_with(parser.token.span.shrink_to_hi(), true);
394        }
395    }
396    if e.span.is_dummy() {
397        // Get around lack of span in error (#30128)
398        e.replace_span_with(site_span, true);
399        if !parser.psess.source_map().is_imported(arm_span) {
400            e.span_label(arm_span, "in this macro arm");
401        }
402    } else if parser.psess.source_map().is_imported(parser.token.span) {
403        e.span_label(site_span, "in this macro invocation");
404    }
405    match kind {
406        // Try a statement if an expression is wanted but failed and suggest adding `;` to call.
407        AstFragmentKind::Expr => match parse_ast_fragment(orig_parser, AstFragmentKind::Stmts) {
408            Err(err) => err.cancel(),
409            Ok(_) => {
410                e.note(
411                    "the macro call doesn't expand to an expression, but it can expand to a statement",
412                );
413
414                if parser.token == token::Semi {
415                    if let Ok(snippet) = parser.psess.source_map().span_to_snippet(site_span) {
416                        e.span_suggestion_verbose(
417                            site_span,
418                            "surround the macro invocation with `{}` to interpret the expansion as a statement",
419                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{ {0}; }}", snippet))
    })format!("{{ {snippet}; }}"),
420                            Applicability::MaybeIncorrect,
421                        );
422                    }
423                } else {
424                    e.span_suggestion_verbose(
425                        site_span.shrink_to_hi(),
426                        "add `;` to interpret the expansion as a statement",
427                        ";",
428                        Applicability::MaybeIncorrect,
429                    );
430                }
431            }
432        },
433        _ => annotate_err_with_kind(&mut e, kind, site_span),
434    };
435
436    if parser.token.kind == token::Dollar {
437        let dollar_span = parser.token.span;
438        parser.bump();
439        if let token::Ident(name, _) = parser.token.kind {
440            let metavar_span = dollar_span.to(parser.token.span);
441            let mut bindings_names = ::alloc::vec::Vec::new()vec![];
442            for rule in bindings {
443                let MacroRule::Func { lhs, .. } = rule else { continue };
444                for param in lhs {
445                    let MatcherLoc::MetaVarDecl { bind, .. } = param else { continue };
446                    bindings_names.push(bind.name);
447                }
448            }
449
450            let mut matched_rule_bindings_names = ::alloc::vec::Vec::new()vec![];
451            for param in matched_rule_bindings {
452                let MatcherLoc::MetaVarDecl { bind, .. } = param else { continue };
453                matched_rule_bindings_names.push(bind.name);
454            }
455
456            // Report the unbound metavariable as the primary error up front, so every
457            // case is consistent regardless of which suggestion (if any) we attach below.
458            e.primary_message(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot find macro parameter `${0}` in this scope",
                name))
    })format!("cannot find macro parameter `${name}` in this scope"));
459            e.span(metavar_span);
460            e.span_label(metavar_span, "not found in this scope");
461            if parser.psess.source_map().is_imported(metavar_span) {
462                e.span_label(site_span, "in this macro invocation");
463            }
464
465            if let Some(matched_name) = rustc_span::edit_distance::find_best_match_for_name(
466                &matched_rule_bindings_names[..],
467                name,
468                None,
469            ) {
470                e.span_suggestion_verbose(
471                    parser.token.span,
472                    "there is a macro metavariable with a similar name",
473                    matched_name,
474                    Applicability::MaybeIncorrect,
475                );
476            } else if bindings_names.contains(&name) {
477                e.span_label(
478                    parser.token.span,
479                    "there is an macro metavariable with this name in another macro matcher",
480                );
481            } else if let Some(matched_name) =
482                rustc_span::edit_distance::find_best_match_for_name(&bindings_names[..], name, None)
483            {
484                e.span_suggestion_verbose(
485                    parser.token.span,
486                    "there is a macro metavariable with a similar name in another macro matcher",
487                    matched_name,
488                    Applicability::MaybeIncorrect,
489                );
490            } else if !matched_rule_bindings_names.is_empty() {
491                let msg = matched_rule_bindings_names
492                    .iter()
493                    .map(|sym| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${0}", sym))
    })format!("${}", sym))
494                    .collect::<Vec<_>>()
495                    .join(", ");
496                e.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("available metavariable names are: {0}",
                msg))
    })format!("available metavariable names are: {msg}"));
497            }
498        }
499    }
500    e.emit()
501}
502
503pub(crate) fn annotate_err_with_kind(err: &mut Diag<'_>, kind: AstFragmentKind, span: Span) {
504    match kind {
505        AstFragmentKind::Ty => {
506            err.span_label(span, "this macro call doesn't expand to a type");
507        }
508        AstFragmentKind::Pat => {
509            err.span_label(span, "this macro call doesn't expand to a pattern");
510        }
511        _ => {}
512    };
513}
514
515#[derive(const _: () =
    {
        impl rustc_errors::Subdiagnostic for ExplainDocComment {
            fn add_to_diag<__G>(self, diag: &mut rustc_errors::Diag<'_, __G>)
                where __G: rustc_errors::EmissionGuarantee {
                match self {
                    ExplainDocComment::Inner { span: __binding_0 } => {
                        let mut sub_args = rustc_errors::DiagArgMap::default();
                        let __message =
                            rustc_errors::format_diag_message(&rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("inner doc comments expand to `#![doc = \"...\"]`, which is what this macro attempted to match")),
                                &sub_args);
                        diag.span_label(__binding_0, __message);
                    }
                    ExplainDocComment::Outer { span: __binding_0 } => {
                        let mut sub_args = rustc_errors::DiagArgMap::default();
                        let __message =
                            rustc_errors::format_diag_message(&rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("outer doc comments expand to `#[doc = \"...\"]`, which is what this macro attempted to match")),
                                &sub_args);
                        diag.span_label(__binding_0, __message);
                    }
                }
            }
        }
    };Subdiagnostic)]
516enum ExplainDocComment {
517    #[label(
518        "inner doc comments expand to `#![doc = \"...\"]`, which is what this macro attempted to match"
519    )]
520    Inner {
521        #[primary_span]
522        span: Span,
523    },
524    #[label(
525        "outer doc comments expand to `#[doc = \"...\"]`, which is what this macro attempted to match"
526    )]
527    Outer {
528        #[primary_span]
529        span: Span,
530    },
531}
532
533fn annotate_doc_comment(err: &mut Diag<'_>, sm: &SourceMap, span: Span) {
534    if let Ok(src) = sm.span_to_snippet(span) {
535        if src.starts_with("///") || src.starts_with("/**") {
536            err.subdiagnostic(ExplainDocComment::Outer { span });
537        } else if src.starts_with("//!") || src.starts_with("/*!") {
538            err.subdiagnostic(ExplainDocComment::Inner { span });
539        }
540    }
541}
542
543/// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For
544/// other tokens, this is "unexpected token...".
545fn parse_failure_msg(tok: &Token, expected_token: Option<&Token>) -> Cow<'static, str> {
546    if let Some(expected_token) = expected_token {
547        Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}, found {1}",
                token_descr(expected_token), token_descr(tok)))
    })format!("expected {}, found {}", token_descr(expected_token), token_descr(tok)))
548    } else {
549        match tok.kind {
550            token::Eof => Cow::from("unexpected end of macro invocation"),
551            _ => Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no rules expected {0}",
                token_descr(tok)))
    })format!("no rules expected {}", token_descr(tok))),
552        }
553    }
554}