Skip to main content

rustc_expand/mbe/
macro_rules.rs

1use std::borrow::Cow;
2use std::collections::hash_map::Entry;
3use std::sync::Arc;
4use std::{mem, slice};
5
6use ast::token::IdentIsRaw;
7use rustc_ast::token::NtPatKind::*;
8use rustc_ast::token::TokenKind::*;
9use rustc_ast::token::{self, Delimiter, NonterminalKind, Token, TokenKind};
10use rustc_ast::tokenstream::{self, DelimSpan, TokenStream};
11use rustc_ast::{self as ast, DUMMY_NODE_ID, NodeId, Safety};
12use rustc_ast_pretty::pprust;
13use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
14use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan};
15use rustc_feature::Features;
16use rustc_hir as hir;
17use rustc_hir::attrs::diagnostic::Directive;
18use rustc_hir::def::MacroKinds;
19use rustc_hir::find_attr;
20use rustc_lint_defs::builtin::{
21    RUST_2021_INCOMPATIBLE_OR_PATTERNS, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
22};
23use rustc_parse::exp;
24use rustc_parse::parser::{Parser, Recovery};
25use rustc_session::Session;
26use rustc_session::errors::feature_err;
27use rustc_session::parse::ParseSess;
28use rustc_span::edition::Edition;
29use rustc_span::hygiene::Transparency;
30use rustc_span::{Ident, Span, Symbol, kw, sym};
31use tracing::{debug, instrument, trace, trace_span};
32
33use super::SequenceRepetition;
34use super::diagnostics::{FailedMacro, failed_to_match_macro};
35use super::macro_parser::{NamedMatches, NamedParseResult};
36use crate::base::{
37    AttrProcMacro, BangProcMacro, DummyResult, ExpandResult, ExtCtxt, MacResult,
38    MacroExpanderResult, SyntaxExtension, SyntaxExtensionKind, TTMacroExpander,
39};
40use crate::diagnostics;
41use crate::expand::{AstFragment, AstFragmentKind, ensure_complete_parse, parse_ast_fragment};
42use crate::mbe::macro_check::check_meta_variables;
43use crate::mbe::macro_parser::{Ambiguity, ErrorReported, Failure, MatcherLoc, Success, TtParser};
44use crate::mbe::quoted::{RulePart, parse_one_tt};
45use crate::mbe::transcribe::transcribe;
46use crate::mbe::{self, KleeneOp};
47
48pub(crate) struct ParserAnyMacro<'a, 'b> {
49    parser: Parser<'a>,
50
51    /// Span of the expansion site of the macro this parser is for
52    site_span: Span,
53    /// The ident of the macro we're parsing
54    macro_ident: Ident,
55    lint_node_id: NodeId,
56    is_trailing_mac: bool,
57    arm_span: Span,
58    /// Whether or not this macro is defined in the current crate
59    is_local: bool,
60    bindings: &'b [MacroRule],
61    matched_rule_bindings: &'b [MatcherLoc],
62}
63
64impl<'a, 'b> ParserAnyMacro<'a, 'b> {
65    pub(crate) fn make(
66        mut self: Box<ParserAnyMacro<'a, 'b>>,
67        kind: AstFragmentKind,
68    ) -> AstFragment {
69        let ParserAnyMacro {
70            site_span,
71            macro_ident,
72            ref mut parser,
73            lint_node_id,
74            arm_span,
75            is_trailing_mac,
76            is_local,
77            bindings,
78            matched_rule_bindings,
79        } = *self;
80        let snapshot = &mut parser.create_snapshot_for_diagnostic();
81        let fragment = match parse_ast_fragment(parser, kind) {
82            Ok(f) => f,
83            Err(err) => {
84                let guar = super::diagnostics::emit_frag_parse_err(
85                    err,
86                    parser,
87                    snapshot,
88                    site_span,
89                    arm_span,
90                    kind,
91                    bindings,
92                    matched_rule_bindings,
93                );
94                return kind.dummy(site_span, guar);
95            }
96        };
97
98        // We allow semicolons at the end of expressions -- e.g., the semicolon in
99        // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
100        // but `m!()` is allowed in expression positions (cf. issue #34706).
101        if kind == AstFragmentKind::Expr && parser.token == token::Semi {
102            if is_local {
103                parser.psess.buffer_lint(
104                    SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
105                    parser.token.span,
106                    lint_node_id,
107                    diagnostics::TrailingMacro { is_trailing: is_trailing_mac, name: macro_ident },
108                );
109            }
110            parser.bump();
111        }
112
113        // Make sure we don't have any tokens left to parse so we don't silently drop anything.
114        let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
115        ensure_complete_parse(parser, &path, kind.name(), site_span);
116        fragment
117    }
118
119    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::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("from_tts",
                                    "rustc_expand::mbe::macro_rules", ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                    ::tracing_core::__macro_support::Option::Some(119u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&["site_span",
                                                    "arm_span", "is_local", "macro_ident"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&site_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arm_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&is_local as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&macro_ident)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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: Self = loop {};
            return __tracing_attr_fake_return;
        }
        {
            Self {
                parser: Parser::new(&cx.sess.psess, tts, None),
                site_span,
                macro_ident,
                lint_node_id: cx.current_expansion.lint_node_id,
                is_trailing_mac: cx.current_expansion.is_trailing_mac,
                arm_span,
                is_local,
                bindings,
                matched_rule_bindings,
            }
        }
    }
}#[instrument(skip(cx, tts, bindings, matched_rule_bindings))]
120    pub(crate) fn from_tts<'cx>(
121        cx: &'cx mut ExtCtxt<'a>,
122        tts: TokenStream,
123        site_span: Span,
124        arm_span: Span,
125        is_local: bool,
126        macro_ident: Ident,
127        // bindings and lhs is for diagnostics
128        bindings: &'b [MacroRule],
129        matched_rule_bindings: &'b [MatcherLoc],
130    ) -> Self {
131        Self {
132            parser: Parser::new(&cx.sess.psess, tts, None),
133
134            // Pass along the original expansion site and the name of the macro
135            // so we can print a useful error message if the parse of the expanded
136            // macro leaves unparsed tokens.
137            site_span,
138            macro_ident,
139            lint_node_id: cx.current_expansion.lint_node_id,
140            is_trailing_mac: cx.current_expansion.is_trailing_mac,
141            arm_span,
142            is_local,
143            bindings,
144            matched_rule_bindings,
145        }
146    }
147}
148
149pub(crate) enum MacroRule {
150    /// A function-style rule, for use with `m!()`
151    Func { lhs: Vec<MatcherLoc>, lhs_span: Span, rhs: mbe::TokenTree },
152    /// An attr rule, for use with `#[m]`
153    Attr {
154        unsafe_rule: bool,
155        args: Vec<MatcherLoc>,
156        args_span: Span,
157        body: Vec<MatcherLoc>,
158        body_span: Span,
159        rhs: mbe::TokenTree,
160    },
161    /// A derive rule, for use with `#[m]`
162    Derive { body: Vec<MatcherLoc>, body_span: Span, rhs: mbe::TokenTree },
163}
164
165/// A selection of a matcher in a [`MacroRule`].
166///
167/// [`MacroRule::Attr`] has two different matchers (args and body). This enum allows distinguishing
168/// between them, even when used for other kinds of rules.
169///
170/// This type implements [`Ord`]. The arms within a rule come in a fixed order and this type is
171/// consistent with that ordering.
172#[derive(#[automatically_derived]
impl ::core::marker::Copy for WhichMatcher { }Copy, #[automatically_derived]
impl ::core::clone::Clone for WhichMatcher {
    #[inline]
    fn clone(&self) -> WhichMatcher { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for WhichMatcher {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                WhichMatcher::Args => "Args",
                WhichMatcher::Body => "Body",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for WhichMatcher {
    #[inline]
    fn eq(&self, other: &WhichMatcher) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for WhichMatcher {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for WhichMatcher {
    #[inline]
    fn partial_cmp(&self, other: &WhichMatcher)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for WhichMatcher {
    #[inline]
    fn cmp(&self, other: &WhichMatcher) -> ::core::cmp::Ordering {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr)
    }
}Ord)]
173pub(crate) enum WhichMatcher {
174    /// The arguments of an attr macro ([`MacroRule::Attr::args`]).
175    Args,
176
177    /// The body of an attr macro ([`MacroRule::Attr::body`]), **or** the only arm of the rule.
178    ///
179    /// This is also used to express the only arm in a [`MacroRule::Func`] or [`MacroRule::Derive`].
180    Body,
181}
182
183impl WhichMatcher {
184    /// The [`WhichMatcher`] for [`MacroRule::Func`].
185    pub(crate) const FOR_FUNC: Self = Self::Body;
186
187    /// The [`WhichMatcher`] for [`MacroRule::Derive`].
188    pub(crate) const FOR_DERIVE: Self = Self::Body;
189}
190
191pub struct MacroRulesMacroExpander {
192    node_id: NodeId,
193    name: Ident,
194    span: Span,
195    on_unmatched_args: Option<Directive>,
196    transparency: Transparency,
197    kinds: MacroKinds,
198    rules: Vec<MacroRule>,
199    macro_rules: bool,
200}
201
202impl MacroRulesMacroExpander {
203    pub fn get_unused_rule(&self, rule_i: usize) -> Option<(&Ident, MultiSpan)> {
204        // If the rhs contains an invocation like `compile_error!`, don't report it as unused.
205        let (span, rhs) = match self.rules[rule_i] {
206            MacroRule::Func { lhs_span, ref rhs, .. } => (MultiSpan::from_span(lhs_span), rhs),
207            MacroRule::Attr { args_span, body_span, ref rhs, .. } => {
208                (MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [args_span, body_span]))vec![args_span, body_span]), rhs)
209            }
210            MacroRule::Derive { body_span, ref rhs, .. } => (MultiSpan::from_span(body_span), rhs),
211        };
212        if has_compile_error_macro(rhs) { None } else { Some((&self.name, span)) }
213    }
214
215    pub fn kinds(&self) -> MacroKinds {
216        self.kinds
217    }
218
219    pub fn nrules(&self) -> usize {
220        self.rules.len()
221    }
222
223    pub fn is_macro_rules(&self) -> bool {
224        self.macro_rules
225    }
226
227    pub fn expand_derive(
228        &self,
229        cx: &mut ExtCtxt<'_>,
230        sp: Span,
231        body: &TokenStream,
232    ) -> Result<TokenStream, ErrorGuaranteed> {
233        // This is similar to `expand_macro`, but they have very different signatures, and will
234        // diverge further once derives support arguments.
235        let name = self.name;
236        let rules = &self.rules;
237        let psess = &cx.sess.psess;
238
239        if cx.trace_macros() {
240            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expanding `#[derive({1})] {0}`",
                pprust::tts_to_string(body), name))
    })format!("expanding `#[derive({name})] {}`", pprust::tts_to_string(body));
