Skip to main content

rustc_expand/mbe/
macro_rules.rs

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