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::IdentKind;
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_attr_ir::diagnostic::Directive;
14use rustc_attr_ir::{self as attrs, find_attr};
15use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
16use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, StringPart};
17use rustc_feature::Features;
18use rustc_hir::def::MacroKinds;
19use rustc_lint_defs::builtin::{
20    RUST_2021_INCOMPATIBLE_OR_PATTERNS, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS,
21    SEMICOLON_IN_EXPRESSIONS_FROM_NON_LOCAL_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    /// Whether or not this macro is defined in the current crate
59    is_local: bool,
60    bindings: &'b [MacroRule],
61    matched_rule_bindings: &'b [MatcherLoc],
62}
63
64impl<'a, 'b> ParserAnyMacro<'a, 'b> {
65    pub(crate) fn make(
66        mut self: Box<ParserAnyMacro<'a, 'b>>,
67        kind: AstFragmentKind,
68    ) -> AstFragment {
69        let ParserAnyMacro {
70            site_span,
71            macro_ident,
72            ref mut parser,
73            lint_node_id,
74            arm_span,
75            is_trailing_mac,
76            is_local,
77            bindings,
78            matched_rule_bindings,
79        } = *self;
80        let snapshot = &mut parser.create_snapshot_for_diagnostic();
81        let fragment = match parse_ast_fragment(parser, kind) {
82            Ok(f) => f,
83            Err(err) => {
84                let guar = super::diagnostics::emit_frag_parse_err(
85                    err,
86                    parser,
87                    snapshot,
88                    site_span,
89                    arm_span,
90                    kind,
91                    bindings,
92                    matched_rule_bindings,
93                );
94                return kind.dummy(site_span, guar);
95            }
96        };
97
98        // We allow semicolons at the end of expressions -- e.g., the semicolon in
99        // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
100        // but `m!()` is allowed in expression positions (cf. issue #34706).
101        if kind == AstFragmentKind::Expr && parser.token == token::Semi {
102            let lint = if is_local {
103                SEMICOLON_IN_EXPRESSIONS_FROM_MACROS
104            } else {
105                SEMICOLON_IN_EXPRESSIONS_FROM_NON_LOCAL_MACROS
106            };
107            parser.psess.buffer_lint(
108                lint,
109                parser.token.span,
110                lint_node_id,
111                diagnostics::TrailingMacro { is_trailing: is_trailing_mac, name: macro_ident },
112            );
113            parser.bump();
114        }
115
116        // Make sure we don't have any tokens left to parse so we don't silently drop anything.
117        let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
118        ensure_complete_parse(parser, &path, kind.name(), site_span);
119        fragment
120    }
121
122    {}
#[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("/rustc-dev/5df8c02afdf6b882bc301442cea70f026e3d3974/compiler/rustc_expand/src/mbe/macro_rules.rs"),
                                    ::tracing_core::__macro_support::Option::Some(122u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::mbe::macro_rules"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("site_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("site_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("arm_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("arm_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("is_local")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("is_local");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("macro_ident")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("macro_ident");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&site_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arm_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&is_local as
                                                            &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&macro_ident)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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