241            trace_macros_note(&mut cx.expansions, sp, msg);
242        }
243
244        match try_match_macro_derive(psess, name, body, rules, &mut NoopTracker) {
245            Ok((rule_index, rule, named_matches)) => {
246                let MacroRule::Derive { rhs, .. } = rule else {
247                    {
    ::core::panicking::panic_fmt(format_args!("try_match_macro_derive returned non-derive rule"));
};panic!("try_match_macro_derive returned non-derive rule");
248                };
249                let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
250                    cx.dcx().span_bug(sp, "malformed macro derive rhs");
251                };
252
253                let id = cx.current_expansion.id;
254                let tts = transcribe(psess, &named_matches, rhs, *rhs_span, self.transparency, id)
255                    .map_err(|e| e.emit())?;
256
257                if cx.trace_macros() {
258                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to `{0}`",
                pprust::tts_to_string(&tts)))
    })format!("to `{}`", pprust::tts_to_string(&tts));
259                    trace_macros_note(&mut cx.expansions, sp, msg);
260                }
261
262                if is_defined_in_current_crate(self.node_id) {
263                    cx.resolver.record_macro_rule_usage(self.node_id, rule_index);
264                }
265
266                Ok(tts)
267            }
268            Err(CanRetry::No(guar)) => Err(guar),
269            Err(CanRetry::Yes) => {
270                let (_, guar) = failed_to_match_macro(
271                    cx.psess(),
272                    sp,
273                    self.span,
274                    name,
275                    FailedMacro::Derive,
276                    body,
277                    rules,
278                    self.on_unmatched_args.as_ref(),
279                );
280                cx.macro_error_and_trace_macros_diag();
281                Err(guar)
282            }
283        }
284    }
285}
286
287impl TTMacroExpander for MacroRulesMacroExpander {
288    fn expand<'cx, 'a: 'cx>(
289        &'a self,
290        cx: &'cx mut ExtCtxt<'_>,
291        sp: Span,
292        input: TokenStream,
293    ) -> MacroExpanderResult<'cx> {
294        ExpandResult::Ready(expand_macro(
295            cx,
296            sp,
297            self.span,
298            self.node_id,
299            self.name,
300            self.transparency,
301            input,
302            &self.rules,
303            self.on_unmatched_args.as_ref(),
304        ))
305    }
306}
307
308impl AttrProcMacro for MacroRulesMacroExpander {
309    fn expand(
310        &self,
311        _cx: &mut ExtCtxt<'_>,
312        _sp: Span,
313        _args: TokenStream,
314        _body: TokenStream,
315    ) -> Result<TokenStream, ErrorGuaranteed> {
316        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`expand` called on `MacroRulesMacroExpander`, expected `expand_with_safety`")));
}unreachable!("`expand` called on `MacroRulesMacroExpander`, expected `expand_with_safety`")
317    }
318
319    fn expand_with_safety(
320        &self,
321        cx: &mut ExtCtxt<'_>,
322        safety: Safety,
323        sp: Span,
324        args: TokenStream,
325        body: TokenStream,
326    ) -> Result<TokenStream, ErrorGuaranteed> {
327        expand_macro_attr(
328            cx,
329            sp,
330            self.span,
331            self.node_id,
332            self.name,
333            self.transparency,
334            safety,
335            args,
336            body,
337            &self.rules,
338            self.on_unmatched_args.as_ref(),
339        )
340    }
341}
342
343struct DummyBang(ErrorGuaranteed);
344
345impl BangProcMacro for DummyBang {
346    fn expand<'cx>(
347        &self,
348        _: &'cx mut ExtCtxt<'_>,
349        _: Span,
350        _: TokenStream,
351    ) -> Result<TokenStream, ErrorGuaranteed> {
352        Err(self.0)
353    }
354}
355
356fn trace_macros_note(cx_expansions: &mut FxIndexMap<Span, Vec<String>>, sp: Span, message: String) {
357    let sp = sp.macro_backtrace().last().map_or(sp, |trace| trace.call_site);
358    cx_expansions.entry(sp).or_default().push(message);
359}
360
361pub(super) trait Tracker<'matcher> {
362    /// Provide context on the arm that's about to be matched.
363    fn prepare(&mut self, which_matcher: WhichMatcher);
364
365    /// This is called before trying to match next MatcherLoc on the current token.
366    fn before_match_loc(&mut self, parser: &TtParser, matcher: &'matcher MatcherLoc);
367
368    /// This is called after an arm has been parsed, either successfully or unsuccessfully. When
369    /// this is called, `before_match_loc` was called at least once (with a `MatcherLoc::Eof`).
370    fn after_arm(&mut self, result: &NamedParseResult);
371
372    /// The arm could not be matched successfully.
373    ///
374    /// If the parser is located at [`token::Eof`], it indicates an unexpected end of macro
375    /// invocation. Otherwise, the parser is located at a token in the middle of the input, and it
376    /// indicates that no rules in the arm expected the given token.
377    ///
378    /// The parser will return [`NamedParseResult::Failure`] after calling this.
379    fn failure(&mut self, parser: &Parser<'_>);
380
381    /// An ambiguity error occurred.
382    ///
383    /// The parser will return [`NamedParseResult::Ambiguity`] after calling this.
384    fn ambiguity(
385        &mut self,
386        parser: &Parser<'_>,
387        bb_locs: impl IntoIterator<Item = &'matcher MatcherLoc>,
388        next_locs: impl IntoIterator<Item = &'matcher MatcherLoc>,
389    );
390
391    /// For tracing.
392    fn description() -> &'static str;
393
394    fn recovery() -> Recovery;
395}
396
397/// A noop tracker that is used in the hot path of the expansion, has zero overhead thanks to
398/// monomorphization.
399pub(super) struct NoopTracker;
400
401impl<'matcher> Tracker<'matcher> for NoopTracker {
402    fn prepare(&mut self, _which_matcher: WhichMatcher) {}
403
404    fn before_match_loc(&mut self, _parser: &TtParser, _matcher: &'matcher MatcherLoc) {}
405
406    fn ambiguity(
407        &mut self,
408        _parser: &Parser<'_>,
409        _bb_locs: impl IntoIterator<Item = &'matcher MatcherLoc>,
410        _next_locs: impl IntoIterator<Item = &'matcher MatcherLoc>,
411    ) {
412    }
413
414    fn after_arm(&mut self, _result: &NamedParseResult) {}
415
416    fn failure(&mut self, _parser: &Parser<'_>) {}
417
418    fn description() -> &'static str {
419        "none"
420    }
421
422    fn recovery() -> Recovery {
423        Recovery::Forbidden
424    }
425}
426
427/// Expands the rules based macro defined by `rules` for a given input `arg`.
428#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::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("expand_macro",
                                    "rustc_expand::mbe::macro_rules", ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                    ::tracing_core::__macro_support::Option::Some(428u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&["sp", "def_span",
                                                    "node_id", "name"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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: Box<dyn MacResult + 'cx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let psess = &cx.sess.psess;
            if cx.trace_macros() {
                let msg =
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expanding `{0}! {{ {1} }}`",
                                    name, pprust::tts_to_string(&arg)))
                        });
                trace_macros_note(&mut cx.expansions, sp, msg);
            }
            let try_success_result =
                try_match_macro(psess, name, &arg, rules, &mut NoopTracker);
            match try_success_result {
                Ok((rule_index, rule, named_matches)) => {
                    let MacroRule::Func { lhs, rhs, .. } =
                        rule else {
                            {
                                ::core::panicking::panic_fmt(format_args!("try_match_macro returned non-func rule"));
                            };
                        };
                    let mbe::TokenTree::Delimited(rhs_span, _, rhs) =
                        rhs else { cx.dcx().span_bug(sp, "malformed macro rhs"); };
                    let arm_span = rhs_span.entire();
                    let id = cx.current_expansion.id;
                    let tts =
                        match transcribe(psess, &named_matches, rhs, *rhs_span,
                                transparency, id) {
                            Ok(tts) => tts,
                            Err(err) => {
                                let guar = err.emit();
                                return DummyResult::any(arm_span, guar);
                            }
                        };
                    if cx.trace_macros() {
                        let msg =
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("to `{0}`",
                                            pprust::tts_to_string(&tts)))
                                });
                        trace_macros_note(&mut cx.expansions, sp, msg);
                    }
                    let is_local = is_defined_in_current_crate(node_id);
                    if is_local {
                        cx.resolver.record_macro_rule_usage(node_id, rule_index);
                    }
                    Box::new(ParserAnyMacro::from_tts(cx, tts, sp, arm_span,
                            is_local, name, rules, lhs))
                }
                Err(CanRetry::No(guar)) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:484",
                                            "rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                            ::tracing_core::__macro_support::Option::Some(484u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                            ::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};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("Will not retry matching as an error was emitted already")
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    DummyResult::any(sp, guar)
                }
                Err(CanRetry::Yes) => {
                    let (span, guar) =
                        failed_to_match_macro(cx.psess(), sp, def_span, name,
                            FailedMacro::Func, &arg, rules, on_unmatched_args);
                    cx.macro_error_and_trace_macros_diag();
                    DummyResult::any(span, guar)
                }
            }
        }
    }
}#[instrument(skip(cx, transparency, arg, rules, on_unmatched_args))]
429fn expand_macro<'cx, 'a: 'cx>(
430    cx: &'cx mut ExtCtxt<'_>,
431    sp: Span,
432    def_span: Span,
433    node_id: NodeId,
434    name: Ident,
435    transparency: Transparency,
436    arg: TokenStream,
437    rules: &'a [MacroRule],
438    on_unmatched_args: Option<&Directive>,
439) -> Box<dyn MacResult + 'cx> {
440    let psess = &cx.sess.psess;
441
442    if cx.trace_macros() {
443        let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
444        trace_macros_note(&mut cx.expansions, sp, msg);
445    }
446
447    // Track nothing for the best performance.
448    let try_success_result = try_match_macro(psess, name, &arg, rules, &mut NoopTracker);
449
450    match try_success_result {
451        Ok((rule_index, rule, named_matches)) => {
452            let MacroRule::Func { lhs, rhs, .. } = rule else {
453                panic!("try_match_macro returned non-func rule");
454            };
455            let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
456                cx.dcx().span_bug(sp, "malformed macro rhs");
457            };
458            let arm_span = rhs_span.entire();
459
460            // rhs has holes ( `$id` and `$(...)` that need filled)
461            let id = cx.current_expansion.id;
462            let tts = match transcribe(psess, &named_matches, rhs, *rhs_span, transparency, id) {
463                Ok(tts) => tts,
464                Err(err) => {
465                    let guar = err.emit();
466                    return DummyResult::any(arm_span, guar);
467                }
468            };
469
470            if cx.trace_macros() {
471                let msg = format!("to `{}`", pprust::tts_to_string(&tts));
472                trace_macros_note(&mut cx.expansions, sp, msg);
473            }
474
475            let is_local = is_defined_in_current_crate(node_id);
476            if is_local {
477                cx.resolver.record_macro_rule_usage(node_id, rule_index);
478            }
479
480            // Let the context choose how to interpret the result. Weird, but useful for X-macros.
481            Box::new(ParserAnyMacro::from_tts(cx, tts, sp, arm_span, is_local, name, rules, lhs))
482        }
483        Err(CanRetry::No(guar)) => {
484            debug!("Will not retry matching as an error was emitted already");
485            DummyResult::any(sp, guar)
486        }
487        Err(CanRetry::Yes) => {
488            // Retry and emit a better error.
489            let (span, guar) = failed_to_match_macro(
490                cx.psess(),
491                sp,
492                def_span,
493                name,
494                FailedMacro::Func,
495                &arg,
496                rules,
497                on_unmatched_args,
498            );
499            cx.macro_error_and_trace_macros_diag();
500            DummyResult::any(span, guar)
501        }
502    }
503}
504
505/// Expands the rules based macro defined by `rules` for a given attribute `args` and `body`.
506#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::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("expand_macro_attr",
                                    "rustc_expand::mbe::macro_rules", ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                    ::tracing_core::__macro_support::Option::Some(506u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&["sp", "def_span",
                                                    "node_id", "name", "safety"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&safety)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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<TokenStream, ErrorGuaranteed> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let psess = &cx.sess.psess;
            let is_local = node_id != DUMMY_NODE_ID;
            if cx.trace_macros() {
                let msg =
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expanding `#[{2}({0})] {1}`",
                                    pprust::tts_to_string(&args), pprust::tts_to_string(&body),
                                    name))
                        });
                trace_macros_note(&mut cx.expansions, sp, msg);
            }
            match try_match_macro_attr(psess, name, &args, &body, rules,
                    &mut NoopTracker) {
                Ok((i, rule, named_matches)) => {
                    let MacroRule::Attr { rhs, unsafe_rule, .. } =
                        rule else {
                            {
                                ::core::panicking::panic_fmt(format_args!("try_macro_match_attr returned non-attr rule"));
                            };
                        };
                    let mbe::TokenTree::Delimited(rhs_span, _, rhs) =
                        rhs else { cx.dcx().span_bug(sp, "malformed macro rhs"); };
                    match (safety, unsafe_rule) {
                        (Safety::Default, false) | (Safety::Unsafe(_), true) => {}
                        (Safety::Default, true) => {
                            cx.dcx().span_err(sp,
                                "unsafe attribute invocation requires `unsafe`");
                        }
                        (Safety::Unsafe(span), false) => {
                            cx.dcx().span_err(span,
                                "unnecessary `unsafe` on safe attribute invocation");
                        }
                        (Safety::Safe(span), _) => {
                            cx.dcx().span_bug(span, "unexpected `safe` keyword");
                        }
                    }
                    let id = cx.current_expansion.id;
                    let tts =
                        transcribe(psess, &named_matches, rhs, *rhs_span,
                                    transparency, id).map_err(|e| e.emit())?;
                    if cx.trace_macros() {
                        let msg =
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("to `{0}`",
                                            pprust::tts_to_string(&tts)))
                                });
                        trace_macros_note(&mut cx.expansions, sp, msg);
                    }
                    if is_local {
                        cx.resolver.record_macro_rule_usage(node_id, i);
                    }
                    Ok(tts)
                }
                Err(CanRetry::No(guar)) => Err(guar),
                Err(CanRetry::Yes) => {
                    let (_, guar) =
                        failed_to_match_macro(cx.psess(), sp, def_span, name,
                            FailedMacro::Attr(&args), &body, rules, on_unmatched_args);
                    cx.trace_macros_diag();
                    Err(guar)
                }
            }
        }
    }
}#[instrument(skip(cx, transparency, args, body, rules, on_unmatched_args))]
507fn expand_macro_attr(
508    cx: &mut ExtCtxt<'_>,
509    sp: Span,
510    def_span: Span,
511    node_id: NodeId,
512    name: Ident,
513    transparency: Transparency,
514    safety: Safety,
515    args: TokenStream,
516    body: TokenStream,
517    rules: &[MacroRule],
518    on_unmatched_args: Option<&Directive>,
519) -> Result<TokenStream, ErrorGuaranteed> {
520    let psess = &cx.sess.psess;
521    // Macros defined in the current crate have a real node id,
522    // whereas macros from an external crate have a dummy id.
523    let is_local = node_id != DUMMY_NODE_ID;
524
525    if cx.trace_macros() {
526        let msg = format!(
527            "expanding `#[{name}({})] {}`",
528            pprust::tts_to_string(&args),
529            pprust::tts_to_string(&body),
530        );
531        trace_macros_note(&mut cx.expansions, sp, msg);
532    }
533
534    // Track nothing for the best performance.
535    match try_match_macro_attr(psess, name, &args, &body, rules, &mut NoopTracker) {
536        Ok((i, rule, named_matches)) => {
537            let MacroRule::Attr { rhs, unsafe_rule, .. } = rule else {
538                panic!("try_macro_match_attr returned non-attr rule");
539            };
540            let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
541                cx.dcx().span_bug(sp, "malformed macro rhs");
542            };
543
544            match (safety, unsafe_rule) {
545                (Safety::Default, false) | (Safety::Unsafe(_), true) => {}
546                (Safety::Default, true) => {
547                    cx.dcx().span_err(sp, "unsafe attribute invocation requires `unsafe`");
548                }
549                (Safety::Unsafe(span), false) => {
550                    cx.dcx().span_err(span, "unnecessary `unsafe` on safe attribute invocation");
551                }
552                (Safety::Safe(span), _) => {
553                    cx.dcx().span_bug(span, "unexpected `safe` keyword");
554                }
555            }
556
557            let id = cx.current_expansion.id;
558            let tts = transcribe(psess, &named_matches, rhs, *rhs_span, transparency, id)
559                .map_err(|e| e.emit())?;
560
561            if cx.trace_macros() {
562                let msg = format!("to `{}`", pprust::tts_to_string(&tts));
563                trace_macros_note(&mut cx.expansions, sp, msg);
564            }
565
566            if is_local {
567                cx.resolver.record_macro_rule_usage(node_id, i);
568            }
569
570            Ok(tts)
571        }
572        Err(CanRetry::No(guar)) => Err(guar),
573        Err(CanRetry::Yes) => {
574            // Retry and emit a better error.
575            let (_, guar) = failed_to_match_macro(
576                cx.psess(),
577                sp,
578                def_span,
579                name,
580                FailedMacro::Attr(&args),
581                &body,
582                rules,
583                on_unmatched_args,
584            );
585            cx.trace_macros_diag();
586            Err(guar)
587        }
588    }
589}
590
591pub(super) enum CanRetry {
592    Yes,
593    /// We are not allowed to retry macro expansion as a fatal error has been emitted already.
594    No(ErrorGuaranteed),
595}
596
597/// Try expanding the macro. Returns the index of the successful arm and its named_matches if it was successful,
598/// and nothing if it failed. On failure, it's the callers job to use `track` accordingly to record all errors
599/// correctly.
600#[allow(clippy :: suspicious_else_formatting)]
{
    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("try_match_macro",
                                    "rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                    ::tracing_core::__macro_support::Option::Some(600u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&["name", "tracking"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&display(&T::description())
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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<(usize, &'matcher MacroRule, NamedMatches),
                    CanRetry> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let parser = parser_from_cx(psess, arg.clone(), T::recovery());
            let mut tt_parser = TtParser::new();
            for (i, rule) in rules.iter().enumerate() {
                let MacroRule::Func { lhs, .. } = rule else { continue };
                let _tracing_span =
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("Matching arm",
                                            "rustc_expand::mbe::macro_rules", ::tracing::Level::TRACE,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                            ::tracing_core::__macro_support::Option::Some(632u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                            ::tracing_core::field::FieldSet::new(&["i"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::SPAN)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let mut interest = ::tracing::subscriber::Interest::never();
                        if ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::TRACE <=
                                            ::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};
                                        let mut iter = meta.fields().iter();
                                        meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&display(&i) as
                                                                    &dyn Value))])
                                    })
                        } else {
                            let span =
                                ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                            {};
                            span
                        }
                    };
                let mut gated_spans_snapshot =
                    mem::take(&mut *psess.gated_spans.spans.borrow_mut());
                track.prepare(WhichMatcher::FOR_FUNC);
                let result =
                    tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, track);
                track.after_arm(&result);
                match result {
                    Success(named_matches) => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:646",
                                                "rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                                ::tracing_core::__macro_support::Option::Some(646u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                                ::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};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("Parsed arm successfully")
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        psess.gated_spans.merge(gated_spans_snapshot);
                        return Ok((i, rule, named_matches));
                    }
                    Failure => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:654",
                                                "rustc_expand::mbe::macro_rules", ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                                ::tracing_core::__macro_support::Option::Some(654u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::TRACE <=
                                            ::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};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("Failed to match arm, trying the next one")
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                    }
                    Ambiguity => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:658",
                                                "rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                                ::tracing_core::__macro_support::Option::Some(658u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                                ::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};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("Fatal error occurred during matching")
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        return Err(CanRetry::Yes);
                    }
                    ErrorReported(guarantee) => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_expand/src/mbe/macro_rules.rs:663",
                                                "rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                                ::tracing_core::__macro_support::Option::Some(663u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                                ::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};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("Fatal error occurred and was reported during matching")
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        return Err(CanRetry::No(guarantee));
                    }
                }
                mem::swap(&mut gated_spans_snapshot,
                    &mut psess.gated_spans.spans.borrow_mut());
            }
            Err(CanRetry::Yes)
        }
    }
}#[instrument(level = "debug", skip(psess, arg, rules, track), fields(tracking = %T::description()))]
601pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>(
602    psess: &ParseSess,
603    name: Ident,
604    arg: &TokenStream,
605    rules: &'matcher [MacroRule],
606    track: &mut T,
607) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
608    // We create a base parser that can be used for the "black box" parts.
609    // Every iteration needs a fresh copy of that parser. However, the parser
610    // is not mutated on many of the iterations, particularly when dealing with
611    // macros like this:
612    //
613    // macro_rules! foo {
614    //     ("a") => (A);
615    //     ("b") => (B);
616    //     ("c") => (C);
617    //     // ... etc. (maybe hundreds more)
618    // }
619    //
620    // as seen in the `html5ever` benchmark. We use a `Cow` so that the base
621    // parser is only cloned when necessary (upon mutation). Furthermore, we
622    // reinitialize the `Cow` with the base parser at the start of every
623    // iteration, so that any mutated parsers are not reused. This is all quite
624    // hacky, but speeds up the `html5ever` benchmark significantly. (Issue
625    // 68836 suggests a more comprehensive but more complex change to deal with
626    // this situation.)
627    let parser = parser_from_cx(psess, arg.clone(), T::recovery());
628    // Try each arm's matchers.
629    let mut tt_parser = TtParser::new();
630    for (i, rule) in rules.iter().enumerate() {
631        let MacroRule::Func { lhs, .. } = rule else { continue };
632        let _tracing_span = trace_span!("Matching arm", %i);
633
634        // Take a snapshot of the state of pre-expansion gating at this point.
635        // This is used so that if a matcher is not `Success(..)`ful,
636        // then the spans which became gated when parsing the unsuccessful matcher
637        // are not recorded. On the first `Success(..)`ful matcher, the spans are merged.
638        let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
639
640        track.prepare(WhichMatcher::FOR_FUNC);
641        let result = tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, track);
642        track.after_arm(&result);
643
644        match result {
645            Success(named_matches) => {
646                debug!("Parsed arm successfully");
647                // The matcher was `Success(..)`ful.
648                // Merge the gated spans from parsing the matcher with the preexisting ones.
649                psess.gated_spans.merge(gated_spans_snapshot);
650
651                return Ok((i, rule, named_matches));
652            }
653            Failure => {
654                trace!("Failed to match arm, trying the next one");
655                // Try the next arm.
656            }
657            Ambiguity => {
658                debug!("Fatal error occurred during matching");
659                // We haven't emitted an error yet, so we can retry.
660                return Err(CanRetry::Yes);
661            }
662            ErrorReported(guarantee) => {
663                debug!("Fatal error occurred and was reported during matching");
664                // An error has been reported already, we cannot retry as that would cause duplicate errors.
665                return Err(CanRetry::No(guarantee));
666            }
667        }
668
669        // The matcher was not `Success(..)`ful.
670        // Restore to the state before snapshotting and maybe try again.
671        mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut());
672    }
673
674    Err(CanRetry::Yes)
675}
676
677/// Try expanding the macro attribute. Returns the index of the successful arm and its
678/// named_matches if it was successful, and nothing if it failed. On failure, it's the caller's job
679/// to use `track` accordingly to record all errors correctly.
680#[allow(clippy :: suspicious_else_formatting)]
{
    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("try_match_macro_attr",
                                    "rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                    ::tracing_core::__macro_support::Option::Some(680u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&["name", "tracking"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&display(&T::description())
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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<(usize, &'matcher MacroRule, NamedMatches),
                    CanRetry> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let args_parser =
                parser_from_cx(psess, attr_args.clone(), T::recovery());
            let body_parser =
                parser_from_cx(psess, attr_body.clone(), T::recovery());
            let mut tt_parser = TtParser::new();
            for (i, rule) in rules.iter().enumerate() {
                let MacroRule::Attr { args, body, .. } =
                    rule else { continue };
                let mut gated_spans_snapshot =
                    mem::take(&mut *psess.gated_spans.spans.borrow_mut());
                track.prepare(WhichMatcher::Args);
                let result =
                    tt_parser.parse_tt(&mut Cow::Borrowed(&args_parser), args,
                        track);
                track.after_arm(&result);
                let mut named_matches =
                    match result {
                        Success(named_matches) => named_matches,
                        Failure => {
                            mem::swap(&mut gated_spans_snapshot,
                                &mut psess.gated_spans.spans.borrow_mut());
                            continue;
                        }
                        Ambiguity => return Err(CanRetry::Yes),
                        ErrorReported(guar) => return Err(CanRetry::No(guar)),
                    };
                track.prepare(WhichMatcher::Body);
                let result =
                    tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body,
                        track);
                track.after_arm(&result);
                match result {
                    Success(body_named_matches) => {
                        psess.gated_spans.merge(gated_spans_snapshot);

                        #[allow(rustc::potential_query_instability)]
                        named_matches.extend(body_named_matches);
                        return Ok((i, rule, named_matches));
                    }
                    Failure => {
                        mem::swap(&mut gated_spans_snapshot,
                            &mut psess.gated_spans.spans.borrow_mut())
                    }
                    Ambiguity => return Err(CanRetry::Yes),
                    ErrorReported(guar) => return Err(CanRetry::No(guar)),
                }
            }
            Err(CanRetry::Yes)
        }
    }
}#[instrument(level = "debug", skip(psess, attr_args, attr_body, rules, track), fields(tracking = %T::description()))]
681pub(super) fn try_match_macro_attr<'matcher, T: Tracker<'matcher>>(
682    psess: &ParseSess,
683    name: Ident,
684    attr_args: &TokenStream,
685    attr_body: &TokenStream,
686    rules: &'matcher [MacroRule],
687    track: &mut T,
688) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
689    // This uses the same strategy as `try_match_macro`
690    let args_parser = parser_from_cx(psess, attr_args.clone(), T::recovery());
691    let body_parser = parser_from_cx(psess, attr_body.clone(), T::recovery());
692    let mut tt_parser = TtParser::new();
693    for (i, rule) in rules.iter().enumerate() {
694        let MacroRule::Attr { args, body, .. } = rule else { continue };
695
696        let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
697
698        track.prepare(WhichMatcher::Args);
699        let result = tt_parser.parse_tt(&mut Cow::Borrowed(&args_parser), args, track);
700        track.after_arm(&result);
701
702        let mut named_matches = match result {
703            Success(named_matches) => named_matches,
704            Failure => {
705                mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut());
706                continue;
707            }
708            Ambiguity => return Err(CanRetry::Yes),
709            ErrorReported(guar) => return Err(CanRetry::No(guar)),
710        };
711
712        track.prepare(WhichMatcher::Body);
713        let result = tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body, track);
714        track.after_arm(&result);
715
716        match result {
717            Success(body_named_matches) => {
718                psess.gated_spans.merge(gated_spans_snapshot);
719                #[allow(rustc::potential_query_instability)]
720                named_matches.extend(body_named_matches);
721                return Ok((i, rule, named_matches));
722            }
723            Failure => {
724                mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut())
725            }
726            Ambiguity => return Err(CanRetry::Yes),
727            ErrorReported(guar) => return Err(CanRetry::No(guar)),
728        }
729    }
730
731    Err(CanRetry::Yes)
732}
733
734/// Try expanding the macro derive. Returns the index of the successful arm and its
735/// named_matches if it was successful, and nothing if it failed. On failure, it's the caller's job
736/// to use `track` accordingly to record all errors correctly.
737#[allow(clippy :: suspicious_else_formatting)]
{
    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("try_match_macro_derive",
                                    "rustc_expand::mbe::macro_rules", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                    ::tracing_core::__macro_support::Option::Some(737u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&["name", "tracking"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&display(&T::description())
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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<(usize, &'matcher MacroRule, NamedMatches),
                    CanRetry> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let body_parser =
                parser_from_cx(psess, body.clone(), T::recovery());
            let mut tt_parser = TtParser::new();
            for (i, rule) in rules.iter().enumerate() {
                let MacroRule::Derive { body, .. } = rule else { continue };
                let mut gated_spans_snapshot =
                    mem::take(&mut *psess.gated_spans.spans.borrow_mut());
                track.prepare(WhichMatcher::FOR_DERIVE);
                let result =
                    tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body,
                        track);
                track.after_arm(&result);
                match result {
                    Success(named_matches) => {
                        psess.gated_spans.merge(gated_spans_snapshot);
                        return Ok((i, rule, named_matches));
                    }
                    Failure => {
                        mem::swap(&mut gated_spans_snapshot,
                            &mut psess.gated_spans.spans.borrow_mut())
                    }
                    Ambiguity => return Err(CanRetry::Yes),
                    ErrorReported(guar) => return Err(CanRetry::No(guar)),
                }
            }
            Err(CanRetry::Yes)
        }
    }
}#[instrument(level = "debug", skip(psess, body, rules, track), fields(tracking = %T::description()))]
738pub(super) fn try_match_macro_derive<'matcher, T: Tracker<'matcher>>(
739    psess: &ParseSess,
740    name: Ident,
741    body: &TokenStream,
742    rules: &'matcher [MacroRule],
743    track: &mut T,
744) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
745    // This uses the same strategy as `try_match_macro`
746    let body_parser = parser_from_cx(psess, body.clone(), T::recovery());
747    let mut tt_parser = TtParser::new();
748    for (i, rule) in rules.iter().enumerate() {
749        let MacroRule::Derive { body, .. } = rule else { continue };
750
751        let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
752
753        track.prepare(WhichMatcher::FOR_DERIVE);
754        let result = tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body, track);
755        track.after_arm(&result);
756
757        match result {
758            Success(named_matches) => {
759                psess.gated_spans.merge(gated_spans_snapshot);
760                return Ok((i, rule, named_matches));
761            }
762            Failure => {
763                mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut())
764            }
765            Ambiguity => return Err(CanRetry::Yes),
766            ErrorReported(guar) => return Err(CanRetry::No(guar)),
767        }
768    }
769
770    Err(CanRetry::Yes)
771}
772
773/// Converts a macro item into a syntax extension.
774pub fn compile_declarative_macro(
775    sess: &Session,
776    features: &Features,
777    macro_def: &ast::MacroDef,
778    ident: Ident,
779    attrs: &[hir::Attribute],
780    span: Span,
781    node_id: NodeId,
782    edition: Edition,
783) -> SyntaxExtension {
784    let mk_syn_ext = |kind| {
785        let is_local = is_defined_in_current_crate(node_id);
786        SyntaxExtension::new(sess, kind, span, Vec::new(), edition, ident.name, attrs, is_local)
787    };
788    let dummy_syn_ext = |guar| mk_syn_ext(SyntaxExtensionKind::Bang(Arc::new(DummyBang(guar))));
789
790    let macro_rules = macro_def.macro_rules;
791    let exp_sep = if macro_rules { ::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: ::rustc_parse::parser::token_type::TokenType::Semi,
}exp!(Semi) } else { ::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma) };
792
793    let body = macro_def.body.tokens.clone();
794    let mut p = Parser::new(&sess.psess, body, rustc_parse::MACRO_ARGUMENTS);
795
796    // Don't abort iteration early, so that multiple errors can be reported. We only abort early on
797    // parse failures we can't recover from.
798    let mut guar = None;
799    let mut check_emission = |ret: Result<(), ErrorGuaranteed>| guar = guar.or(ret.err());
800
801    let mut kinds = MacroKinds::empty();
802    let mut rules = Vec::new();
803
804    while p.token != token::Eof {
805        let unsafe_rule = p.eat_keyword_noexpect(kw::Unsafe);
806        let unsafe_keyword_span = p.prev_token.span;
807        if unsafe_rule && let Some(guar) = check_no_eof(sess, &p, "expected `attr`") {
808            return dummy_syn_ext(guar);
809        }
810        let (args, is_derive) = if p.eat_keyword_noexpect(sym::attr) {
811            kinds |= MacroKinds::ATTR;
812            if !features.macro_attr() {
813                feature_err(sess, sym::macro_attr, span, "`macro_rules!` attributes are unstable")
814                    .emit();
815            }
816            if let Some(guar) = check_no_eof(sess, &p, "expected macro attr args") {
817                return dummy_syn_ext(guar);
818            }
819            let args = p.parse_token_tree();
820            check_args_parens(sess, sym::attr, &args);
821            let args = parse_one_tt(args, RulePart::Pattern, sess, node_id, features, edition);
822            check_emission(check_lhs(sess, features, node_id, &args));
823            if let Some(guar) = check_no_eof(sess, &p, "expected macro attr body") {
824                return dummy_syn_ext(guar);
825            }
826            (Some(args), false)
827        } else if p.eat_keyword_noexpect(sym::derive) {
828            kinds |= MacroKinds::DERIVE;
829            let derive_keyword_span = p.prev_token.span;
830            if !features.macro_derive() {
831                feature_err(sess, sym::macro_derive, span, "`macro_rules!` derives are unstable")
832                    .emit();
833            }
834            if unsafe_rule {
835                sess.dcx()
836                    .span_err(unsafe_keyword_span, "`unsafe` is only supported on `attr` rules");
837            }
838            if let Some(guar) = check_no_eof(sess, &p, "expected `()` after `derive`") {
839                return dummy_syn_ext(guar);
840            }
841            let args = p.parse_token_tree();
842            check_args_parens(sess, sym::derive, &args);
843            let args_empty_result = check_args_empty(sess, &args);
844            let args_not_empty = args_empty_result.is_err();
845            check_emission(args_empty_result);
846            if let Some(guar) = check_no_eof(sess, &p, "expected macro derive body") {
847                return dummy_syn_ext(guar);
848            }
849            // If the user has `=>` right after the `()`, they might have forgotten the empty
850            // parentheses.
851            if p.token == token::FatArrow {
852                let mut err = sess
853                    .dcx()
854                    .struct_span_err(p.token.span, "expected macro derive body, got `=>`");
855                if args_not_empty {
856                    err.span_label(derive_keyword_span, "need `()` after this `derive`");
857                }
858                return dummy_syn_ext(err.emit());
859            }
860            (None, true)
861        } else {
862            kinds |= MacroKinds::BANG;
863            if unsafe_rule {
864                sess.dcx()
865                    .span_err(unsafe_keyword_span, "`unsafe` is only supported on `attr` rules");
866            }
867            (None, false)
868        };
869        let lhs_tt = p.parse_token_tree();
870        let lhs_tt = parse_one_tt(lhs_tt, RulePart::Pattern, sess, node_id, features, edition);
871        check_emission(check_lhs(sess, features, node_id, &lhs_tt));
872        if let Err(e) = p.expect(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::FatArrow,
    token_type: ::rustc_parse::parser::token_type::TokenType::FatArrow,
}exp!(FatArrow)) {
873            return dummy_syn_ext(e.emit());
874        }
875        if let Some(guar) = check_no_eof(sess, &p, "expected right-hand side of macro rule") {
876            return dummy_syn_ext(guar);
877        }
878        let rhs = p.parse_token_tree();
879        let rhs = parse_one_tt(rhs, RulePart::Body, sess, node_id, features, edition);
880        check_emission(check_rhs(sess, &rhs));
881        check_emission(check_meta_variables(&sess.psess, node_id, args.as_ref(), &lhs_tt, &rhs));
882        let lhs_span = lhs_tt.span();
883        // Convert the lhs into `MatcherLoc` form, which is better for doing the
884        // actual matching.
885        let mbe::TokenTree::Delimited(.., delimited) = lhs_tt else {
886            return dummy_syn_ext(guar.unwrap());
887        };
888        let lhs = mbe::macro_parser::compute_locs(&delimited.tts);
889        if let Some(args) = args {
890            let args_span = args.span();
891            let mbe::TokenTree::Delimited(.., delimited) = args else {
892                return dummy_syn_ext(guar.unwrap());
893            };
894            let args = mbe::macro_parser::compute_locs(&delimited.tts);
895            let body_span = lhs_span;
896            rules.push(MacroRule::Attr { unsafe_rule, args, args_span, body: lhs, body_span, rhs });
897        } else if is_derive {
898            rules.push(MacroRule::Derive { body: lhs, body_span: lhs_span, rhs });
899        } else {
900            rules.push(MacroRule::Func { lhs, lhs_span, rhs });
901        }
902        if p.token == token::Eof {
903            break;
904        }
905        if let Err(e) = p.expect(exp_sep) {
906            return dummy_syn_ext(e.emit());
907        }
908    }
909
910    if rules.is_empty() {
911        let guar = sess.dcx().span_err(span, "macros must contain at least one rule");
912        return dummy_syn_ext(guar);
913    }
914    if !!kinds.is_empty() {
    ::core::panicking::panic("assertion failed: !kinds.is_empty()")
};assert!(!kinds.is_empty());
915
916    let transparency = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(RustcMacroTransparency(x)) => {
                    break 'done Some(*x);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcMacroTransparency(x) => *x)
917        .unwrap_or(Transparency::fallback(macro_rules));
918
919    if let Some(guar) = guar {
920        // To avoid warning noise, only consider the rules of this
921        // macro for the lint, if all rules are valid.
922        return dummy_syn_ext(guar);
923    }
924
925    let on_unmatched_args = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(OnUnmatchedArgs { directive, ..
                    }) => {
                    break 'done Some(directive.clone());
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(
926        attrs,
927        OnUnmatchedArgs { directive, .. } => directive.clone()
928    )
929    .flatten()
930    .map(|directive| *directive);
931
932    let exp = MacroRulesMacroExpander {
933        name: ident,
934        kinds,
935        span,
936        node_id,
937        on_unmatched_args,
938        transparency,
939        rules,
940        macro_rules,
941    };
942    mk_syn_ext(SyntaxExtensionKind::MacroRules(Arc::new(exp)))
943}
944
945fn check_no_eof(sess: &Session, p: &Parser<'_>, msg: &'static str) -> Option<ErrorGuaranteed> {
946    if p.token == token::Eof {
947        let err_sp = p.token.span.shrink_to_hi();
948        let guar = sess
949            .dcx()
950            .struct_span_err(err_sp, "macro definition ended unexpectedly")
951            .with_span_label(err_sp, msg)
952            .emit();
953        return Some(guar);
954    }
955    None
956}
957
958fn check_args_parens(sess: &Session, rule_kw: Symbol, args: &tokenstream::TokenTree) {
959    // This does not handle the non-delimited case; that gets handled separately by `check_lhs`.
960    if let tokenstream::TokenTree::Delimited(dspan, _, delim, _) = args
961        && *delim != Delimiter::Parenthesis
962    {
963        sess.dcx().emit_err(diagnostics::MacroArgsBadDelim {
964            span: dspan.entire(),
965            sugg: diagnostics::MacroArgsBadDelimSugg { open: dspan.open, close: dspan.close },
966            rule_kw,
967        });
968    }
969}
970
971fn check_args_empty(sess: &Session, args: &tokenstream::TokenTree) -> Result<(), ErrorGuaranteed> {
972    match args {
973        tokenstream::TokenTree::Delimited(.., delimited) if delimited.is_empty() => Ok(()),
974        _ => {
975            let msg = "`derive` rules do not accept arguments; `derive` must be followed by `()`";
976            Err(sess.dcx().span_err(args.span(), msg))
977        }
978    }
979}
980
981fn check_lhs(
982    sess: &Session,
983    features: &Features,
984    node_id: NodeId,
985    lhs: &mbe::TokenTree,
986) -> Result<(), ErrorGuaranteed> {
987    let e1 = check_lhs_nt_follows(sess, features, node_id, lhs);
988    let e2 = check_lhs_no_empty_seq(sess, slice::from_ref(lhs));
989    e1.and(e2)
990}
991
992fn check_lhs_nt_follows(
993    sess: &Session,
994    features: &Features,
995    node_id: NodeId,
996    lhs: &mbe::TokenTree,
997) -> Result<(), ErrorGuaranteed> {
998    // lhs is going to be like TokenTree::Delimited(...), where the
999    // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
1000    if let mbe::TokenTree::Delimited(.., delimited) = lhs {
1001        check_matcher(sess, features, node_id, &delimited.tts)
1002    } else {
1003        let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
1004        Err(sess.dcx().span_err(lhs.span(), msg))
1005    }
1006}
1007
1008fn is_empty_token_tree(sess: &Session, seq: &mbe::SequenceRepetition) -> bool {
1009    if seq.separator.is_some() {
1010        false
1011    } else {
1012        let mut is_empty = true;
1013        let mut iter = seq.tts.iter().peekable();
1014        while let Some(tt) = iter.next() {
1015            match tt {
1016                mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. } => {}
1017                mbe::TokenTree::Token(t @ Token { kind: DocComment(..), .. }) => {
1018                    let mut now = t;
1019                    while let Some(&mbe::TokenTree::Token(
1020                        next @ Token { kind: DocComment(..), .. },
1021                    )) = iter.peek()
1022                    {
1023                        now = next;
1024                        iter.next();
1025                    }
1026                    let span = t.span.to(now.span);
1027                    sess.dcx().span_note(span, "doc comments are ignored in matcher position");
1028                }
1029                mbe::TokenTree::Sequence(_, sub_seq)
1030                    if (sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
1031                        || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne) => {}
1032                _ => is_empty = false,
1033            }
1034        }
1035        is_empty
1036    }
1037}
1038
1039/// Checks if a `vis` nonterminal fragment is unnecessarily wrapped in an optional repetition.
1040///
1041/// When a `vis` fragment (which can already be empty) is wrapped in `$(...)?`,
1042/// this suggests removing the redundant repetition syntax since it provides no additional benefit.
1043fn check_redundant_vis_repetition(
1044    err: &mut Diag<'_>,
1045    sess: &Session,
1046    seq: &SequenceRepetition,
1047    span: &DelimSpan,
1048) {
1049    if seq.kleene.op == KleeneOp::ZeroOrOne
1050        && #[allow(non_exhaustive_omitted_patterns)] match seq.tts.first() {
    Some(mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. }) =>
        true,
    _ => false,
}matches!(
1051            seq.tts.first(),
1052            Some(mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. })
1053        )
1054    {
1055        err.note("a `vis` fragment can already be empty");
1056        err.multipart_suggestion(
1057            "remove the `$(` and `)?`",
1058            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(sess.source_map().span_extend_to_prev_char_before(span.open, '$',
                        true), "".to_string()),
                (span.close.with_hi(seq.kleene.span.hi()), "".to_string())]))vec![
1059                (
1060                    sess.source_map().span_extend_to_prev_char_before(span.open, '$', true),
1061                    "".to_string(),
1062                ),
1063                (span.close.with_hi(seq.kleene.span.hi()), "".to_string()),
1064            ],
1065            Applicability::MaybeIncorrect,
1066        );
1067    }
1068}
1069
1070/// Checks that the lhs contains no repetition which could match an empty token
1071/// tree, because then the matcher would hang indefinitely.
1072fn check_lhs_no_empty_seq(sess: &Session, tts: &[mbe::TokenTree]) -> Result<(), ErrorGuaranteed> {
1073    use mbe::TokenTree;
1074    for tt in tts {
1075        match tt {
1076            TokenTree::Token(..)
1077            | TokenTree::MetaVar(..)
1078            | TokenTree::MetaVarDecl { .. }
1079            | TokenTree::MetaVarExpr(..) => (),
1080            TokenTree::Delimited(.., del) => check_lhs_no_empty_seq(sess, &del.tts)?,
1081            TokenTree::Sequence(span, seq) => {
1082                if is_empty_token_tree(sess, seq) {
1083                    let sp = span.entire();
1084                    let mut err =
1085                        sess.dcx().struct_span_err(sp, "repetition matches empty token tree");
1086                    check_redundant_vis_repetition(&mut err, sess, seq, span);
1087                    return Err(err.emit());
1088                }
1089                check_lhs_no_empty_seq(sess, &seq.tts)?
1090            }
1091        }
1092    }
1093
1094    Ok(())
1095}
1096
1097fn check_rhs(sess: &Session, rhs: &mbe::TokenTree) -> Result<(), ErrorGuaranteed> {
1098    match *rhs {
1099        mbe::TokenTree::Delimited(..) => Ok(()),
1100        _ => Err(sess.dcx().span_err(rhs.span(), "macro rhs must be delimited")),
1101    }
1102}
1103
1104fn check_matcher(
1105    sess: &Session,
1106    features: &Features,
1107    node_id: NodeId,
1108    matcher: &[mbe::TokenTree],
1109) -> Result<(), ErrorGuaranteed> {
1110    let first_sets = FirstSets::new(matcher);
1111    let empty_suffix = TokenSet::empty();
1112    check_matcher_core(sess, features, node_id, &first_sets, matcher, &empty_suffix)?;
1113    Ok(())
1114}
1115
1116fn has_compile_error_macro(rhs: &mbe::TokenTree) -> bool {
1117    match rhs {
1118        mbe::TokenTree::Delimited(.., d) => {
1119            let has_compile_error = d.tts.array_windows::<3>().any(|[ident, bang, args]| {
1120                if let mbe::TokenTree::Token(ident) = ident
1121                    && let TokenKind::Ident(ident, _) = ident.kind
1122                    && ident == sym::compile_error
1123                    && let mbe::TokenTree::Token(bang) = bang
1124                    && let TokenKind::Bang = bang.kind
1125                    && let mbe::TokenTree::Delimited(.., del) = args
1126                    && !del.delim.skip()
1127                {
1128                    true
1129                } else {
1130                    false
1131                }
1132            });
1133            if has_compile_error { true } else { d.tts.iter().any(has_compile_error_macro) }
1134        }
1135        _ => false,
1136    }
1137}
1138
1139// `The FirstSets` for a matcher is a mapping from subsequences in the
1140// matcher to the FIRST set for that subsequence.
1141//
1142// This mapping is partially precomputed via a backwards scan over the
1143// token trees of the matcher, which provides a mapping from each
1144// repetition sequence to its *first* set.
1145//
1146// (Hypothetically, sequences should be uniquely identifiable via their
1147// spans, though perhaps that is false, e.g., for macro-generated macros
1148// that do not try to inject artificial span information. My plan is
1149// to try to catch such cases ahead of time and not include them in
1150// the precomputed mapping.)
1151struct FirstSets<'tt> {
1152    // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
1153    // span in the original matcher to the First set for the inner sequence `tt ...`.
1154    //
1155    // If two sequences have the same span in a matcher, then map that
1156    // span to None (invalidating the mapping here and forcing the code to
1157    // use a slow path).
1158    first: FxHashMap<Span, Option<TokenSet<'tt>>>,
1159}
1160
1161impl<'tt> FirstSets<'tt> {
1162    fn new(tts: &'tt [mbe::TokenTree]) -> FirstSets<'tt> {
1163        use mbe::TokenTree;
1164
1165        let mut sets = FirstSets { first: FxHashMap::default() };
1166        build_recur(&mut sets, tts);
1167        return sets;
1168
1169        // walks backward over `tts`, returning the FIRST for `tts`
1170        // and updating `sets` at the same time for all sequence
1171        // substructure we find within `tts`.
1172        fn build_recur<'tt>(sets: &mut FirstSets<'tt>, tts: &'tt [TokenTree]) -> TokenSet<'tt> {
1173            let mut first = TokenSet::empty();
1174            for tt in tts.iter().rev() {
1175                match tt {
1176                    TokenTree::Token(..)
1177                    | TokenTree::MetaVar(..)
1178                    | TokenTree::MetaVarDecl { .. }
1179                    | TokenTree::MetaVarExpr(..) => {
1180                        first.replace_with(TtHandle::TtRef(tt));
1181                    }
1182                    TokenTree::Delimited(span, _, delimited) => {
1183                        build_recur(sets, &delimited.tts);
1184                        first.replace_with(TtHandle::from_token_kind(
1185                            delimited.delim.as_open_token_kind(),
1186                            span.open,
1187                        ));
1188                    }
1189                    TokenTree::Sequence(sp, seq_rep) => {
1190                        let subfirst = build_recur(sets, &seq_rep.tts);
1191
1192                        match sets.first.entry(sp.entire()) {
1193                            Entry::Vacant(vac) => {
1194                                vac.insert(Some(subfirst.clone()));
1195                            }
1196                            Entry::Occupied(mut occ) => {
1197                                // if there is already an entry, then a span must have collided.
1198                                // This should not happen with typical macro_rules macros,
1199                                // but syntax extensions need not maintain distinct spans,
1200                                // so distinct syntax trees can be assigned the same span.
1201                                // In such a case, the map cannot be trusted; so mark this
1202                                // entry as unusable.
1203                                occ.insert(None);
1204                            }
1205                        }
1206
1207                        // If the sequence contents can be empty, then the first
1208                        // token could be the separator token itself.
1209
1210                        if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
1211                            first.add_one_maybe(TtHandle::from_token(*sep));
1212                        }
1213
1214                        // Reverse scan: Sequence comes before `first`.
1215                        if subfirst.maybe_empty
1216                            || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
1217                            || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
1218                        {
1219                            // If sequence is potentially empty, then
1220                            // union them (preserving first emptiness).
1221                            first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
1222                        } else {
1223                            // Otherwise, sequence guaranteed
1224                            // non-empty; replace first.
1225                            first = subfirst;
1226                        }
1227                    }
1228                }
1229            }
1230
1231            first
1232        }
1233    }
1234
1235    // walks forward over `tts` until all potential FIRST tokens are
1236    // identified.
1237    fn first(&self, tts: &'tt [mbe::TokenTree]) -> TokenSet<'tt> {
1238        use mbe::TokenTree;
1239
1240        let mut first = TokenSet::empty();
1241        for tt in tts.iter() {
1242            if !first.maybe_empty {
    ::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1243            match tt {
1244                TokenTree::Token(..)
1245                | TokenTree::MetaVar(..)
1246                | TokenTree::MetaVarDecl { .. }
1247                | TokenTree::MetaVarExpr(..) => {
1248                    first.add_one(TtHandle::TtRef(tt));
1249                    return first;
1250                }
1251                TokenTree::Delimited(span, _, delimited) => {
1252                    first.add_one(TtHandle::from_token_kind(
1253                        delimited.delim.as_open_token_kind(),
1254                        span.open,
1255                    ));
1256                    return first;
1257                }
1258                TokenTree::Sequence(sp, seq_rep) => {
1259                    let subfirst_owned;
1260                    let subfirst = match self.first.get(&sp.entire()) {
1261                        Some(Some(subfirst)) => subfirst,
1262                        Some(&None) => {
1263                            subfirst_owned = self.first(&seq_rep.tts);
1264                            &subfirst_owned
1265                        }
1266                        None => {
1267                            {
    ::core::panicking::panic_fmt(format_args!("We missed a sequence during FirstSets construction"));
};panic!("We missed a sequence during FirstSets construction");
1268                        }
1269                    };
1270
1271                    // If the sequence contents can be empty, then the first
1272                    // token could be the separator token itself.
1273                    if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
1274                        first.add_one_maybe(TtHandle::from_token(*sep));
1275                    }
1276
1277                    if !first.maybe_empty {
    ::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1278                    first.add_all(subfirst);
1279                    if subfirst.maybe_empty
1280                        || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
1281                        || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
1282                    {
1283                        // Continue scanning for more first
1284                        // tokens, but also make sure we
1285                        // restore empty-tracking state.
1286                        first.maybe_empty = true;
1287                        continue;
1288                    } else {
1289                        return first;
1290                    }
1291                }
1292            }
1293        }
1294
1295        // we only exit the loop if `tts` was empty or if every
1296        // element of `tts` matches the empty sequence.
1297        if !first.maybe_empty {
    ::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1298        first
1299    }
1300}
1301
1302// Most `mbe::TokenTree`s are preexisting in the matcher, but some are defined
1303// implicitly, such as opening/closing delimiters and sequence repetition ops.
1304// This type encapsulates both kinds. It implements `Clone` while avoiding the
1305// need for `mbe::TokenTree` to implement `Clone`.
1306#[derive(#[automatically_derived]
impl<'tt> ::core::fmt::Debug for TtHandle<'tt> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TtHandle::TtRef(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "TtRef",
                    &__self_0),
            TtHandle::Token(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Token",
                    &__self_0),
        }
    }
}Debug)]
1307enum TtHandle<'tt> {
1308    /// This is used in most cases.
1309    TtRef(&'tt mbe::TokenTree),
1310
1311    /// This is only used for implicit token trees. The `mbe::TokenTree` *must*
1312    /// be `mbe::TokenTree::Token`. No other variants are allowed. We store an
1313    /// `mbe::TokenTree` rather than a `Token` so that `get()` can return a
1314    /// `&mbe::TokenTree`.
1315    Token(mbe::TokenTree),
1316}
1317
1318impl<'tt> TtHandle<'tt> {
1319    fn from_token(tok: Token) -> Self {
1320        TtHandle::Token(mbe::TokenTree::Token(tok))
1321    }
1322
1323    fn from_token_kind(kind: TokenKind, span: Span) -> Self {
1324        TtHandle::from_token(Token::new(kind, span))
1325    }
1326
1327    // Get a reference to a token tree.
1328    fn get(&'tt self) -> &'tt mbe::TokenTree {
1329        match self {
1330            TtHandle::TtRef(tt) => tt,
1331            TtHandle::Token(token_tt) => token_tt,
1332        }
1333    }
1334}
1335
1336impl<'tt> PartialEq for TtHandle<'tt> {
1337    fn eq(&self, other: &TtHandle<'tt>) -> bool {
1338        self.get() == other.get()
1339    }
1340}
1341
1342impl<'tt> Clone for TtHandle<'tt> {
1343    fn clone(&self) -> Self {
1344        match self {
1345            TtHandle::TtRef(tt) => TtHandle::TtRef(tt),
1346
1347            // This variant *must* contain a `mbe::TokenTree::Token`, and not
1348            // any other variant of `mbe::TokenTree`.
1349            TtHandle::Token(mbe::TokenTree::Token(tok)) => {
1350                TtHandle::Token(mbe::TokenTree::Token(*tok))
1351            }
1352
1353            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1354        }
1355    }
1356}
1357
1358// A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s
1359// (for macro-by-example syntactic variables). It also carries the
1360// `maybe_empty` flag; that is true if and only if the matcher can
1361// match an empty token sequence.
1362//
1363// The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
1364// which has corresponding FIRST = {$a:expr, c, d}.
1365// Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
1366//
1367// (Notably, we must allow for *-op to occur zero times.)
1368#[derive(#[automatically_derived]
impl<'tt> ::core::clone::Clone for TokenSet<'tt> {
    #[inline]
    fn clone(&self) -> TokenSet<'tt> {
        TokenSet {
            tokens: ::core::clone::Clone::clone(&self.tokens),
            maybe_empty: ::core::clone::Clone::clone(&self.maybe_empty),
        }
    }
}Clone, #[automatically_derived]
impl<'tt> ::core::fmt::Debug for TokenSet<'tt> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "TokenSet",
            "tokens", &self.tokens, "maybe_empty", &&self.maybe_empty)
    }
}Debug)]
1369struct TokenSet<'tt> {
1370    tokens: Vec<TtHandle<'tt>>,
1371    maybe_empty: bool,
1372}
1373
1374impl<'tt> TokenSet<'tt> {
1375    // Returns a set for the empty sequence.
1376    fn empty() -> Self {
1377        TokenSet { tokens: Vec::new(), maybe_empty: true }
1378    }
1379
1380    // Returns the set `{ tok }` for the single-token (and thus
1381    // non-empty) sequence [tok].
1382    fn singleton(tt: TtHandle<'tt>) -> Self {
1383        TokenSet { tokens: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [tt]))vec![tt], maybe_empty: false }
1384    }
1385
1386    // Changes self to be the set `{ tok }`.
1387    // Since `tok` is always present, marks self as non-empty.
1388    fn replace_with(&mut self, tt: TtHandle<'tt>) {
1389        self.tokens.clear();
1390        self.tokens.push(tt);
1391        self.maybe_empty = false;
1392    }
1393
1394    // Changes self to be the empty set `{}`; meant for use when
1395    // the particular token does not matter, but we want to
1396    // record that it occurs.
1397    fn replace_with_irrelevant(&mut self) {
1398        self.tokens.clear();
1399        self.maybe_empty = false;
1400    }
1401
1402    // Adds `tok` to the set for `self`, marking sequence as non-empty.
1403    fn add_one(&mut self, tt: TtHandle<'tt>) {
1404        if !self.tokens.contains(&tt) {
1405            self.tokens.push(tt);
1406        }
1407        self.maybe_empty = false;
1408    }
1409
1410    // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
1411    fn add_one_maybe(&mut self, tt: TtHandle<'tt>) {
1412        if !self.tokens.contains(&tt) {
1413            self.tokens.push(tt);
1414        }
1415    }
1416
1417    // Adds all elements of `other` to this.
1418    //
1419    // (Since this is a set, we filter out duplicates.)
1420    //
1421    // If `other` is potentially empty, then preserves the previous
1422    // setting of the empty flag of `self`. If `other` is guaranteed
1423    // non-empty, then `self` is marked non-empty.
1424    fn add_all(&mut self, other: &Self) {
1425        for tt in &other.tokens {
1426            if !self.tokens.contains(tt) {
1427                self.tokens.push(tt.clone());
1428            }
1429        }
1430        if !other.maybe_empty {
1431            self.maybe_empty = false;
1432        }
1433    }
1434}
1435
1436// Checks that `matcher` is internally consistent and that it
1437// can legally be followed by a token `N`, for all `N` in `follow`.
1438// (If `follow` is empty, then it imposes no constraint on
1439// the `matcher`.)
1440//
1441// Returns the set of NT tokens that could possibly come last in
1442// `matcher`. (If `matcher` matches the empty sequence, then
1443// `maybe_empty` will be set to true.)
1444//
1445// Requires that `first_sets` is pre-computed for `matcher`;
1446// see `FirstSets::new`.
1447fn check_matcher_core<'tt>(
1448    sess: &Session,
1449    features: &Features,
1450    node_id: NodeId,
1451    first_sets: &FirstSets<'tt>,
1452    matcher: &'tt [mbe::TokenTree],
1453    follow: &TokenSet<'tt>,
1454) -> Result<TokenSet<'tt>, ErrorGuaranteed> {
1455    use mbe::TokenTree;
1456
1457    let mut last = TokenSet::empty();
1458
1459    let mut errored = Ok(());
1460
1461    // 2. For each token and suffix  [T, SUFFIX] in M:
1462    // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
1463    // then ensure T can also be followed by any element of FOLLOW.
1464    'each_token: for i in 0..matcher.len() {
1465        let token = &matcher[i];
1466        let suffix = &matcher[i + 1..];
1467
1468        let build_suffix_first = || {
1469            let mut s = first_sets.first(suffix);
1470            if s.maybe_empty {
1471                s.add_all(follow);
1472            }
1473            s
1474        };
1475
1476        // (we build `suffix_first` on demand below; you can tell
1477        // which cases are supposed to fall through by looking for the
1478        // initialization of this variable.)
1479        let suffix_first;
1480
1481        // First, update `last` so that it corresponds to the set
1482        // of NT tokens that might end the sequence `... token`.
1483        match token {
1484            TokenTree::Token(..)
1485            | TokenTree::MetaVar(..)
1486            | TokenTree::MetaVarDecl { .. }
1487            | TokenTree::MetaVarExpr(..) => {
1488                if let TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } = token
1489                    && !features.macro_guard_matcher()
1490                {
1491                    feature_err(
1492                        sess,
1493                        sym::macro_guard_matcher,
1494                        token.span(),
1495                        "`guard` fragments in macro are unstable",
1496                    )
1497                    .emit();
1498                }
1499                if token_can_be_followed_by_any(token) {
1500                    // don't need to track tokens that work with any,
1501                    last.replace_with_irrelevant();
1502                    // ... and don't need to check tokens that can be
1503                    // followed by anything against SUFFIX.
1504                    continue 'each_token;
1505                } else {
1506                    last.replace_with(TtHandle::TtRef(token));
1507                    suffix_first = build_suffix_first();
1508                }
1509            }
1510            TokenTree::Delimited(span, _, d) => {
1511                let my_suffix = TokenSet::singleton(TtHandle::from_token_kind(
1512                    d.delim.as_close_token_kind(),
1513                    span.close,
1514                ));
1515                check_matcher_core(sess, features, node_id, first_sets, &d.tts, &my_suffix)?;
1516                // don't track non NT tokens
1517                last.replace_with_irrelevant();
1518
1519                // also, we don't need to check delimited sequences
1520                // against SUFFIX
1521                continue 'each_token;
1522            }
1523            TokenTree::Sequence(_, seq_rep) => {
1524                suffix_first = build_suffix_first();
1525                // The trick here: when we check the interior, we want
1526                // to include the separator (if any) as a potential
1527                // (but not guaranteed) element of FOLLOW. So in that
1528                // case, we make a temp copy of suffix and stuff
1529                // delimiter in there.
1530                //
1531                // FIXME: Should I first scan suffix_first to see if
1532                // delimiter is already in it before I go through the
1533                // work of cloning it? But then again, this way I may
1534                // get a "tighter" span?
1535                let mut new;
1536                let my_suffix = if let Some(sep) = &seq_rep.separator {
1537                    new = suffix_first.clone();
1538                    new.add_one_maybe(TtHandle::from_token(*sep));
1539                    &new
1540                } else {
1541                    &suffix_first
1542                };
1543
1544                // At this point, `suffix_first` is built, and
1545                // `my_suffix` is some TokenSet that we can use
1546                // for checking the interior of `seq_rep`.
1547                let next = check_matcher_core(
1548                    sess,
1549                    features,
1550                    node_id,
1551                    first_sets,
1552                    &seq_rep.tts,
1553                    my_suffix,
1554                )?;
1555                if next.maybe_empty {
1556                    last.add_all(&next);
1557                } else {
1558                    last = next;
1559                }
1560
1561                // the recursive call to check_matcher_core already ran the 'each_last
1562                // check below, so we can just keep going forward here.
1563                continue 'each_token;
1564            }
1565        }
1566
1567        // (`suffix_first` guaranteed initialized once reaching here.)
1568
1569        // Now `last` holds the complete set of NT tokens that could
1570        // end the sequence before SUFFIX. Check that every one works with `suffix`.
1571        for tt in &last.tokens {
1572            if let &TokenTree::MetaVarDecl { span, name, kind } = tt.get() {
1573                for next_token in &suffix_first.tokens {
1574                    let next_token = next_token.get();
1575
1576                    // Check if the old pat is used and the next token is `|`
1577                    // to warn about incompatibility with Rust 2021.
1578                    // We only emit this lint if we're parsing the original
1579                    // definition of this macro_rules, not while (re)parsing
1580                    // the macro when compiling another crate that is using the
1581                    // macro. (See #86567.)
1582                    if is_defined_in_current_crate(node_id)
1583                        && #[allow(non_exhaustive_omitted_patterns)] match kind {
    NonterminalKind::Pat(PatParam { inferred: true }) => true,
    _ => false,
}matches!(kind, NonterminalKind::Pat(PatParam { inferred: true }))
1584                        && #[allow(non_exhaustive_omitted_patterns)] match next_token {
    TokenTree::Token(token) if *token == token::Or => true,
    _ => false,
}matches!(
1585                            next_token,
1586                            TokenTree::Token(token) if *token == token::Or
1587                        )
1588                    {
1589                        // It is suggestion to use pat_param, for example: $x:pat -> $x:pat_param.
1590                        let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl {
1591                            span,
1592                            name,
1593                            kind: NonterminalKind::Pat(PatParam { inferred: false }),
1594                        });
1595                        sess.psess.buffer_lint(
1596                            RUST_2021_INCOMPATIBLE_OR_PATTERNS,
1597                            span,
1598                            ast::CRATE_NODE_ID,
1599                            diagnostics::OrPatternsBackCompat { span, suggestion },
1600                        );
1601                    }
1602                    match is_in_follow(next_token, kind) {
1603                        IsInFollow::Yes => {}
1604                        IsInFollow::No(possible) => {
1605                            let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
1606                            {
1607                                "is"
1608                            } else {
1609                                "may be"
1610                            };
1611
1612                            let sp = next_token.span();
1613                            let mut err = sess.dcx().struct_span_err(
1614                                sp,
1615                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`${0}:{1}` {3} followed by `{2}`, which is not allowed for `{1}` fragments",
                name, kind, quoted_tt_to_string(next_token), may_be))
    })format!(
1616                                    "`${name}:{frag}` {may_be} followed by `{next}`, which \
1617                                     is not allowed for `{frag}` fragments",
1618                                    name = name,
1619                                    frag = kind,
1620                                    next = quoted_tt_to_string(next_token),
1621                                    may_be = may_be
1622                                ),
1623                            );
1624                            err.span_label(sp, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not allowed after `{0}` fragments",
                kind))
    })format!("not allowed after `{kind}` fragments"));
