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    SEMICOLON_IN_EXPRESSIONS_FROM_NON_LOCAL_MACROS,
23};
24use rustc_parse::exp;
25use rustc_parse::parser::{Parser, Recovery};
26use rustc_session::Session;
27use rustc_session::diagnostics::feature_err;
28use rustc_session::parse::ParseSess;
29use rustc_span::edition::Edition;
30use rustc_span::hygiene::Transparency;
31use rustc_span::{Ident, Span, Symbol, kw, sym};
32use tracing::{debug, instrument, trace, trace_span};
33
34use super::SequenceRepetition;
35use super::diagnostics::{FailedMacro, failed_to_match_macro};
36use super::macro_parser::{NamedMatches, NamedParseResult};
37use crate::base::{
38    AttrProcMacro, BangProcMacro, DummyResult, ExpandResult, ExtCtxt, MacResult,
39    MacroExpanderResult, SyntaxExtension, SyntaxExtensionKind, TTMacroExpander,
40};
41use crate::diagnostics;
42use crate::expand::{AstFragment, AstFragmentKind, ensure_complete_parse, parse_ast_fragment};
43use crate::mbe::macro_check::check_meta_variables;
44use crate::mbe::macro_parser::{Ambiguity, ErrorReported, Failure, MatcherLoc, Success, TtParser};
45use crate::mbe::quoted::{RulePart, parse_one_tt};
46use crate::mbe::transcribe::transcribe;
47use crate::mbe::{self, KleeneOp};
48
49pub(crate) struct ParserAnyMacro<'a, 'b> {
50    parser: Parser<'a>,
51
52    /// Span of the expansion site of the macro this parser is for
53    site_span: Span,
54    /// The ident of the macro we're parsing
55    macro_ident: Ident,
56    lint_node_id: NodeId,
57    is_trailing_mac: bool,
58    arm_span: Span,
59    /// Whether or not this macro is defined in the current crate
60    is_local: bool,
61    bindings: &'b [MacroRule],
62    matched_rule_bindings: &'b [MatcherLoc],
63}
64
65impl<'a, 'b> ParserAnyMacro<'a, 'b> {
66    pub(crate) fn make(
67        mut self: Box<ParserAnyMacro<'a, 'b>>,
68        kind: AstFragmentKind,
69    ) -> AstFragment {
70        let ParserAnyMacro {
71            site_span,
72            macro_ident,
73            ref mut parser,
74            lint_node_id,
75            arm_span,
76            is_trailing_mac,
77            is_local,
78            bindings,
79            matched_rule_bindings,
80        } = *self;
81        let snapshot = &mut parser.create_snapshot_for_diagnostic();
82        let fragment = match parse_ast_fragment(parser, kind) {
83            Ok(f) => f,
84            Err(err) => {
85                let guar = super::diagnostics::emit_frag_parse_err(
86                    err,
87                    parser,
88                    snapshot,
89                    site_span,
90                    arm_span,
91                    kind,
92                    bindings,
93                    matched_rule_bindings,
94                );
95                return kind.dummy(site_span, guar);
96            }
97        };
98
99        // We allow semicolons at the end of expressions -- e.g., the semicolon in
100        // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
101        // but `m!()` is allowed in expression positions (cf. issue #34706).
102        if kind == AstFragmentKind::Expr && parser.token == token::Semi {
103            let lint = if is_local {
104                SEMICOLON_IN_EXPRESSIONS_FROM_MACROS
105            } else {
106                SEMICOLON_IN_EXPRESSIONS_FROM_NON_LOCAL_MACROS
107            };
108            parser.psess.buffer_lint(
109                lint,
110                parser.token.span,
111                lint_node_id,
112                diagnostics::TrailingMacro { is_trailing: is_trailing_mac, name: macro_ident },
113            );
114            parser.bump();
115        }
116
117        // Make sure we don't have any tokens left to parse so we don't silently drop anything.
118        let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
119        ensure_complete_parse(parser, &path, kind.name(), site_span);
120        fragment
121    }
122
123    #[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(123u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("site_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("site_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("arm_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("arm_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_local")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_local");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("macro_ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("macro_ident");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&site_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arm_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&is_local as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&macro_ident)
                                                            as &dyn ::tracing::field::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))]
