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