1625
1626                            if kind == NonterminalKind::Pat(PatWithOr)
1627                                && sess.psess.edition.at_least_rust_2021()
1628                                && next_token.is_token(&token::Or)
1629                            {
1630                                let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl {
1631                                    span,
1632                                    name,
1633                                    kind: NonterminalKind::Pat(PatParam { inferred: false }),
1634                                });
1635                                err.span_suggestion(
1636                                    span,
1637                                    "try a `pat_param` fragment specifier instead",
1638                                    suggestion,
1639                                    Applicability::MaybeIncorrect,
1640                                );
1641                            }
1642
1643                            let msg = "allowed there are: ";
1644                            match possible {
1645                                &[] => {}
1646                                &[t] => {
1647                                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("only {0} is allowed after `{1}` fragments",
                t, kind))
    })format!(
1648                                        "only {t} is allowed after `{kind}` fragments",
1649                                    ));
1650                                }
1651                                ts => {
1652                                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1} or {2}", msg,
                ts[..ts.len() - 1].to_vec().join(", "), ts[ts.len() - 1]))
    })format!(
1653                                        "{}{} or {}",
1654                                        msg,
1655                                        ts[..ts.len() - 1].to_vec().join(", "),
1656                                        ts[ts.len() - 1],
1657                                    ));
1658                                }
1659                            }
1660                            errored = Err(err.emit());
1661                        }
1662                    }
1663                }
1664            }
1665        }
1666    }
1667    errored?;
1668    Ok(last)
1669}
1670
1671fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
1672    if let mbe::TokenTree::MetaVarDecl { kind, .. } = *tok {
1673        frag_can_be_followed_by_any(kind)
1674    } else {
1675        // (Non NT's can always be followed by anything in matchers.)
1676        true
1677    }
1678}
1679
1680/// Returns `true` if a fragment of type `frag` can be followed by any sort of
1681/// token. We use this (among other things) as a useful approximation
1682/// for when `frag` can be followed by a repetition like `$(...)*` or
1683/// `$(...)+`. In general, these can be a bit tricky to reason about,
1684/// so we adopt a conservative position that says that any fragment
1685/// specifier which consumes at most one token tree can be followed by
1686/// a fragment specifier (indeed, these fragments can be followed by
1687/// ANYTHING without fear of future compatibility hazards).
1688fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
1689    #[allow(non_exhaustive_omitted_patterns)] match kind {
    NonterminalKind::Item | NonterminalKind::Block | NonterminalKind::Ident |
        NonterminalKind::Literal | NonterminalKind::Meta |
        NonterminalKind::Lifetime | NonterminalKind::TT => true,
    _ => false,
}matches!(
1690        kind,
1691        NonterminalKind::Item           // always terminated by `}` or `;`
1692        | NonterminalKind::Block        // exactly one token tree
1693        | NonterminalKind::Ident        // exactly one token tree
1694        | NonterminalKind::Literal      // exactly one token tree
1695        | NonterminalKind::Meta         // exactly one token tree
1696        | NonterminalKind::Lifetime     // exactly one token tree
1697        | NonterminalKind::TT // exactly one token tree
1698    )
1699}
1700
1701enum IsInFollow {
1702    Yes,
1703    No(&'static [&'static str]),
1704}
1705
1706/// Returns `true` if `frag` can legally be followed by the token `tok`. For
1707/// fragments that can consume an unbounded number of tokens, `tok`
1708/// must be within a well-defined follow set. This is intended to
1709/// guarantee future compatibility: for example, without this rule, if
1710/// we expanded `expr` to include a new binary operator, we might
1711/// break macros that were relying on that binary operator as a
1712/// separator.
1713// when changing this do not forget to update doc/book/macros.md!
1714fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
1715    use mbe::TokenTree;
1716
1717    if let TokenTree::Token(Token { kind, .. }) = tok
1718        && kind.close_delim().is_some()
1719    {
1720        // closing a token tree can never be matched by any fragment;
1721        // iow, we always require that `(` and `)` match, etc.
1722        IsInFollow::Yes
1723    } else {
1724        match kind {
1725            NonterminalKind::Item => {
1726                // since items *must* be followed by either a `;` or a `}`, we can
1727                // accept anything after them
1728                IsInFollow::Yes
1729            }
1730            NonterminalKind::Block => {
1731                // anything can follow block, the braces provide an easy boundary to
1732                // maintain
1733                IsInFollow::Yes
1734            }
1735            NonterminalKind::Stmt | NonterminalKind::Expr(_) => {
1736                const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1737                match tok {
1738                    TokenTree::Token(token) => match token.kind {
1739                        FatArrow | Comma | Semi => IsInFollow::Yes,
1740                        _ => IsInFollow::No(TOKENS),
1741                    },
1742                    _ => IsInFollow::No(TOKENS),
1743                }
1744            }
1745            NonterminalKind::Pat(PatParam { .. }) => {
1746                const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`if let`", "`in`"];
1747                match tok {
1748                    TokenTree::Token(token) => match token.kind {
1749                        FatArrow | Comma | Eq | Or => IsInFollow::Yes,
1750                        Ident(name, IdentIsRaw::No) if name == kw::If || name == kw::In => {
1751                            IsInFollow::Yes
1752                        }
1753                        _ => IsInFollow::No(TOKENS),
1754                    },
1755                    TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } => IsInFollow::Yes,
1756                    _ => IsInFollow::No(TOKENS),
1757                }
1758            }
1759            NonterminalKind::Pat(PatWithOr) => {
1760                const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`if let`", "`in`"];
1761                match tok {
1762                    TokenTree::Token(token) => match token.kind {
1763                        FatArrow | Comma | Eq => IsInFollow::Yes,
1764                        Ident(name, IdentIsRaw::No) if name == kw::If || name == kw::In => {
1765                            IsInFollow::Yes
1766                        }
1767                        _ => IsInFollow::No(TOKENS),
1768                    },
1769                    TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } => IsInFollow::Yes,
1770                    _ => IsInFollow::No(TOKENS),
1771                }
1772            }
1773            NonterminalKind::Guard => {
1774                const TOKENS: &[&str] = &["`=>`", "`,`", "`{`"];
1775                match tok {
1776                    TokenTree::Token(token) => match token.kind {
1777                        FatArrow | Comma | OpenBrace => IsInFollow::Yes,
1778                        _ => IsInFollow::No(TOKENS),
1779                    },
1780                    _ => IsInFollow::No(TOKENS),
1781                }
1782            }
1783            NonterminalKind::Path | NonterminalKind::Ty => {
1784                const TOKENS: &[&str] = &[
1785                    "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1786                    "`where`",
1787                ];
1788                match tok {
1789                    TokenTree::Token(token) => match token.kind {
1790                        OpenBrace | OpenBracket | Comma | FatArrow | Colon | Eq | Gt | Shr
1791                        | Semi | Or => IsInFollow::Yes,
1792                        Ident(name, IdentIsRaw::No) if name == kw::As || name == kw::Where => {
1793                            IsInFollow::Yes
1794                        }
1795                        _ => IsInFollow::No(TOKENS),
1796                    },
1797                    TokenTree::MetaVarDecl { kind: NonterminalKind::Block, .. } => IsInFollow::Yes,
1798                    _ => IsInFollow::No(TOKENS),
1799                }
1800            }
1801            NonterminalKind::Ident | NonterminalKind::Lifetime => {
1802                // being a single token, idents and lifetimes are harmless
1803                IsInFollow::Yes
1804            }
1805            NonterminalKind::Literal => {
1806                // literals may be of a single token, or two tokens (negative numbers)
1807                IsInFollow::Yes
1808            }
1809            NonterminalKind::Meta | NonterminalKind::TT => {
1810                // being either a single token or a delimited sequence, tt is
1811                // harmless
1812                IsInFollow::Yes
1813            }
1814            NonterminalKind::Vis => {
1815                // Explicitly disallow `priv`, on the off chance it comes back.
1816                const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1817                match tok {
1818                    TokenTree::Token(token) => match token.kind {
1819                        Comma => IsInFollow::Yes,
1820                        Ident(_, IdentIsRaw::Yes) => IsInFollow::Yes,
1821                        Ident(name, _) if name != kw::Priv => IsInFollow::Yes,
1822                        _ => {
1823                            if token.can_begin_type() {
1824                                IsInFollow::Yes
1825                            } else {
1826                                IsInFollow::No(TOKENS)
1827                            }
1828                        }
1829                    },
1830                    TokenTree::MetaVarDecl {
1831                        kind: NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path,
1832                        ..
1833                    } => IsInFollow::Yes,
1834                    _ => IsInFollow::No(TOKENS),
1835                }
1836            }
1837        }
1838    }
1839}
1840
1841fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1842    match tt {
1843        mbe::TokenTree::Token(token) => pprust::token_to_string(token).into(),
1844        mbe::TokenTree::MetaVar(_, name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${0}", name))
    })format!("${name}"),
1845        mbe::TokenTree::MetaVarDecl { name, kind, .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${0}:{1}", name, kind))
    })format!("${name}:{kind}"),
1846        _ => {
    ::core::panicking::panic_display(&"unexpected mbe::TokenTree::{Sequence or Delimited} \
             in follow set checker");
}panic!(
1847            "{}",
1848            "unexpected mbe::TokenTree::{Sequence or Delimited} \
1849             in follow set checker"
1850        ),
1851    }
1852}
1853
1854fn is_defined_in_current_crate(node_id: NodeId) -> bool {
1855    // Macros defined in the current crate have a real node id,
1856    // whereas macros from an external crate have a dummy id.
1857    node_id != DUMMY_NODE_ID
1858}
1859
1860pub(super) fn parser_from_cx(
1861    psess: &ParseSess,
1862    mut tts: TokenStream,
1863    recovery: Recovery,
1864) -> Parser<'_> {
1865    tts.desugar_doc_comments();
1866    Parser::new(psess, tts, rustc_parse::MACRO_ARGUMENTS).recovery(recovery)
1867}