124    pub(crate) fn from_tts<'cx>(
125        cx: &'cx mut ExtCtxt<'a>,
126        tts: TokenStream,
127        site_span: Span,
128        arm_span: Span,
129        is_local: bool,
130        macro_ident: Ident,
131        // bindings and lhs is for diagnostics
132        bindings: &'b [MacroRule],
133        matched_rule_bindings: &'b [MatcherLoc],
134    ) -> Self {
135        Self {
136            parser: Parser::new(&cx.sess.psess, tts, None),
137
138            // Pass along the original expansion site and the name of the macro
139            // so we can print a useful error message if the parse of the expanded
140            // macro leaves unparsed tokens.
141            site_span,
142            macro_ident,
143            lint_node_id: cx.current_expansion.lint_node_id,
144            is_trailing_mac: cx.current_expansion.is_trailing_mac,
145            arm_span,
146            is_local,
147            bindings,
148            matched_rule_bindings,
149        }
150    }
151}
152
153pub(crate) enum MacroRule {
154    /// A function-style rule, for use with `m!()`
155    Func { lhs: Vec<MatcherLoc>, lhs_span: Span, rhs: mbe::TokenTree },
156    /// An attr rule, for use with `#[m]`
157    Attr {
158        unsafe_rule: bool,
159        args: Vec<MatcherLoc>,
160        args_span: Span,
161        body: Vec<MatcherLoc>,
162        body_span: Span,
163        rhs: mbe::TokenTree,
164    },
165    /// A derive rule, for use with `#[m]`
166    Derive { body: Vec<MatcherLoc>, body_span: Span, rhs: mbe::TokenTree },
167}
168
169/// A selection of a matcher in a [`MacroRule`].
170///
171/// [`MacroRule::Attr`] has two different matchers (args and body). This enum allows distinguishing
172/// between them, even when used for other kinds of rules.
173///
174/// This type implements [`Ord`]. The arms within a rule come in a fixed order and this type is
175/// consistent with that ordering.
176#[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)]
177pub(crate) enum WhichMatcher {
178    /// The arguments of an attr macro ([`MacroRule::Attr::args`]).
179    Args,
180
181    /// The body of an attr macro ([`MacroRule::Attr::body`]), **or** the only arm of the rule.
182    ///
183    /// This is also used to express the only arm in a [`MacroRule::Func`] or [`MacroRule::Derive`].
184    Body,
185}
186
187impl WhichMatcher {
188    /// The [`WhichMatcher`] for [`MacroRule::Func`].
189    pub(crate) const FOR_FUNC: Self = Self::Body;
190
191    /// The [`WhichMatcher`] for [`MacroRule::Derive`].
192    pub(crate) const FOR_DERIVE: Self = Self::Body;
193}
194
195pub struct MacroRulesMacroExpander {
196    node_id: NodeId,
197    name: Ident,
198    span: Span,
199    on_unmatched_args: Option<Directive>,
200    transparency: Transparency,
201    kinds: MacroKinds,
202    rules: Vec<MacroRule>,
203    macro_rules: bool,
204}
205
206impl MacroRulesMacroExpander {
207    pub fn get_unused_rule(&self, rule_i: usize) -> Option<(&Ident, MultiSpan)> {
208        // If the rhs contains an invocation like `compile_error!`, don't report it as unused.
209        let (span, rhs) = match self.rules[rule_i] {
210            MacroRule::Func { lhs_span, ref rhs, .. } => (MultiSpan::from_span(lhs_span), rhs),
211            MacroRule::Attr { args_span, body_span, ref rhs, .. } => {
212                (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)
213            }
214            MacroRule::Derive { body_span, ref rhs, .. } => (MultiSpan::from_span(body_span), rhs),
215        };
216        if has_compile_error_macro(rhs) { None } else { Some((&self.name, span)) }
217    }
218
219    pub fn kinds(&self) -> MacroKinds {
220        self.kinds
221    }
222
223    pub fn nrules(&self) -> usize {
224        self.rules.len()
225    }
226
227    pub fn is_macro_rules(&self) -> bool {
228        self.macro_rules
229    }
230
231    pub fn expand_derive(
232        &self,
233        cx: &mut ExtCtxt<'_>,
234        sp: Span,
235        body: &TokenStream,
236    ) -> Result<TokenStream, ErrorGuaranteed> {
237        // This is similar to `expand_macro`, but they have very different signatures, and will
238        // diverge further once derives support arguments.
239        let name = self.name;
240        let rules = &self.rules;
241        let psess = &cx.sess.psess;
242
243        if cx.trace_macros() {
244            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));
245            trace_macros_note(&mut cx.expansions, sp, msg);
246        }
247
248        match try_match_macro_derive(psess, name, body, rules, &mut NoopTracker) {
249            Ok((rule_index, rule, named_matches)) => {
250                let MacroRule::Derive { rhs, .. } = rule else {
251                    {
    ::core::panicking::panic_fmt(format_args!("try_match_macro_derive returned non-derive rule"));
};panic!("try_match_macro_derive returned non-derive rule");
252                };
253                let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
254                    cx.dcx().span_bug(sp, "malformed macro derive rhs");
255                };
256
257                let id = cx.current_expansion.id;
258                let tts = transcribe(psess, &named_matches, rhs, *rhs_span, self.transparency, id)
259                    .map_err(|e| e.emit())?;
260
261                if cx.trace_macros() {
262                    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));
263                    trace_macros_note(&mut cx.expansions, sp, msg);
264                }
265
266                if is_defined_in_current_crate(self.node_id) {
267                    cx.resolver.record_macro_rule_usage(self.node_id, rule_index);
268                }
269
270                Ok(tts)
271            }
272            Err(CanRetry::No(guar)) => Err(guar),
273            Err(CanRetry::Yes) => {
274                let (_, guar) = failed_to_match_macro(
275                    cx.psess(),
276                    sp,
277                    self.span,
278                    name,
279                    FailedMacro::Derive,
280                    body,
281                    rules,
282                    self.on_unmatched_args.as_ref(),
283                );
284                cx.macro_error_and_trace_macros_diag();
285                Err(guar)
286            }
287        }
288    }
289}
290
291impl TTMacroExpander for MacroRulesMacroExpander {
292    fn expand<'cx, 'a: 'cx>(
293        &'a self,
294        cx: &'cx mut ExtCtxt<'_>,
295        sp: Span,
296        input: TokenStream,
297    ) -> MacroExpanderResult<'cx> {
298        ExpandResult::Ready(expand_macro(
299            cx,
300            sp,
301            self.span,
302            self.node_id,
303            self.name,
304            self.transparency,
305            input,
306            &self.rules,
307            self.on_unmatched_args.as_ref(),
308        ))
309    }
310}
311
312impl AttrProcMacro for MacroRulesMacroExpander {
313    fn expand(
314        &self,
315        _cx: &mut ExtCtxt<'_>,
316        _sp: Span,
317        _args: TokenStream,
318        _body: TokenStream,
319    ) -> Result<TokenStream, ErrorGuaranteed> {
320        {
    ::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`")
321    }
322
323    fn expand_with_safety(
324        &self,
325        cx: &mut ExtCtxt<'_>,
326        safety: Safety,
327        sp: Span,
328        args: TokenStream,
329        body: TokenStream,
330    ) -> Result<TokenStream, ErrorGuaranteed> {
331        expand_macro_attr(
332            cx,
333            sp,
334            self.span,
335            self.node_id,
336            self.name,
337            self.transparency,
338            safety,
339            args,
340            body,
341            &self.rules,
342            self.on_unmatched_args.as_ref(),
343        )
344    }
345}
346
347struct DummyBang(ErrorGuaranteed);
348
349impl BangProcMacro for DummyBang {
350    fn expand<'cx>(
351        &self,
352        _: &'cx mut ExtCtxt<'_>,
353        _: Span,
354        _: TokenStream,
355    ) -> Result<TokenStream, ErrorGuaranteed> {
356        Err(self.0)
357    }
358}
359
360fn trace_macros_note(cx_expansions: &mut FxIndexMap<Span, Vec<String>>, sp: Span, message: String) {
361    let sp = sp.macro_backtrace().last().map_or(sp, |trace| trace.call_site);
362    cx_expansions.entry(sp).or_default().push(message);
363}
364
365pub(super) trait Tracker<'matcher> {
366    /// Provide context on the arm that's about to be matched.
367    fn prepare(&mut self, which_matcher: WhichMatcher, matcher: &'matcher [MatcherLoc]);
368
369    /// This is called before trying to match next MatcherLoc on the current token.
370    fn before_match_loc(&mut self, parser: &TtParser, matcher: &'matcher MatcherLoc);
371
372    /// A [`MatcherLoc`] successfully consumed input from the parser.
373    ///
374    /// This is called for [`MatcherLoc::Token`] and [`MatcherLoc::SequenceSep`], which consume
375    /// single tokens, when they successfully match [`Parser::token`]. It is also called for
376    /// [`MatcherLoc::MetaVarDecl`] when non-terminal parsing is guaranteed to occur (i.e. after
377    /// [`Parser::nonterminal_may_begin_with()`] returns `true`).
378    fn matched_one(&mut self, parser: &Parser<'_>, loc_index: usize);
379
380    /// This is called after an arm has been parsed, either successfully or unsuccessfully. When
381    /// this is called, `before_match_loc` was called at least once (with a `MatcherLoc::Eof`).
382    fn after_arm(&mut self, result: &NamedParseResult);
383
384    /// The arm could not be matched successfully.
385    ///
386    /// If the parser is located at [`token::Eof`], it indicates an unexpected end of macro
387    /// invocation. Otherwise, the parser is located at a token in the middle of the input, and it
388    /// indicates that no rules in the arm expected the given token.
389    ///
390    /// The parser will return [`NamedParseResult::Failure`] after calling this.
391    fn failure(&mut self, parser: &Parser<'_>);
392
393    /// An ambiguity error occurred.
394    ///
395    /// The parser will return [`NamedParseResult::Ambiguity`] after calling this.
396    fn ambiguity(&mut self, parser: &Parser<'_>);
397
398    /// For tracing.
399    fn description() -> &'static str;
400
401    fn recovery() -> Recovery;
402}
403
404/// A noop tracker that is used in the hot path of the expansion, has zero overhead thanks to
405/// monomorphization.
406pub(super) struct NoopTracker;
407
408impl<'matcher> Tracker<'matcher> for NoopTracker {
409    fn prepare(&mut self, _which_matcher: WhichMatcher, _matcher: &'matcher [MatcherLoc]) {}
410
411    fn before_match_loc(&mut self, _parser: &TtParser, _matcher: &'matcher MatcherLoc) {}
412
413    fn matched_one(&mut self, _parser: &Parser<'_>, _loc_index: usize) {}
414
415    fn ambiguity(&mut self, _parser: &Parser<'_>) {}
416
417    fn after_arm(&mut self, _result: &NamedParseResult) {}
418
419    fn failure(&mut self, _parser: &Parser<'_>) {}
420
421    fn description() -> &'static str {
422        "none"
423    }
424
425    fn recovery() -> Recovery {
426        Recovery::Forbidden
427    }
428}
429
430/// Expands the rules based macro defined by `rules` for a given input `arg`.
431#[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(431u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sp")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sp");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("node_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("node_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("name");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn ::tracing::field::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:487",
                                            "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(487u32),
                                            ::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};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Will not retry matching as an error was emitted already")
                                                                as &dyn ::tracing::field::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))]
432fn expand_macro<'cx, 'a: 'cx>(
433    cx: &'cx mut ExtCtxt<'_>,
434    sp: Span,
435    def_span: Span,
436    node_id: NodeId,
437    name: Ident,
438    transparency: Transparency,
439    arg: TokenStream,
440    rules: &'a [MacroRule],
441    on_unmatched_args: Option<&Directive>,
442) -> Box<dyn MacResult + 'cx> {
443    let psess = &cx.sess.psess;
444
445    if cx.trace_macros() {
446        let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
447        trace_macros_note(&mut cx.expansions, sp, msg);
448    }
449
450    // Track nothing for the best performance.
451    let try_success_result = try_match_macro(psess, name, &arg, rules, &mut NoopTracker);
452
453    match try_success_result {
454        Ok((rule_index, rule, named_matches)) => {
455            let MacroRule::Func { lhs, rhs, .. } = rule else {
456                panic!("try_match_macro returned non-func rule");
457            };
458            let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
459                cx.dcx().span_bug(sp, "malformed macro rhs");
460            };
461            let arm_span = rhs_span.entire();
462
463            // rhs has holes ( `$id` and `$(...)` that need filled)
464            let id = cx.current_expansion.id;
465            let tts = match transcribe(psess, &named_matches, rhs, *rhs_span, transparency, id) {
466                Ok(tts) => tts,
467                Err(err) => {
468                    let guar = err.emit();
469                    return DummyResult::any(arm_span, guar);
470                }
471            };
472
473            if cx.trace_macros() {
474                let msg = format!("to `{}`", pprust::tts_to_string(&tts));
475                trace_macros_note(&mut cx.expansions, sp, msg);
476            }
477
478            let is_local = is_defined_in_current_crate(node_id);
479            if is_local {
480                cx.resolver.record_macro_rule_usage(node_id, rule_index);
481            }
482
483            // Let the context choose how to interpret the result. Weird, but useful for X-macros.
484            Box::new(ParserAnyMacro::from_tts(cx, tts, sp, arm_span, is_local, name, rules, lhs))
485        }
486        Err(CanRetry::No(guar)) => {
487            debug!("Will not retry matching as an error was emitted already");
488            DummyResult::any(sp, guar)
489        }
490        Err(CanRetry::Yes) => {
491            // Retry and emit a better error.
492            let (span, guar) = failed_to_match_macro(
493                cx.psess(),
494                sp,
495                def_span,
496                name,
497                FailedMacro::Func,
498                &arg,
499                rules,
500                on_unmatched_args,
501            );
502            cx.macro_error_and_trace_macros_diag();
503            DummyResult::any(span, guar)
504        }
505    }
506}
507
508/// Expands the rules based macro defined by `rules` for a given attribute `args` and `body`.
509#[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(509u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sp")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sp");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("node_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("node_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("safety")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("safety");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&safety)
                                                            as &dyn ::tracing::field::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 !is_local && !cx.ecfg.features.macro_attr() {
                feature_err(cx.sess, sym::macro_attr, sp,
                        "`macro_rules!` attributes are unstable").emit();
            }
            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))]
510fn expand_macro_attr(
511    cx: &mut ExtCtxt<'_>,
512    sp: Span,
513    def_span: Span,
514    node_id: NodeId,
515    name: Ident,
516    transparency: Transparency,
517    safety: Safety,
518    args: TokenStream,
519    body: TokenStream,
520    rules: &[MacroRule],
521    on_unmatched_args: Option<&Directive>,
522) -> Result<TokenStream, ErrorGuaranteed> {
523    let psess = &cx.sess.psess;
524    // Macros defined in the current crate have a real node id,
525    // whereas macros from an external crate have a dummy id.
526    let is_local = node_id != DUMMY_NODE_ID;
527
528    if !is_local && !cx.ecfg.features.macro_attr() {
529        feature_err(cx.sess, sym::macro_attr, sp, "`macro_rules!` attributes are unstable").emit();
530    }
531
532    if cx.trace_macros() {
533        let msg = format!(
534            "expanding `#[{name}({})] {}`",
535            pprust::tts_to_string(&args),
536            pprust::tts_to_string(&body),
537        );
538        trace_macros_note(&mut cx.expansions, sp, msg);
539    }
540
541    // Track nothing for the best performance.
542    match try_match_macro_attr(psess, name, &args, &body, rules, &mut NoopTracker) {
543        Ok((i, rule, named_matches)) => {
544            let MacroRule::Attr { rhs, unsafe_rule, .. } = rule else {
545                panic!("try_macro_match_attr returned non-attr rule");
546            };
547            let mbe::TokenTree::Delimited(rhs_span, _, rhs) = rhs else {
548                cx.dcx().span_bug(sp, "malformed macro rhs");
549            };
550
551            match (safety, unsafe_rule) {
552                (Safety::Default, false) | (Safety::Unsafe(_), true) => {}
553                (Safety::Default, true) => {
554                    cx.dcx().span_err(sp, "unsafe attribute invocation requires `unsafe`");
555                }
556                (Safety::Unsafe(span), false) => {
557                    cx.dcx().span_err(span, "unnecessary `unsafe` on safe attribute invocation");
558                }
559                (Safety::Safe(span), _) => {
560                    cx.dcx().span_bug(span, "unexpected `safe` keyword");
561                }
562            }
563
564            let id = cx.current_expansion.id;
565            let tts = transcribe(psess, &named_matches, rhs, *rhs_span, transparency, id)
566                .map_err(|e| e.emit())?;
567
568            if cx.trace_macros() {
569                let msg = format!("to `{}`", pprust::tts_to_string(&tts));
570                trace_macros_note(&mut cx.expansions, sp, msg);
571            }
572
573            if is_local {
574                cx.resolver.record_macro_rule_usage(node_id, i);
575            }
576
577            Ok(tts)
578        }
579        Err(CanRetry::No(guar)) => Err(guar),
580        Err(CanRetry::Yes) => {
581            // Retry and emit a better error.
582            let (_, guar) = failed_to_match_macro(
583                cx.psess(),
584                sp,
585                def_span,
586                name,
587                FailedMacro::Attr(&args),
588                &body,
589                rules,
590                on_unmatched_args,
591            );
592            cx.trace_macros_diag();
593            Err(guar)
594        }
595    }
596}
597
598pub(super) enum CanRetry {
599    Yes,
600    /// We are not allowed to retry macro expansion as a fatal error has been emitted already.
601    No(ErrorGuaranteed),
602}
603
604/// Try expanding the macro. Returns the index of the successful arm and its named_matches if it was successful,
605/// and nothing if it failed. On failure, it's the callers job to use `track` accordingly to record all errors
606/// correctly.
607#[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(607u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("tracking")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("tracking");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::display(&T::description())
                                                            as &dyn ::tracing::field::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(639u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("i")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("i");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::SPAN)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let mut interest = ::tracing::subscriber::Interest::never();
                        if ::tracing::Level::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};
                                        meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::display(&i)
                                                                    as &dyn ::tracing::field::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, lhs);
                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:653",
                                                "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(653u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Parsed arm successfully")
                                                                    as &dyn ::tracing::field::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:661",
                                                "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(661u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Failed to match arm, trying the next one")
                                                                    as &dyn ::tracing::field::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:665",
                                                "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(665u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Fatal error occurred during matching")
                                                                    as &dyn ::tracing::field::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:670",
                                                "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(670u32),
                                                ::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};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Fatal error occurred and was reported during matching")
                                                                    as &dyn ::tracing::field::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()))]
608pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>(
609    psess: &ParseSess,
610    name: Ident,
611    arg: &TokenStream,
612    rules: &'matcher [MacroRule],
613    track: &mut T,
614) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
615    // We create a base parser that can be used for the "black box" parts.
616    // Every iteration needs a fresh copy of that parser. However, the parser
617    // is not mutated on many of the iterations, particularly when dealing with
618    // macros like this:
619    //
620    // macro_rules! foo {
621    //     ("a") => (A);
622    //     ("b") => (B);
623    //     ("c") => (C);
624    //     // ... etc. (maybe hundreds more)
625    // }
626    //
627    // as seen in the `html5ever` benchmark. We use a `Cow` so that the base
628    // parser is only cloned when necessary (upon mutation). Furthermore, we
629    // reinitialize the `Cow` with the base parser at the start of every
630    // iteration, so that any mutated parsers are not reused. This is all quite
631    // hacky, but speeds up the `html5ever` benchmark significantly. (Issue
632    // 68836 suggests a more comprehensive but more complex change to deal with
633    // this situation.)
634    let parser = parser_from_cx(psess, arg.clone(), T::recovery());
635    // Try each arm's matchers.
636    let mut tt_parser = TtParser::new();
637    for (i, rule) in rules.iter().enumerate() {
638        let MacroRule::Func { lhs, .. } = rule else { continue };
639        let _tracing_span = trace_span!("Matching arm", %i);
640
641        // Take a snapshot of the state of pre-expansion gating at this point.
642        // This is used so that if a matcher is not `Success(..)`ful,
643        // then the spans which became gated when parsing the unsuccessful matcher
644        // are not recorded. On the first `Success(..)`ful matcher, the spans are merged.
645        let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
646
647        track.prepare(WhichMatcher::FOR_FUNC, lhs);
648        let result = tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, track);
649        track.after_arm(&result);
650
651        match result {
652            Success(named_matches) => {
653                debug!("Parsed arm successfully");
654                // The matcher was `Success(..)`ful.
655                // Merge the gated spans from parsing the matcher with the preexisting ones.
656                psess.gated_spans.merge(gated_spans_snapshot);
657
658                return Ok((i, rule, named_matches));
659            }
660            Failure => {
661                trace!("Failed to match arm, trying the next one");
662                // Try the next arm.
663            }
664            Ambiguity => {
665                debug!("Fatal error occurred during matching");
666                // We haven't emitted an error yet, so we can retry.
667                return Err(CanRetry::Yes);
668            }
669            ErrorReported(guarantee) => {
670                debug!("Fatal error occurred and was reported during matching");
671                // An error has been reported already, we cannot retry as that would cause duplicate errors.
672                return Err(CanRetry::No(guarantee));
673            }
674        }
675
676        // The matcher was not `Success(..)`ful.
677        // Restore to the state before snapshotting and maybe try again.
678        mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut());
679    }
680
681    Err(CanRetry::Yes)
682}
683
684/// Try expanding the macro attribute. Returns the index of the successful arm and its
685/// named_matches if it was successful, and nothing if it failed. On failure, it's the caller's job
686/// to use `track` accordingly to record all errors correctly.
687#[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(687u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("tracking")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("tracking");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::display(&T::description())
                                                            as &dyn ::tracing::field::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, 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, 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()))]
688pub(super) fn try_match_macro_attr<'matcher, T: Tracker<'matcher>>(
689    psess: &ParseSess,
690    name: Ident,
691    attr_args: &TokenStream,
692    attr_body: &TokenStream,
693    rules: &'matcher [MacroRule],
694    track: &mut T,
695) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
696    // This uses the same strategy as `try_match_macro`
697    let args_parser = parser_from_cx(psess, attr_args.clone(), T::recovery());
698    let body_parser = parser_from_cx(psess, attr_body.clone(), T::recovery());
699    let mut tt_parser = TtParser::new();
700    for (i, rule) in rules.iter().enumerate() {
701        let MacroRule::Attr { args, body, .. } = rule else { continue };
702
703        let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
704
705        track.prepare(WhichMatcher::Args, args);
706        let result = tt_parser.parse_tt(&mut Cow::Borrowed(&args_parser), args, track);
707        track.after_arm(&result);
708
709        let mut named_matches = match result {
710            Success(named_matches) => named_matches,
711            Failure => {
712                mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut());
713                continue;
714            }
715            Ambiguity => return Err(CanRetry::Yes),
716            ErrorReported(guar) => return Err(CanRetry::No(guar)),
717        };
718
719        track.prepare(WhichMatcher::Body, body);
720        let result = tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body, track);
721        track.after_arm(&result);
722
723        match result {
724            Success(body_named_matches) => {
725                psess.gated_spans.merge(gated_spans_snapshot);
726                #[allow(rustc::potential_query_instability)]
727                named_matches.extend(body_named_matches);
728                return Ok((i, rule, named_matches));
729            }
730            Failure => {
731                mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut())
732            }
733            Ambiguity => return Err(CanRetry::Yes),
734            ErrorReported(guar) => return Err(CanRetry::No(guar)),
735        }
736    }
737
738    Err(CanRetry::Yes)
739}
740
741/// Try expanding the macro derive. Returns the index of the successful arm and its
742/// named_matches if it was successful, and nothing if it failed. On failure, it's the caller's job
743/// to use `track` accordingly to record all errors correctly.
744#[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(744u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("name");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("tracking")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("tracking");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::display(&T::description())
                                                            as &dyn ::tracing::field::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, body);
                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()))]
745pub(super) fn try_match_macro_derive<'matcher, T: Tracker<'matcher>>(
746    psess: &ParseSess,
747    name: Ident,
748    body: &TokenStream,
749    rules: &'matcher [MacroRule],
750    track: &mut T,
751) -> Result<(usize, &'matcher MacroRule, NamedMatches), CanRetry> {
752    // This uses the same strategy as `try_match_macro`
753    let body_parser = parser_from_cx(psess, body.clone(), T::recovery());
754    let mut tt_parser = TtParser::new();
755    for (i, rule) in rules.iter().enumerate() {
756        let MacroRule::Derive { body, .. } = rule else { continue };
757
758        let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut());
759
760        track.prepare(WhichMatcher::FOR_DERIVE, body);
761        let result = tt_parser.parse_tt(&mut Cow::Borrowed(&body_parser), body, track);
762        track.after_arm(&result);
763
764        match result {
765            Success(named_matches) => {
766                psess.gated_spans.merge(gated_spans_snapshot);
767                return Ok((i, rule, named_matches));
768            }
769            Failure => {
770                mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut())
771            }
772            Ambiguity => return Err(CanRetry::Yes),
773            ErrorReported(guar) => return Err(CanRetry::No(guar)),
774        }
775    }
776
777    Err(CanRetry::Yes)
778}
779
780/// Converts a macro item into a syntax extension.
781pub fn compile_declarative_macro(
782    sess: &Session,
783    features: &Features,
784    macro_def: &ast::MacroDef,
785    ident: Ident,
786    attrs: &[hir::Attribute],
787    span: Span,
788    node_id: NodeId,
789    edition: Edition,
790) -> SyntaxExtension {
791    let mk_syn_ext = |kind| {
792        let is_local = is_defined_in_current_crate(node_id);
793        SyntaxExtension::new(sess, kind, span, Vec::new(), edition, ident.name, attrs, is_local)
794    };
795    let dummy_syn_ext = |guar| mk_syn_ext(SyntaxExtensionKind::Bang(Arc::new(DummyBang(guar))));
796
797    let macro_rules = macro_def.macro_rules;
798    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) };
799
800    let body = macro_def.body.tokens.clone();
801    let mut p = Parser::new(&sess.psess, body, rustc_parse::MACRO_ARGUMENTS);
802
803    // Don't abort iteration early, so that multiple errors can be reported. We only abort early on
804    // parse failures we can't recover from.
805    let mut guar = None;
806    let mut check_emission = |ret: Result<(), ErrorGuaranteed>| guar = guar.or(ret.err());
807
808    let mut kinds = MacroKinds::empty();
809    let mut rules = Vec::new();
810
811    while p.token != token::Eof {
812        let unsafe_rule = p.eat_keyword_noexpect(kw::Unsafe);
813        let unsafe_keyword_span = p.prev_token.span;
814        if unsafe_rule && let Some(guar) = check_no_eof(sess, &p, "expected `attr`") {
815            return dummy_syn_ext(guar);
816        }
817        let (args, is_derive) = if p.eat_keyword_noexpect(sym::attr) {
818            kinds |= MacroKinds::ATTR;
819            if is_defined_in_current_crate(node_id) && !features.macro_attr() {
820                feature_err(sess, sym::macro_attr, span, "`macro_rules!` attributes are unstable")
821                    .emit();
822            }
823            if let Some(guar) = check_no_eof(sess, &p, "expected macro attr args") {
824                return dummy_syn_ext(guar);
825            }
826            let args = p.parse_token_tree();
827            check_args_parens(sess, sym::attr, &args);
828            let args = parse_one_tt(args, RulePart::Pattern, sess, node_id, features, edition);
829            check_emission(check_lhs(sess, features, node_id, &args));
830            if let Some(guar) = check_no_eof(sess, &p, "expected macro attr body") {
831                return dummy_syn_ext(guar);
832            }
833            (Some(args), false)
834        } else if p.eat_keyword_noexpect(sym::derive) {
835            kinds |= MacroKinds::DERIVE;
836            let derive_keyword_span = p.prev_token.span;
837            if !features.macro_derive() {
838                feature_err(sess, sym::macro_derive, span, "`macro_rules!` derives are unstable")
839                    .emit();
840            }
841            if unsafe_rule {
842                sess.dcx()
843                    .span_err(unsafe_keyword_span, "`unsafe` is only supported on `attr` rules");
844            }
845            if let Some(guar) = check_no_eof(sess, &p, "expected `()` after `derive`") {
846                return dummy_syn_ext(guar);
847            }
848            let args = p.parse_token_tree();
849            check_args_parens(sess, sym::derive, &args);
850            let args_empty_result = check_args_empty(sess, &args);
851            let args_not_empty = args_empty_result.is_err();
852            check_emission(args_empty_result);
853            if let Some(guar) = check_no_eof(sess, &p, "expected macro derive body") {
854                return dummy_syn_ext(guar);
855            }
856            // If the user has `=>` right after the `()`, they might have forgotten the empty
857            // parentheses.
858            if p.token == token::FatArrow {
859                let mut err = sess
860                    .dcx()
861                    .struct_span_err(p.token.span, "expected macro derive body, got `=>`");
862                if args_not_empty {
863                    err.span_label(derive_keyword_span, "need `()` after this `derive`");
864                }
865                return dummy_syn_ext(err.emit());
866            }
867            (None, true)
868        } else {
869            kinds |= MacroKinds::BANG;
870            if unsafe_rule {
871                sess.dcx()
872                    .span_err(unsafe_keyword_span, "`unsafe` is only supported on `attr` rules");
873            }
874            (None, false)
875        };
876        let lhs_tt = p.parse_token_tree();
877        let lhs_tt = parse_one_tt(lhs_tt, RulePart::Pattern, sess, node_id, features, edition);
878        check_emission(check_lhs(sess, features, node_id, &lhs_tt));
879        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)) {
880            return dummy_syn_ext(e.emit());
881        }
882        if let Some(guar) = check_no_eof(sess, &p, "expected right-hand side of macro rule") {
883            return dummy_syn_ext(guar);
884        }
885        let rhs = p.parse_token_tree();
886        let rhs = parse_one_tt(rhs, RulePart::Body, sess, node_id, features, edition);
887        check_emission(check_rhs(sess, &rhs));
888        check_emission(check_meta_variables(&sess.psess, node_id, args.as_ref(), &lhs_tt, &rhs));
889        let lhs_span = lhs_tt.span();
890        // Convert the lhs into `MatcherLoc` form, which is better for doing the
891        // actual matching.
892        let mbe::TokenTree::Delimited(.., delimited) = lhs_tt else {
893            return dummy_syn_ext(guar.unwrap());
894        };
895        let lhs = mbe::macro_parser::compute_locs(&delimited.tts);
896        if let Some(args) = args {
897            let args_span = args.span();
898            let mbe::TokenTree::Delimited(.., delimited) = args else {
899                return dummy_syn_ext(guar.unwrap());
900            };
901            let args = mbe::macro_parser::compute_locs(&delimited.tts);
902            let body_span = lhs_span;
903            rules.push(MacroRule::Attr { unsafe_rule, args, args_span, body: lhs, body_span, rhs });
904        } else if is_derive {
905            rules.push(MacroRule::Derive { body: lhs, body_span: lhs_span, rhs });
906        } else {
907            rules.push(MacroRule::Func { lhs, lhs_span, rhs });
908        }
909        if p.token == token::Eof {
910            break;
911        }
912        if let Err(e) = p.expect(exp_sep) {
913            return dummy_syn_ext(e.emit());
914        }
915    }
916
917    if rules.is_empty() {
918        let guar = sess.dcx().span_err(span, "macros must contain at least one rule");
919        return dummy_syn_ext(guar);
920    }
921    if !!kinds.is_empty() {
    ::core::panicking::panic("assertion failed: !kinds.is_empty()")
};assert!(!kinds.is_empty());
922
923    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)
924        .unwrap_or(Transparency::fallback(macro_rules));
925
926    if let Some(guar) = guar {
927        // To avoid warning noise, only consider the rules of this
928        // macro for the lint, if all rules are valid.
929        return dummy_syn_ext(guar);
930    }
931
932    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!(
933        attrs,
934        OnUnmatchedArgs { directive, .. } => directive.clone()
935    )
936    .flatten()
937    .map(|directive| *directive);
938
939    let exp = MacroRulesMacroExpander {
940        name: ident,
941        kinds,
942        span,
943        node_id,
944        on_unmatched_args,
945        transparency,
946        rules,
947        macro_rules,
948    };
949    mk_syn_ext(SyntaxExtensionKind::MacroRules(Arc::new(exp)))
950}
951
952fn check_no_eof(sess: &Session, p: &Parser<'_>, msg: &'static str) -> Option<ErrorGuaranteed> {
953    if p.token == token::Eof {
954        let err_sp = p.token.span.shrink_to_hi();
955        let guar = sess
956            .dcx()
957            .struct_span_err(err_sp, "macro definition ended unexpectedly")
958            .with_span_label(err_sp, msg)
959            .emit();
960        return Some(guar);
961    }
962    None
963}
964
965fn check_args_parens(sess: &Session, rule_kw: Symbol, args: &tokenstream::TokenTree) {
966    // This does not handle the non-delimited case; that gets handled separately by `check_lhs`.
967    if let tokenstream::TokenTree::Delimited(dspan, _, delim, _) = args
968        && *delim != Delimiter::Parenthesis
969    {
970        sess.dcx().emit_err(diagnostics::MacroArgsBadDelim {
971            span: dspan.entire(),
972            sugg: diagnostics::MacroArgsBadDelimSugg { open: dspan.open, close: dspan.close },
973            rule_kw,
974        });
975    }
976}
977
978fn check_args_empty(sess: &Session, args: &tokenstream::TokenTree) -> Result<(), ErrorGuaranteed> {
979    match args {
980        tokenstream::TokenTree::Delimited(.., delimited) if delimited.is_empty() => Ok(()),
981        _ => {
982            let msg = "`derive` rules do not accept arguments; `derive` must be followed by `()`";
983            Err(sess.dcx().span_err(args.span(), msg))
984        }
985    }
986}
987
988fn check_lhs(
989    sess: &Session,
990    features: &Features,
991    node_id: NodeId,
992    lhs: &mbe::TokenTree,
993) -> Result<(), ErrorGuaranteed> {
994    let e1 = check_lhs_nt_follows(sess, features, node_id, lhs);
995    let e2 = check_lhs_no_empty_seq(sess, slice::from_ref(lhs));
996    e1.and(e2)
997}
998
999fn check_lhs_nt_follows(
1000    sess: &Session,
1001    features: &Features,
1002    node_id: NodeId,
1003    lhs: &mbe::TokenTree,
1004) -> Result<(), ErrorGuaranteed> {
1005    // lhs is going to be like TokenTree::Delimited(...), where the
1006    // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
1007    if let mbe::TokenTree::Delimited(.., delimited) = lhs {
1008        check_matcher(sess, features, node_id, &delimited.tts)
1009    } else {
1010        let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
1011        Err(sess.dcx().span_err(lhs.span(), msg))
1012    }
1013}
1014
1015fn is_empty_token_tree(sess: &Session, seq: &mbe::SequenceRepetition) -> bool {
1016    if seq.separator.is_some() {
1017        false
1018    } else {
1019        let mut is_empty = true;
1020        let mut iter = seq.tts.iter().peekable();
1021        while let Some(tt) = iter.next() {
1022            match tt {
1023                mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. } => {}
1024                mbe::TokenTree::Token(t @ Token { kind: DocComment(..), .. }) => {
1025                    let mut now = t;
1026                    while let Some(&mbe::TokenTree::Token(
1027                        next @ Token { kind: DocComment(..), .. },
1028                    )) = iter.peek()
1029                    {
1030                        now = next;
1031                        iter.next();
1032                    }
1033                    let span = t.span.to(now.span);
1034                    sess.dcx().span_note(span, "doc comments are ignored in matcher position");
1035                }
1036                mbe::TokenTree::Sequence(_, sub_seq)
1037                    if (sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
1038                        || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne) => {}
1039                _ => is_empty = false,
1040            }
1041        }
1042        is_empty
1043    }
1044}
1045
1046/// Checks if a `vis` nonterminal fragment is unnecessarily wrapped in an optional repetition.
1047///
1048/// When a `vis` fragment (which can already be empty) is wrapped in `$(...)?`,
1049/// this suggests removing the redundant repetition syntax since it provides no additional benefit.
1050fn check_redundant_vis_repetition(
1051    err: &mut Diag<'_>,
1052    sess: &Session,
1053    seq: &SequenceRepetition,
1054    span: &DelimSpan,
1055) {
1056    if seq.kleene.op == KleeneOp::ZeroOrOne
1057        && #[allow(non_exhaustive_omitted_patterns)] match seq.tts.first() {
    Some(mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. }) =>
        true,
    _ => false,
}matches!(
1058            seq.tts.first(),
1059            Some(mbe::TokenTree::MetaVarDecl { kind: NonterminalKind::Vis, .. })
1060        )
1061    {
1062        err.note("a `vis` fragment can already be empty");
1063        err.multipart_suggestion(
1064            "remove the `$(` and `)?`",
1065            ::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![
1066                (
1067                    sess.source_map().span_extend_to_prev_char_before(span.open, '$', true),
1068                    "".to_string(),
1069                ),
1070                (span.close.with_hi(seq.kleene.span.hi()), "".to_string()),
1071            ],
1072            Applicability::MaybeIncorrect,
1073        );
1074    }
1075}
1076
1077/// Checks that the lhs contains no repetition which could match an empty token
1078/// tree, because then the matcher would hang indefinitely.
1079fn check_lhs_no_empty_seq(sess: &Session, tts: &[mbe::TokenTree]) -> Result<(), ErrorGuaranteed> {
1080    use mbe::TokenTree;
1081    for tt in tts {
1082        match tt {
1083            TokenTree::Token(..)
1084            | TokenTree::MetaVar(..)
1085            | TokenTree::MetaVarDecl { .. }
1086            | TokenTree::MetaVarExpr(..) => (),
1087            TokenTree::Delimited(.., del) => check_lhs_no_empty_seq(sess, &del.tts)?,
1088            TokenTree::Sequence(span, seq) => {
1089                if is_empty_token_tree(sess, seq) {
1090                    let sp = span.entire();
1091                    let mut err =
1092                        sess.dcx().struct_span_err(sp, "repetition matches empty token tree");
1093                    check_redundant_vis_repetition(&mut err, sess, seq, span);
1094                    return Err(err.emit());
1095                }
1096                check_lhs_no_empty_seq(sess, &seq.tts)?
1097            }
1098        }
1099    }
1100
1101    Ok(())
1102}
1103
1104fn check_rhs(sess: &Session, rhs: &mbe::TokenTree) -> Result<(), ErrorGuaranteed> {
1105    match *rhs {
1106        mbe::TokenTree::Delimited(..) => Ok(()),
1107        _ => Err(sess.dcx().span_err(rhs.span(), "macro rhs must be delimited")),
1108    }
1109}
1110
1111fn check_matcher(
1112    sess: &Session,
1113    features: &Features,
1114    node_id: NodeId,
1115    matcher: &[mbe::TokenTree],
1116) -> Result<(), ErrorGuaranteed> {
1117    let first_sets = FirstSets::new(matcher);
1118    let empty_suffix = TokenSet::empty();
1119    check_matcher_core(sess, features, node_id, &first_sets, matcher, &empty_suffix)?;
1120    Ok(())
1121}
1122
1123fn has_compile_error_macro(rhs: &mbe::TokenTree) -> bool {
1124    match rhs {
1125        mbe::TokenTree::Delimited(.., d) => {
1126            let has_compile_error = d.tts.array_windows::<3>().any(|[ident, bang, args]| {
1127                if let mbe::TokenTree::Token(ident) = ident
1128                    && let TokenKind::Ident(ident, _) = ident.kind
1129                    && ident == sym::compile_error
1130                    && let mbe::TokenTree::Token(bang) = bang
1131                    && let TokenKind::Bang = bang.kind
1132                    && let mbe::TokenTree::Delimited(.., del) = args
1133                    && !del.delim.skip()
1134                {
1135                    true
1136                } else {
1137                    false
1138                }
1139            });
1140            if has_compile_error { true } else { d.tts.iter().any(has_compile_error_macro) }
1141        }
1142        _ => false,
1143    }
1144}
1145
1146// `The FirstSets` for a matcher is a mapping from subsequences in the
1147// matcher to the FIRST set for that subsequence.
1148//
1149// This mapping is partially precomputed via a backwards scan over the
1150// token trees of the matcher, which provides a mapping from each
1151// repetition sequence to its *first* set.
1152//
1153// (Hypothetically, sequences should be uniquely identifiable via their
1154// spans, though perhaps that is false, e.g., for macro-generated macros
1155// that do not try to inject artificial span information. My plan is
1156// to try to catch such cases ahead of time and not include them in
1157// the precomputed mapping.)
1158struct FirstSets<'tt> {
1159    // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
1160    // span in the original matcher to the First set for the inner sequence `tt ...`.
1161    //
1162    // If two sequences have the same span in a matcher, then map that
1163    // span to None (invalidating the mapping here and forcing the code to
1164    // use a slow path).
1165    first: FxHashMap<Span, Option<TokenSet<'tt>>>,
1166}
1167
1168impl<'tt> FirstSets<'tt> {
1169    fn new(tts: &'tt [mbe::TokenTree]) -> FirstSets<'tt> {
1170        use mbe::TokenTree;
1171
1172        let mut sets = FirstSets { first: FxHashMap::default() };
1173        build_recur(&mut sets, tts);
1174        return sets;
1175
1176        // walks backward over `tts`, returning the FIRST for `tts`
1177        // and updating `sets` at the same time for all sequence
1178        // substructure we find within `tts`.
1179        fn build_recur<'tt>(sets: &mut FirstSets<'tt>, tts: &'tt [TokenTree]) -> TokenSet<'tt> {
1180            let mut first = TokenSet::empty();
1181            for tt in tts.iter().rev() {
1182                match tt {
1183                    TokenTree::Token(..)
1184                    | TokenTree::MetaVar(..)
1185                    | TokenTree::MetaVarDecl { .. }
1186                    | TokenTree::MetaVarExpr(..) => {
1187                        first.replace_with(TtHandle::TtRef(tt));
1188                    }
1189                    TokenTree::Delimited(span, _, delimited) => {
1190                        build_recur(sets, &delimited.tts);
1191                        first.replace_with(TtHandle::from_token_kind(
1192                            delimited.delim.as_open_token_kind(),
1193                            span.open,
1194                        ));
1195                    }
1196                    TokenTree::Sequence(sp, seq_rep) => {
1197                        let subfirst = build_recur(sets, &seq_rep.tts);
1198
1199                        match sets.first.entry(sp.entire()) {
1200                            Entry::Vacant(vac) => {
1201                                vac.insert(Some(subfirst.clone()));
1202                            }
1203                            Entry::Occupied(mut occ) => {
1204                                // if there is already an entry, then a span must have collided.
1205                                // This should not happen with typical macro_rules macros,
1206                                // but syntax extensions need not maintain distinct spans,
1207                                // so distinct syntax trees can be assigned the same span.
1208                                // In such a case, the map cannot be trusted; so mark this
1209                                // entry as unusable.
1210                                occ.insert(None);
1211                            }
1212                        }
1213
1214                        // If the sequence contents can be empty, then the first
1215                        // token could be the separator token itself.
1216
1217                        if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
1218                            first.add_one_maybe(TtHandle::from_token(*sep));
1219                        }
1220
1221                        // Reverse scan: Sequence comes before `first`.
1222                        if subfirst.maybe_empty
1223                            || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
1224                            || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
1225                        {
1226                            // If sequence is potentially empty, then
1227                            // union them (preserving first emptiness).
1228                            first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
1229                        } else {
1230                            // Otherwise, sequence guaranteed
1231                            // non-empty; replace first.
1232                            first = subfirst;
1233                        }
1234                    }
1235                }
1236            }
1237
1238            first
1239        }
1240    }
1241
1242    // walks forward over `tts` until all potential FIRST tokens are
1243    // identified.
1244    fn first(&self, tts: &'tt [mbe::TokenTree]) -> TokenSet<'tt> {
1245        use mbe::TokenTree;
1246
1247        let mut first = TokenSet::empty();
1248        for tt in tts.iter() {
1249            if !first.maybe_empty {
    ::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1250            match tt {
1251                TokenTree::Token(..)
1252                | TokenTree::MetaVar(..)
1253                | TokenTree::MetaVarDecl { .. }
1254                | TokenTree::MetaVarExpr(..) => {
1255                    first.add_one(TtHandle::TtRef(tt));
1256                    return first;
1257                }
1258                TokenTree::Delimited(span, _, delimited) => {
1259                    first.add_one(TtHandle::from_token_kind(
1260                        delimited.delim.as_open_token_kind(),
1261                        span.open,
1262                    ));
1263                    return first;
1264                }
1265                TokenTree::Sequence(sp, seq_rep) => {
1266                    let subfirst_owned;
1267                    let subfirst = match self.first.get(&sp.entire()) {
1268                        Some(Some(subfirst)) => subfirst,
1269                        Some(&None) => {
1270                            subfirst_owned = self.first(&seq_rep.tts);
1271                            &subfirst_owned
1272                        }
1273                        None => {
1274                            {
    ::core::panicking::panic_fmt(format_args!("We missed a sequence during FirstSets construction"));
};panic!("We missed a sequence during FirstSets construction");
1275                        }
1276                    };
1277
1278                    // If the sequence contents can be empty, then the first
1279                    // token could be the separator token itself.
1280                    if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
1281                        first.add_one_maybe(TtHandle::from_token(*sep));
1282                    }
1283
1284                    if !first.maybe_empty {
    ::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1285                    first.add_all(subfirst);
1286                    if subfirst.maybe_empty
1287                        || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
1288                        || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
1289                    {
1290                        // Continue scanning for more first
1291                        // tokens, but also make sure we
1292                        // restore empty-tracking state.
1293                        first.maybe_empty = true;
1294                        continue;
1295                    } else {
1296                        return first;
1297                    }
1298                }
1299            }
1300        }
1301
1302        // we only exit the loop if `tts` was empty or if every
1303        // element of `tts` matches the empty sequence.
1304        if !first.maybe_empty {
    ::core::panicking::panic("assertion failed: first.maybe_empty")
};assert!(first.maybe_empty);
1305        first
1306    }
1307}
1308
1309// Most `mbe::TokenTree`s are preexisting in the matcher, but some are defined
1310// implicitly, such as opening/closing delimiters and sequence repetition ops.
1311// This type encapsulates both kinds. It implements `Clone` while avoiding the
1312// need for `mbe::TokenTree` to implement `Clone`.
1313#[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)]
1314enum TtHandle<'tt> {
1315    /// This is used in most cases.
1316    TtRef(&'tt mbe::TokenTree),
1317
1318    /// This is only used for implicit token trees. The `mbe::TokenTree` *must*
1319    /// be `mbe::TokenTree::Token`. No other variants are allowed. We store an
1320    /// `mbe::TokenTree` rather than a `Token` so that `get()` can return a
1321    /// `&mbe::TokenTree`.
1322    Token(mbe::TokenTree),
1323}
1324
1325impl<'tt> TtHandle<'tt> {
1326    fn from_token(tok: Token) -> Self {
1327        TtHandle::Token(mbe::TokenTree::Token(tok))
1328    }
1329
1330    fn from_token_kind(kind: TokenKind, span: Span) -> Self {
1331        TtHandle::from_token(Token::new(kind, span))
1332    }
1333
1334    // Get a reference to a token tree.
1335    fn get(&'tt self) -> &'tt mbe::TokenTree {
1336        match self {
1337            TtHandle::TtRef(tt) => tt,
1338            TtHandle::Token(token_tt) => token_tt,
1339        }
1340    }
1341}
1342
1343impl<'tt> PartialEq for TtHandle<'tt> {
1344    fn eq(&self, other: &TtHandle<'tt>) -> bool {
1345        self.get() == other.get()
1346    }
1347}
1348
1349impl<'tt> Clone for TtHandle<'tt> {
1350    fn clone(&self) -> Self {
1351        match self {
1352            TtHandle::TtRef(tt) => TtHandle::TtRef(tt),
1353
1354            // This variant *must* contain a `mbe::TokenTree::Token`, and not
1355            // any other variant of `mbe::TokenTree`.
1356            TtHandle::Token(mbe::TokenTree::Token(tok)) => {
1357                TtHandle::Token(mbe::TokenTree::Token(*tok))
1358            }
1359
1360            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1361        }
1362    }
1363}
1364
1365// A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s
1366// (for macro-by-example syntactic variables). It also carries the
1367// `maybe_empty` flag; that is true if and only if the matcher can
1368// match an empty token sequence.
1369//
1370// The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
1371// which has corresponding FIRST = {$a:expr, c, d}.
1372// Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
1373//
1374// (Notably, we must allow for *-op to occur zero times.)
1375#[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)]
1376struct TokenSet<'tt> {
1377    tokens: Vec<TtHandle<'tt>>,
1378    maybe_empty: bool,
1379}
1380
1381impl<'tt> TokenSet<'tt> {
1382    // Returns a set for the empty sequence.
1383    fn empty() -> Self {
1384        TokenSet { tokens: Vec::new(), maybe_empty: true }
1385    }
1386
1387    // Returns the set `{ tok }` for the single-token (and thus
1388    // non-empty) sequence [tok].
1389    fn singleton(tt: TtHandle<'tt>) -> Self {
1390        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 }
1391    }
1392
1393    // Changes self to be the set `{ tok }`.
1394    // Since `tok` is always present, marks self as non-empty.
1395    fn replace_with(&mut self, tt: TtHandle<'tt>) {
1396        self.tokens.clear();
1397        self.tokens.push(tt);
1398        self.maybe_empty = false;
1399    }
1400
1401    // Changes self to be the empty set `{}`; meant for use when
1402    // the particular token does not matter, but we want to
1403    // record that it occurs.
1404    fn replace_with_irrelevant(&mut self) {
1405        self.tokens.clear();
1406        self.maybe_empty = false;
1407    }
1408
1409    // Adds `tok` to the set for `self`, marking sequence as non-empty.
1410    fn add_one(&mut self, tt: TtHandle<'tt>) {
1411        if !self.tokens.contains(&tt) {
1412            self.tokens.push(tt);
1413        }
1414        self.maybe_empty = false;
1415    }
1416
1417    // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
1418    fn add_one_maybe(&mut self, tt: TtHandle<'tt>) {
1419        if !self.tokens.contains(&tt) {
1420            self.tokens.push(tt);
1421        }
1422    }
1423
1424    // Adds all elements of `other` to this.
1425    //
1426    // (Since this is a set, we filter out duplicates.)
1427    //
1428    // If `other` is potentially empty, then preserves the previous
1429    // setting of the empty flag of `self`. If `other` is guaranteed
1430    // non-empty, then `self` is marked non-empty.
1431    fn add_all(&mut self, other: &Self) {
1432        for tt in &other.tokens {
1433            if !self.tokens.contains(tt) {
1434                self.tokens.push(tt.clone());
1435            }
1436        }
1437        if !other.maybe_empty {
1438            self.maybe_empty = false;
1439        }
1440    }
1441}
1442
1443// Checks that `matcher` is internally consistent and that it
1444// can legally be followed by a token `N`, for all `N` in `follow`.
1445// (If `follow` is empty, then it imposes no constraint on
1446// the `matcher`.)
1447//
1448// Returns the set of NT tokens that could possibly come last in
1449// `matcher`. (If `matcher` matches the empty sequence, then
1450// `maybe_empty` will be set to true.)
1451//
1452// Requires that `first_sets` is pre-computed for `matcher`;
1453// see `FirstSets::new`.
1454fn check_matcher_core<'tt>(
1455    sess: &Session,
1456    features: &Features,
1457    node_id: NodeId,
1458    first_sets: &FirstSets<'tt>,
1459    matcher: &'tt [mbe::TokenTree],
1460    follow: &TokenSet<'tt>,
1461) -> Result<TokenSet<'tt>, ErrorGuaranteed> {
1462    use mbe::TokenTree;
1463
1464    let mut last = TokenSet::empty();
1465
1466    let mut errored = Ok(());
1467
1468    // 2. For each token and suffix  [T, SUFFIX] in M:
1469    // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
1470    // then ensure T can also be followed by any element of FOLLOW.
1471    'each_token: for i in 0..matcher.len() {
1472        let token = &matcher[i];
1473        let suffix = &matcher[i + 1..];
1474
1475        let build_suffix_first = || {
1476            let mut s = first_sets.first(suffix);
1477            if s.maybe_empty {
1478                s.add_all(follow);
1479            }
1480            s
1481        };
1482
1483        // (we build `suffix_first` on demand below; you can tell
1484        // which cases are supposed to fall through by looking for the
1485        // initialization of this variable.)
1486        let suffix_first;
1487
1488        // First, update `last` so that it corresponds to the set
1489        // of NT tokens that might end the sequence `... token`.
1490        match token {
1491            TokenTree::Token(..)
1492            | TokenTree::MetaVar(..)
1493            | TokenTree::MetaVarDecl { .. }
1494            | TokenTree::MetaVarExpr(..) => {
1495                if let TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } = token
1496                    && !features.macro_guard_matcher()
1497                {
1498                    feature_err(
1499                        sess,
1500                        sym::macro_guard_matcher,
1501                        token.span(),
1502                        "`guard` fragments in macro are unstable",
1503                    )
1504                    .emit();
1505                }
1506                if token_can_be_followed_by_any(token) {
1507                    // don't need to track tokens that work with any,
1508                    last.replace_with_irrelevant();
1509                    // ... and don't need to check tokens that can be
1510                    // followed by anything against SUFFIX.
1511                    continue 'each_token;
1512                } else {
1513                    last.replace_with(TtHandle::TtRef(token));
1514                    suffix_first = build_suffix_first();
1515                }
1516            }
1517            TokenTree::Delimited(span, _, d) => {
1518                let my_suffix = TokenSet::singleton(TtHandle::from_token_kind(
1519                    d.delim.as_close_token_kind(),
1520                    span.close,
1521                ));
1522                check_matcher_core(sess, features, node_id, first_sets, &d.tts, &my_suffix)?;
1523                // don't track non NT tokens
1524                last.replace_with_irrelevant();
1525
1526                // also, we don't need to check delimited sequences
1527                // against SUFFIX
1528                continue 'each_token;
1529            }
1530            TokenTree::Sequence(_, seq_rep) => {
1531                suffix_first = build_suffix_first();
1532                // The trick here: when we check the interior, we want
1533                // to include the separator (if any) as a potential
1534                // (but not guaranteed) element of FOLLOW. So in that
1535                // case, we make a temp copy of suffix and stuff
1536                // delimiter in there.
1537                //
1538                // FIXME: Should I first scan suffix_first to see if
1539                // delimiter is already in it before I go through the
1540                // work of cloning it? But then again, this way I may
1541                // get a "tighter" span?
1542                let mut new;
1543                let my_suffix = if let Some(sep) = &seq_rep.separator {
1544                    new = suffix_first.clone();
1545                    new.add_one_maybe(TtHandle::from_token(*sep));
1546                    &new
1547                } else {
1548                    &suffix_first
1549                };
1550
1551                // At this point, `suffix_first` is built, and
1552                // `my_suffix` is some TokenSet that we can use
1553                // for checking the interior of `seq_rep`.
1554                let next = check_matcher_core(
1555                    sess,
1556                    features,
1557                    node_id,
1558                    first_sets,
1559                    &seq_rep.tts,
1560                    my_suffix,
1561                )?;
1562                if next.maybe_empty {
1563                    last.add_all(&next);
1564                } else {
1565                    last = next;
1566                }
1567
1568                // the recursive call to check_matcher_core already ran the 'each_last
1569                // check below, so we can just keep going forward here.
1570                continue 'each_token;
1571            }
1572        }
1573
1574        // (`suffix_first` guaranteed initialized once reaching here.)
1575
1576        // Now `last` holds the complete set of NT tokens that could
1577        // end the sequence before SUFFIX. Check that every one works with `suffix`.
1578        for tt in &last.tokens {
1579            if let &TokenTree::MetaVarDecl { span, name, kind } = tt.get() {
1580                for next_token in &suffix_first.tokens {
1581                    let next_token = next_token.get();
1582
1583                    // Check if the old pat is used and the next token is `|`
1584                    // to warn about incompatibility with Rust 2021.
1585                    // We only emit this lint if we're parsing the original
1586                    // definition of this macro_rules, not while (re)parsing
1587                    // the macro when compiling another crate that is using the
1588                    // macro. (See #86567.)
1589                    if is_defined_in_current_crate(node_id)
1590                        && #[allow(non_exhaustive_omitted_patterns)] match kind {
    NonterminalKind::Pat(PatParam { inferred: true }) => true,
    _ => false,
}matches!(kind, NonterminalKind::Pat(PatParam { inferred: true }))
1591                        && #[allow(non_exhaustive_omitted_patterns)] match next_token {
    TokenTree::Token(token) if *token == token::Or => true,
    _ => false,
}matches!(
1592                            next_token,
1593                            TokenTree::Token(token) if *token == token::Or
1594                        )
1595                    {
1596                        // It is suggestion to use pat_param, for example: $x:pat -> $x:pat_param.
1597                        let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl {
1598                            span,
1599                            name,
1600                            kind: NonterminalKind::Pat(PatParam { inferred: false }),
1601                        });
1602                        sess.psess.buffer_lint(
1603                            RUST_2021_INCOMPATIBLE_OR_PATTERNS,
1604                            span,
1605                            ast::CRATE_NODE_ID,
1606                            diagnostics::OrPatternsBackCompat { span, suggestion },
1607                        );
1608                    }
1609                    match is_in_follow(next_token, kind) {
1610                        IsInFollow::Yes => {}
1611                        IsInFollow::No(possible) => {
1612                            let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
1613                            {
1614                                "is"
1615                            } else {
1616                                "may be"
1617                            };
1618
1619                            let sp = next_token.span();
1620                            let mut err = sess.dcx().struct_span_err(
1621                                sp,
1622                                ::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!(
1623                                    "`${name}:{frag}` {may_be} followed by `{next}`, which \
1624                                     is not allowed for `{frag}` fragments",
1625                                    name = name,
1626                                    frag = kind,
1627                                    next = quoted_tt_to_string(next_token),
1628                                    may_be = may_be
1629                                ),
1630                            );
1631                            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"));
1632
1633                            if kind == NonterminalKind::Pat(PatWithOr)
1634                                && sess.psess.edition.at_least_rust_2021()
1635                                && next_token.is_token(&token::Or)
1636                            {
1637                                let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl {
1638                                    span,
1639                                    name,
1640                                    kind: NonterminalKind::Pat(PatParam { inferred: false }),
1641                                });
1642                                err.span_suggestion(
1643                                    span,
1644                                    "try a `pat_param` fragment specifier instead",
1645                                    suggestion,
1646                                    Applicability::MaybeIncorrect,
1647                                );
1648                            }
1649
1650                            let msg = "allowed there are: ";
1651                            match possible {
1652                                &[] => {}
1653                                &[t] => {
1654                                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("only {0} is allowed after `{1}` fragments",
                t, kind))
    })format!(
1655                                        "only {t} is allowed after `{kind}` fragments",
1656                                    ));
1657                                }
1658                                ts => {
1659                                    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!(
1660                                        "{}{} or {}",
1661                                        msg,
1662                                        ts[..ts.len() - 1].to_vec().join(", "),
1663                                        ts[ts.len() - 1],
1664                                    ));
1665                                }
1666                            }
1667                            errored = Err(err.emit());
1668                        }
1669                    }
1670                }
1671            }
1672        }
1673    }
1674    errored?;
1675    Ok(last)
1676}
1677
1678fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
1679    if let mbe::TokenTree::MetaVarDecl { kind, .. } = *tok {
1680        frag_can_be_followed_by_any(kind)
1681    } else {
1682        // (Non NT's can always be followed by anything in matchers.)
1683        true
1684    }
1685}
1686
1687/// Returns `true` if a fragment of type `frag` can be followed by any sort of
1688/// token. We use this (among other things) as a useful approximation
1689/// for when `frag` can be followed by a repetition like `$(...)*` or
1690/// `$(...)+`. In general, these can be a bit tricky to reason about,
1691/// so we adopt a conservative position that says that any fragment
1692/// specifier which consumes at most one token tree can be followed by
1693/// a fragment specifier (indeed, these fragments can be followed by
1694/// ANYTHING without fear of future compatibility hazards).
1695fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
1696    #[allow(non_exhaustive_omitted_patterns)] match kind {
    NonterminalKind::Item | NonterminalKind::Block | NonterminalKind::Ident |
        NonterminalKind::Literal | NonterminalKind::Meta |
        NonterminalKind::Lifetime | NonterminalKind::TT => true,
    _ => false,
}matches!(
1697        kind,
1698        NonterminalKind::Item           // always terminated by `}` or `;`
1699        | NonterminalKind::Block        // exactly one token tree
1700        | NonterminalKind::Ident        // exactly one token tree
1701        | NonterminalKind::Literal      // exactly one token tree
1702        | NonterminalKind::Meta         // exactly one token tree
1703        | NonterminalKind::Lifetime     // exactly one token tree
1704        | NonterminalKind::TT // exactly one token tree
1705    )
1706}
1707
1708enum IsInFollow {
1709    Yes,
1710    No(&'static [&'static str]),
1711}
1712
1713/// Returns `true` if `frag` can legally be followed by the token `tok`. For
1714/// fragments that can consume an unbounded number of tokens, `tok`
1715/// must be within a well-defined follow set. This is intended to
1716/// guarantee future compatibility: for example, without this rule, if
1717/// we expanded `expr` to include a new binary operator, we might
1718/// break macros that were relying on that binary operator as a
1719/// separator.
1720// when changing this do not forget to update doc/book/macros.md!
1721fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
1722    use mbe::TokenTree;
1723
1724    if let TokenTree::Token(Token { kind, .. }) = tok
1725        && kind.close_delim().is_some()
1726    {
1727        // closing a token tree can never be matched by any fragment;
1728        // iow, we always require that `(` and `)` match, etc.
1729        IsInFollow::Yes
1730    } else {
1731        match kind {
1732            NonterminalKind::Item => {
1733                // since items *must* be followed by either a `;` or a `}`, we can
1734                // accept anything after them
1735                IsInFollow::Yes
1736            }
1737            NonterminalKind::Block => {
1738                // anything can follow block, the braces provide an easy boundary to
1739                // maintain
1740                IsInFollow::Yes
1741            }
1742            NonterminalKind::Stmt | NonterminalKind::Expr(_) => {
1743                const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1744                match tok {
1745                    TokenTree::Token(token) => match token.kind {
1746                        FatArrow | Comma | Semi => IsInFollow::Yes,
1747                        _ => IsInFollow::No(TOKENS),
1748                    },
1749                    _ => IsInFollow::No(TOKENS),
1750                }
1751            }
1752            NonterminalKind::Pat(PatParam { .. }) => {
1753                const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`if let`", "`in`"];
1754                match tok {
1755                    TokenTree::Token(token) => match token.kind {
1756                        FatArrow | Comma | Eq | Or => IsInFollow::Yes,
1757                        Ident(name, IdentIsRaw::No) if name == kw::If || name == kw::In => {
1758                            IsInFollow::Yes
1759                        }
1760                        _ => IsInFollow::No(TOKENS),
1761                    },
1762                    TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } => IsInFollow::Yes,
1763                    _ => IsInFollow::No(TOKENS),
1764                }
1765            }
1766            NonterminalKind::Pat(PatWithOr) => {
1767                const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`if let`", "`in`"];
1768                match tok {
1769                    TokenTree::Token(token) => match token.kind {
1770                        FatArrow | Comma | Eq => IsInFollow::Yes,
1771                        Ident(name, IdentIsRaw::No) if name == kw::If || name == kw::In => {
1772                            IsInFollow::Yes
1773                        }
1774                        _ => IsInFollow::No(TOKENS),
1775                    },
1776                    TokenTree::MetaVarDecl { kind: NonterminalKind::Guard, .. } => IsInFollow::Yes,
1777                    _ => IsInFollow::No(TOKENS),
1778                }
1779            }
1780            NonterminalKind::Guard => {
1781                const TOKENS: &[&str] = &["`=>`", "`,`", "`{`"];
1782                match tok {
1783                    TokenTree::Token(token) => match token.kind {
1784                        FatArrow | Comma | OpenBrace => IsInFollow::Yes,
1785                        _ => IsInFollow::No(TOKENS),
1786                    },
1787                    _ => IsInFollow::No(TOKENS),
1788                }
1789            }
1790            NonterminalKind::Path | NonterminalKind::Ty => {
1791                const TOKENS: &[&str] = &[
1792                    "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1793                    "`where`",
1794                ];
1795                match tok {
1796                    TokenTree::Token(token) => match token.kind {
1797                        OpenBrace | OpenBracket | Comma | FatArrow | Colon | Eq | Gt | Shr
1798                        | Semi | Or => IsInFollow::Yes,
1799                        Ident(name, IdentIsRaw::No) if name == kw::As || name == kw::Where => {
1800                            IsInFollow::Yes
1801                        }
1802                        _ => IsInFollow::No(TOKENS),
1803                    },
1804                    TokenTree::MetaVarDecl { kind: NonterminalKind::Block, .. } => IsInFollow::Yes,
1805                    _ => IsInFollow::No(TOKENS),
1806                }
1807            }
1808            NonterminalKind::Ident | NonterminalKind::Lifetime => {
1809                // being a single token, idents and lifetimes are harmless
1810                IsInFollow::Yes
1811            }
1812            NonterminalKind::Literal => {
1813                // literals may be of a single token, or two tokens (negative numbers)
1814                IsInFollow::Yes
1815            }
1816            NonterminalKind::Meta | NonterminalKind::TT => {
1817                // being either a single token or a delimited sequence, tt is
1818                // harmless
1819                IsInFollow::Yes
1820            }
1821            NonterminalKind::Vis => {
1822                // Explicitly disallow `priv`, on the off chance it comes back.
1823                const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1824                match tok {
1825                    TokenTree::Token(token) => match token.kind {
1826                        Comma => IsInFollow::Yes,
1827                        Ident(_, IdentIsRaw::Yes) => IsInFollow::Yes,
1828                        Ident(name, _) if name != kw::Priv => IsInFollow::Yes,
1829                        _ => {
1830                            if token.can_begin_type() {
1831                                IsInFollow::Yes
1832                            } else {
1833                                IsInFollow::No(TOKENS)
1834                            }
1835                        }
1836                    },
1837                    TokenTree::MetaVarDecl {
1838                        kind: NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path,
1839                        ..
1840                    } => IsInFollow::Yes,
1841                    _ => IsInFollow::No(TOKENS),
1842                }
1843            }
1844        }
1845    }
1846}
1847
1848fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1849    match tt {
1850        mbe::TokenTree::Token(token) => pprust::token_to_string(token).into(),
1851        mbe::TokenTree::MetaVar(_, name) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${0}", name))
    })format!("${name}"),
1852        mbe::TokenTree::MetaVarDecl { name, kind, .. } => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${0}:{1}", name, kind))
    })format!("${name}:{kind}"),
1853        _ => {
    ::core::panicking::panic_display(&"unexpected mbe::TokenTree::{Sequence or Delimited} \
             in follow set checker");
}panic!(
1854            "{}",
1855            "unexpected mbe::TokenTree::{Sequence or Delimited} \
1856             in follow set checker"
1857        ),
1858    }
1859}
1860
1861fn is_defined_in_current_crate(node_id: NodeId) -> bool {
1862    // Macros defined in the current crate have a real node id,
1863    // whereas macros from an external crate have a dummy id.
1864    node_id != DUMMY_NODE_ID
1865}
1866
1867pub(super) fn parser_from_cx(
1868    psess: &ParseSess,
1869    mut tts: TokenStream,
1870    recovery: Recovery,
1871) -> Parser<'_> {
1872    tts.desugar_doc_comments();
1873    Parser::new(psess, tts, rustc_parse::MACRO_ARGUMENTS).recovery(recovery)
1874}