Skip to main content

rustc_expand/
expand.rs

1use std::path::PathBuf;
2use std::rc::Rc;
3use std::sync::Arc;
4use std::{iter, mem, slice};
5
6use rustc_ast::mut_visit::*;
7use rustc_ast::tokenstream::TokenStream;
8use rustc_ast::visit::{self, AssocCtxt, Visitor, VisitorResult, try_visit, walk_list};
9use rustc_ast::{
10    self as ast, AssocItemKind, AstNodeWrapper, AttrArgs, AttrItemKind, AttrStyle, AttrVec,
11    DUMMY_NODE_ID, EarlyParsedAttribute, ExprKind, ForeignItemKind, HasAttrs, HasNodeId, Inline,
12    ItemKind, MacStmtStyle, MetaItemInner, MetaItemKind, ModKind, NodeId, PatKind, StmtKind,
13    TyKind, token,
14};
15use rustc_ast_pretty::pprust;
16use rustc_attr_parsing::{
17    AttributeParser, CFG_TEMPLATE, Early, EvalConfigResult, ShouldEmit, eval_config_entry,
18    parse_cfg, validate_attr,
19};
20use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
21use rustc_data_structures::stack::ensure_sufficient_stack;
22use rustc_errors::PResult;
23use rustc_feature::Features;
24use rustc_hir::Target;
25use rustc_hir::def::MacroKinds;
26use rustc_hir::limit::Limit;
27use rustc_parse::parser::{
28    AllowConstBlockItems, AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser,
29    RecoverColon, RecoverComma, Recovery, token_descr,
30};
31use rustc_session::Session;
32use rustc_session::lint::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS};
33use rustc_session::parse::feature_err;
34use rustc_span::hygiene::SyntaxContext;
35use rustc_span::{ErrorGuaranteed, FileName, Ident, LocalExpnId, Span, Symbol, sym};
36use smallvec::SmallVec;
37
38use crate::base::*;
39use crate::config::{StripUnconfigured, attr_into_trace};
40use crate::errors::{
41    EmptyDelegationMac, GlobDelegationOutsideImpls, GlobDelegationTraitlessQpath, IncompleteParse,
42    RecursionLimitReached, RemoveExprNotSupported, RemoveNodeNotSupported, UnsupportedKeyValue,
43    WrongFragmentKind,
44};
45use crate::fluent_generated;
46use crate::mbe::diagnostics::annotate_err_with_kind;
47use crate::module::{
48    DirOwnership, ParsedExternalMod, mod_dir_path, mod_file_path_from_attr, parse_external_mod,
49};
50use crate::placeholders::{PlaceholderExpander, placeholder};
51use crate::stats::*;
52
53macro_rules! ast_fragments {
54    (
55        $($Kind:ident($AstTy:ty) {
56            $kind_name:expr;
57            $(one
58                fn $mut_visit_ast:ident;
59                fn $visit_ast:ident;
60                fn $ast_to_string:path;
61            )?
62            $(many
63                fn $flat_map_ast_elt:ident;
64                fn $visit_ast_elt:ident($($args:tt)*);
65                fn $ast_to_string_elt:path;
66            )?
67            fn $make_ast:ident;
68        })*
69    ) => {
70        /// A fragment of AST that can be produced by a single macro expansion.
71        /// Can also serve as an input and intermediate result for macro expansion operations.
72        pub enum AstFragment {
73            OptExpr(Option<Box<ast::Expr>>),
74            MethodReceiverExpr(Box<ast::Expr>),
75            $($Kind($AstTy),)*
76        }
77
78        /// "Discriminant" of an AST fragment.
79        #[derive(Copy, Clone, Debug, PartialEq, Eq)]
80        pub enum AstFragmentKind {
81            OptExpr,
82            MethodReceiverExpr,
83            $($Kind,)*
84        }
85
86        impl AstFragmentKind {
87            pub fn name(self) -> &'static str {
88                match self {
89                    AstFragmentKind::OptExpr => "expression",
90                    AstFragmentKind::MethodReceiverExpr => "expression",
91                    $(AstFragmentKind::$Kind => $kind_name,)*
92                }
93            }
94
95            fn make_from(self, result: Box<dyn MacResult + '_>) -> Option<AstFragment> {
96                match self {
97                    AstFragmentKind::OptExpr =>
98                        result.make_expr().map(Some).map(AstFragment::OptExpr),
99                    AstFragmentKind::MethodReceiverExpr =>
100                        result.make_expr().map(AstFragment::MethodReceiverExpr),
101                    $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
102                }
103            }
104        }
105
106        impl AstFragment {
107            fn add_placeholders(&mut self, placeholders: &[NodeId]) {
108                if placeholders.is_empty() {
109                    return;
110                }
111                match self {
112                    $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| {
113                        ${ignore($flat_map_ast_elt)}
114                        placeholder(AstFragmentKind::$Kind, *id, None).$make_ast()
115                    })),)?)*
116                    _ => panic!("unexpected AST fragment kind")
117                }
118            }
119
120            pub(crate) fn make_opt_expr(self) -> Option<Box<ast::Expr>> {
121                match self {
122                    AstFragment::OptExpr(expr) => expr,
123                    _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
124                }
125            }
126
127            pub(crate) fn make_method_receiver_expr(self) -> Box<ast::Expr> {
128                match self {
129                    AstFragment::MethodReceiverExpr(expr) => expr,
130                    _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
131                }
132            }
133
134            $(pub fn $make_ast(self) -> $AstTy {
135                match self {
136                    AstFragment::$Kind(ast) => ast,
137                    _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
138                }
139            })*
140
141            fn make_ast<T: InvocationCollectorNode>(self) -> T::OutputTy {
142                T::fragment_to_output(self)
143            }
144
145            pub(crate) fn mut_visit_with(&mut self, vis: &mut impl MutVisitor) {
146                match self {
147                    AstFragment::OptExpr(opt_expr) => {
148                        if let Some(expr) = opt_expr.take() {
149                            *opt_expr = vis.filter_map_expr(expr)
150                        }
151                    }
152                    AstFragment::MethodReceiverExpr(expr) => vis.visit_method_receiver_expr(expr),
153                    $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
154                    $($(AstFragment::$Kind(ast) =>
155                        ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast, $($args)*)),)?)*
156                }
157            }
158
159            pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) -> V::Result {
160                match self {
161                    AstFragment::OptExpr(Some(expr)) => try_visit!(visitor.visit_expr(expr)),
162                    AstFragment::OptExpr(None) => {}
163                    AstFragment::MethodReceiverExpr(expr) => try_visit!(visitor.visit_method_receiver_expr(expr)),
164                    $($(AstFragment::$Kind(ast) => try_visit!(visitor.$visit_ast(ast)),)?)*
165                    $($(AstFragment::$Kind(ast) => walk_list!(visitor, $visit_ast_elt, &ast[..], $($args)*),)?)*
166                }
167                V::Result::output()
168            }
169
170            pub(crate) fn to_string(&self) -> String {
171                match self {
172                    AstFragment::OptExpr(Some(expr)) => pprust::expr_to_string(expr),
173                    AstFragment::OptExpr(None) => unreachable!(),
174                    AstFragment::MethodReceiverExpr(expr) => pprust::expr_to_string(expr),
175                    $($(AstFragment::$Kind(ast) => $ast_to_string(ast),)?)*
176                    $($(
177                        AstFragment::$Kind(ast) => {
178                            // The closure unwraps a `P` if present, or does nothing otherwise.
179                            elems_to_string(&*ast, |ast| $ast_to_string_elt(&*ast))
180                        }
181                    )?)*
182                }
183            }
184        }
185
186        impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
187            $(fn $make_ast(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
188                           -> Option<$AstTy> {
189                Some(self.make(AstFragmentKind::$Kind).$make_ast())
190            })*
191        }
192    }
193}
194
195/// A fragment of AST that can be produced by a single macro expansion.
/// Can also serve as an input and intermediate result for macro expansion operations.
pub enum AstFragment {
    OptExpr(Option<Box<ast::Expr>>),
    MethodReceiverExpr(Box<ast::Expr>),
    Expr(Box<ast::Expr>),
    Pat(Box<ast::Pat>),
    Ty(Box<ast::Ty>),
    Stmts(SmallVec<[ast::Stmt; 1]>),
    Items(SmallVec<[Box<ast::Item>; 1]>),
    TraitItems(SmallVec<[Box<ast::AssocItem>; 1]>),
    ImplItems(SmallVec<[Box<ast::AssocItem>; 1]>),
    TraitImplItems(SmallVec<[Box<ast::AssocItem>; 1]>),
    ForeignItems(SmallVec<[Box<ast::ForeignItem>; 1]>),
    Arms(SmallVec<[ast::Arm; 1]>),
    ExprFields(SmallVec<[ast::ExprField; 1]>),
    PatFields(SmallVec<[ast::PatField; 1]>),
    GenericParams(SmallVec<[ast::GenericParam; 1]>),
    Params(SmallVec<[ast::Param; 1]>),
    FieldDefs(SmallVec<[ast::FieldDef; 1]>),
    Variants(SmallVec<[ast::Variant; 1]>),
    WherePredicates(SmallVec<[ast::WherePredicate; 1]>),
    Crate(ast::Crate),
}
/// "Discriminant" of an AST fragment.
pub enum AstFragmentKind {
    OptExpr,
    MethodReceiverExpr,
    Expr,
    Pat,
    Ty,
    Stmts,
    Items,
    TraitItems,
    ImplItems,
    TraitImplItems,
    ForeignItems,
    Arms,
    ExprFields,
    PatFields,
    GenericParams,
    Params,
    FieldDefs,
    Variants,
    WherePredicates,
    Crate,
}
#[automatically_derived]
impl ::core::marker::Copy for AstFragmentKind { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AstFragmentKind { }
#[automatically_derived]
impl ::core::clone::Clone for AstFragmentKind {
    #[inline]
    fn clone(&self) -> AstFragmentKind { *self }
}
#[automatically_derived]
impl ::core::fmt::Debug for AstFragmentKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AstFragmentKind::OptExpr => "OptExpr",
                AstFragmentKind::MethodReceiverExpr => "MethodReceiverExpr",
                AstFragmentKind::Expr => "Expr",
                AstFragmentKind::Pat => "Pat",
                AstFragmentKind::Ty => "Ty",
                AstFragmentKind::Stmts => "Stmts",
                AstFragmentKind::Items => "Items",
                AstFragmentKind::TraitItems => "TraitItems",
                AstFragmentKind::ImplItems => "ImplItems",
                AstFragmentKind::TraitImplItems => "TraitImplItems",
                AstFragmentKind::ForeignItems => "ForeignItems",
                AstFragmentKind::Arms => "Arms",
                AstFragmentKind::ExprFields => "ExprFields",
                AstFragmentKind::PatFields => "PatFields",
                AstFragmentKind::GenericParams => "GenericParams",
                AstFragmentKind::Params => "Params",
                AstFragmentKind::FieldDefs => "FieldDefs",
                AstFragmentKind::Variants => "Variants",
                AstFragmentKind::WherePredicates => "WherePredicates",
                AstFragmentKind::Crate => "Crate",
            })
    }
}
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for AstFragmentKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AstFragmentKind {
    #[inline]
    fn eq(&self, other: &AstFragmentKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}
#[automatically_derived]
impl ::core::cmp::Eq for AstFragmentKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {}
}
impl AstFragmentKind {
    pub fn name(self) -> &'static str {
        match self {
            AstFragmentKind::OptExpr => "expression",
            AstFragmentKind::MethodReceiverExpr => "expression",
            AstFragmentKind::Expr => "expression",
            AstFragmentKind::Pat => "pattern",
            AstFragmentKind::Ty => "type",
            AstFragmentKind::Stmts => "statement",
            AstFragmentKind::Items => "item",
            AstFragmentKind::TraitItems => "trait item",
            AstFragmentKind::ImplItems => "impl item",
            AstFragmentKind::TraitImplItems => "impl item",
            AstFragmentKind::ForeignItems => "foreign item",
            AstFragmentKind::Arms => "match arm",
            AstFragmentKind::ExprFields => "field expression",
            AstFragmentKind::PatFields => "field pattern",
            AstFragmentKind::GenericParams => "generic parameter",
            AstFragmentKind::Params => "function parameter",
            AstFragmentKind::FieldDefs => "field",
            AstFragmentKind::Variants => "variant",
            AstFragmentKind::WherePredicates => "where predicate",
            AstFragmentKind::Crate => "crate",
        }
    }
    fn make_from(self, result: Box<dyn MacResult + '_>)
        -> Option<AstFragment> {
        match self {
            AstFragmentKind::OptExpr =>
                result.make_expr().map(Some).map(AstFragment::OptExpr),
            AstFragmentKind::MethodReceiverExpr =>
                result.make_expr().map(AstFragment::MethodReceiverExpr),
            AstFragmentKind::Expr =>
                result.make_expr().map(AstFragment::Expr),
            AstFragmentKind::Pat => result.make_pat().map(AstFragment::Pat),
            AstFragmentKind::Ty => result.make_ty().map(AstFragment::Ty),
            AstFragmentKind::Stmts =>
                result.make_stmts().map(AstFragment::Stmts),
            AstFragmentKind::Items =>
                result.make_items().map(AstFragment::Items),
            AstFragmentKind::TraitItems =>
                result.make_trait_items().map(AstFragment::TraitItems),
            AstFragmentKind::ImplItems =>
                result.make_impl_items().map(AstFragment::ImplItems),
            AstFragmentKind::TraitImplItems =>
                result.make_trait_impl_items().map(AstFragment::TraitImplItems),
            AstFragmentKind::ForeignItems =>
                result.make_foreign_items().map(AstFragment::ForeignItems),
            AstFragmentKind::Arms =>
                result.make_arms().map(AstFragment::Arms),
            AstFragmentKind::ExprFields =>
                result.make_expr_fields().map(AstFragment::ExprFields),
            AstFragmentKind::PatFields =>
                result.make_pat_fields().map(AstFragment::PatFields),
            AstFragmentKind::GenericParams =>
                result.make_generic_params().map(AstFragment::GenericParams),
            AstFragmentKind::Params =>
                result.make_params().map(AstFragment::Params),
            AstFragmentKind::FieldDefs =>
                result.make_field_defs().map(AstFragment::FieldDefs),
            AstFragmentKind::Variants =>
                result.make_variants().map(AstFragment::Variants),
            AstFragmentKind::WherePredicates =>
                result.make_where_predicates().map(AstFragment::WherePredicates),
            AstFragmentKind::Crate =>
                result.make_crate().map(AstFragment::Crate),
        }
    }
}
impl AstFragment {
    fn add_placeholders(&mut self, placeholders: &[NodeId]) {
        if placeholders.is_empty() { return; }
        match self {
            AstFragment::Stmts(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::Stmts, *id, None).make_stmts()
                            })),
            AstFragment::Items(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::Items, *id, None).make_items()
                            })),
            AstFragment::TraitItems(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::TraitItems, *id,
                                        None).make_trait_items()
                            })),
            AstFragment::ImplItems(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::ImplItems, *id,
                                        None).make_impl_items()
                            })),
            AstFragment::TraitImplItems(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::TraitImplItems, *id,
                                        None).make_trait_impl_items()
                            })),
            AstFragment::ForeignItems(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::ForeignItems, *id,
                                        None).make_foreign_items()
                            })),
            AstFragment::Arms(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::Arms, *id, None).make_arms()
                            })),
            AstFragment::ExprFields(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::ExprFields, *id,
                                        None).make_expr_fields()
                            })),
            AstFragment::PatFields(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::PatFields, *id,
                                        None).make_pat_fields()
                            })),
            AstFragment::GenericParams(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::GenericParams, *id,
                                        None).make_generic_params()
                            })),
            AstFragment::Params(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::Params, *id,
                                        None).make_params()
                            })),
            AstFragment::FieldDefs(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::FieldDefs, *id,
                                        None).make_field_defs()
                            })),
            AstFragment::Variants(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::Variants, *id,
                                        None).make_variants()
                            })),
            AstFragment::WherePredicates(ast) =>
                ast.extend(placeholders.iter().flat_map(|id|
                            {
                                placeholder(AstFragmentKind::WherePredicates, *id,
                                        None).make_where_predicates()
                            })),
            _ => {
                ::core::panicking::panic_fmt(format_args!("unexpected AST fragment kind"));
            }
        }
    }
    pub(crate) fn make_opt_expr(self) -> Option<Box<ast::Expr>> {
        match self {
            AstFragment::OptExpr(expr) => expr,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub(crate) fn make_method_receiver_expr(self) -> Box<ast::Expr> {
        match self {
            AstFragment::MethodReceiverExpr(expr) => expr,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_expr(self) -> Box<ast::Expr> {
        match self {
            AstFragment::Expr(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_pat(self) -> Box<ast::Pat> {
        match self {
            AstFragment::Pat(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_ty(self) -> Box<ast::Ty> {
        match self {
            AstFragment::Ty(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_stmts(self) -> SmallVec<[ast::Stmt; 1]> {
        match self {
            AstFragment::Stmts(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_items(self) -> SmallVec<[Box<ast::Item>; 1]> {
        match self {
            AstFragment::Items(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_trait_items(self) -> SmallVec<[Box<ast::AssocItem>; 1]> {
        match self {
            AstFragment::TraitItems(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_impl_items(self) -> SmallVec<[Box<ast::AssocItem>; 1]> {
        match self {
            AstFragment::ImplItems(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_trait_impl_items(self) -> SmallVec<[Box<ast::AssocItem>; 1]> {
        match self {
            AstFragment::TraitImplItems(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_foreign_items(self) -> SmallVec<[Box<ast::ForeignItem>; 1]> {
        match self {
            AstFragment::ForeignItems(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_arms(self) -> SmallVec<[ast::Arm; 1]> {
        match self {
            AstFragment::Arms(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_expr_fields(self) -> SmallVec<[ast::ExprField; 1]> {
        match self {
            AstFragment::ExprFields(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_pat_fields(self) -> SmallVec<[ast::PatField; 1]> {
        match self {
            AstFragment::PatFields(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_generic_params(self) -> SmallVec<[ast::GenericParam; 1]> {
        match self {
            AstFragment::GenericParams(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_params(self) -> SmallVec<[ast::Param; 1]> {
        match self {
            AstFragment::Params(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_field_defs(self) -> SmallVec<[ast::FieldDef; 1]> {
        match self {
            AstFragment::FieldDefs(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_variants(self) -> SmallVec<[ast::Variant; 1]> {
        match self {
            AstFragment::Variants(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_where_predicates(self) -> SmallVec<[ast::WherePredicate; 1]> {
        match self {
            AstFragment::WherePredicates(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    pub fn make_crate(self) -> ast::Crate {
        match self {
            AstFragment::Crate(ast) => ast,
            _ => {
                ::core::panicking::panic_fmt(format_args!("AstFragment::make_* called on the wrong kind of fragment"));
            }
        }
    }
    fn make_ast<T: InvocationCollectorNode>(self) -> T::OutputTy {
        T::fragment_to_output(self)
    }
    pub(crate) fn mut_visit_with(&mut self, vis: &mut impl MutVisitor) {
        match self {
            AstFragment::OptExpr(opt_expr) => {
                if let Some(expr) = opt_expr.take() {
                    *opt_expr = vis.filter_map_expr(expr)
                }
            }
            AstFragment::MethodReceiverExpr(expr) =>
                vis.visit_method_receiver_expr(expr),
            AstFragment::Expr(ast) => vis.visit_expr(ast),
            AstFragment::Pat(ast) => vis.visit_pat(ast),
            AstFragment::Ty(ast) => vis.visit_ty(ast),
            AstFragment::Crate(ast) => vis.visit_crate(ast),
            AstFragment::Stmts(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_stmt(ast)),
            AstFragment::Items(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_item(ast)),
            AstFragment::TraitItems(ast) =>
                ast.flat_map_in_place(|ast|
                        vis.flat_map_assoc_item(ast, AssocCtxt::Trait)),
            AstFragment::ImplItems(ast) =>
                ast.flat_map_in_place(|ast|
                        vis.flat_map_assoc_item(ast,
                            AssocCtxt::Impl { of_trait: false })),
            AstFragment::TraitImplItems(ast) =>
                ast.flat_map_in_place(|ast|
                        vis.flat_map_assoc_item(ast,
                            AssocCtxt::Impl { of_trait: true })),
            AstFragment::ForeignItems(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_foreign_item(ast)),
            AstFragment::Arms(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_arm(ast)),
            AstFragment::ExprFields(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_expr_field(ast)),
            AstFragment::PatFields(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_pat_field(ast)),
            AstFragment::GenericParams(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_generic_param(ast)),
            AstFragment::Params(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_param(ast)),
            AstFragment::FieldDefs(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_field_def(ast)),
            AstFragment::Variants(ast) =>
                ast.flat_map_in_place(|ast| vis.flat_map_variant(ast)),
            AstFragment::WherePredicates(ast) =>
                ast.flat_map_in_place(|ast|
                        vis.flat_map_where_predicate(ast)),
        }
    }
    pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V)
        -> V::Result {
        match self {
            AstFragment::OptExpr(Some(expr)) =>
                match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_expr(expr))
                    {
                    core::ops::ControlFlow::Continue(()) =>
                        (),
                        #[allow(unreachable_code)]
                        core::ops::ControlFlow::Break(r) => {
                        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                    }
                },
            AstFragment::OptExpr(None) => {}
            AstFragment::MethodReceiverExpr(expr) =>
                match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_method_receiver_expr(expr))
                    {
                    core::ops::ControlFlow::Continue(()) =>
                        (),
                        #[allow(unreachable_code)]
                        core::ops::ControlFlow::Break(r) => {
                        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                    }
                },
            AstFragment::Expr(ast) =>
                match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_expr(ast))
                    {
                    core::ops::ControlFlow::Continue(()) =>
                        (),
                        #[allow(unreachable_code)]
                        core::ops::ControlFlow::Break(r) => {
                        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                    }
                },
            AstFragment::Pat(ast) =>
                match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_pat(ast))
                    {
                    core::ops::ControlFlow::Continue(()) =>
                        (),
                        #[allow(unreachable_code)]
                        core::ops::ControlFlow::Break(r) => {
                        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                    }
                },
            AstFragment::Ty(ast) =>
                match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_ty(ast))
                    {
                    core::ops::ControlFlow::Continue(()) =>
                        (),
                        #[allow(unreachable_code)]
                        core::ops::ControlFlow::Break(r) => {
                        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                    }
                },
            AstFragment::Crate(ast) =>
                match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_crate(ast))
                    {
                    core::ops::ControlFlow::Continue(()) =>
                        (),
                        #[allow(unreachable_code)]
                        core::ops::ControlFlow::Break(r) => {
                        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                    }
                },
            AstFragment::Stmts(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_stmt(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::Items(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_item(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::TraitItems(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_assoc_item(elem,
                                AssocCtxt::Trait)) {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::ImplItems(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_assoc_item(elem,
                                AssocCtxt::Impl { of_trait: false })) {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::TraitImplItems(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_assoc_item(elem,
                                AssocCtxt::Impl { of_trait: true })) {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::ForeignItems(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_foreign_item(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::Arms(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_arm(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::ExprFields(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_expr_field(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::PatFields(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_pat_field(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::GenericParams(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_generic_param(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::Params(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_param(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::FieldDefs(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_field_def(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::Variants(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_variant(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
            AstFragment::WherePredicates(ast) =>
                for elem in &ast[..] {
                    match ::rustc_ast_ir::visit::VisitorResult::branch(visitor.visit_where_predicate(elem))
                        {
                        core::ops::ControlFlow::Continue(()) =>
                            (),
                            #[allow(unreachable_code)]
                            core::ops::ControlFlow::Break(r) => {
                            return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
                        }
                    };
                },
        }
        V::Result::output()
    }
    pub(crate) fn to_string(&self) -> String {
        match self {
            AstFragment::OptExpr(Some(expr)) => pprust::expr_to_string(expr),
            AstFragment::OptExpr(None) =>
                ::core::panicking::panic("internal error: entered unreachable code"),
            AstFragment::MethodReceiverExpr(expr) =>
                pprust::expr_to_string(expr),
            AstFragment::Expr(ast) => pprust::expr_to_string(ast),
            AstFragment::Pat(ast) => pprust::pat_to_string(ast),
            AstFragment::Ty(ast) => pprust::ty_to_string(ast),
            AstFragment::Crate(ast) => unreachable_to_string(ast),
            AstFragment::Stmts(ast) => {
                elems_to_string(&*ast, |ast| pprust::stmt_to_string(&*ast))
            }
            AstFragment::Items(ast) => {
                elems_to_string(&*ast, |ast| pprust::item_to_string(&*ast))
            }
            AstFragment::TraitItems(ast) => {
                elems_to_string(&*ast,
                    |ast| pprust::assoc_item_to_string(&*ast))
            }
            AstFragment::ImplItems(ast) => {
                elems_to_string(&*ast,
                    |ast| pprust::assoc_item_to_string(&*ast))
            }
            AstFragment::TraitImplItems(ast) => {
                elems_to_string(&*ast,
                    |ast| pprust::assoc_item_to_string(&*ast))
            }
            AstFragment::ForeignItems(ast) => {
                elems_to_string(&*ast,
                    |ast| pprust::foreign_item_to_string(&*ast))
            }
            AstFragment::Arms(ast) => {
                elems_to_string(&*ast, |ast| unreachable_to_string(&*ast))
            }
            AstFragment::ExprFields(ast) => {
                elems_to_string(&*ast, |ast| unreachable_to_string(&*ast))
            }
            AstFragment::PatFields(ast) => {
                elems_to_string(&*ast, |ast| unreachable_to_string(&*ast))
            }
            AstFragment::GenericParams(ast) => {
                elems_to_string(&*ast, |ast| unreachable_to_string(&*ast))
            }
            AstFragment::Params(ast) => {
                elems_to_string(&*ast, |ast| unreachable_to_string(&*ast))
            }
            AstFragment::FieldDefs(ast) => {
                elems_to_string(&*ast, |ast| unreachable_to_string(&*ast))
            }
            AstFragment::Variants(ast) => {
                elems_to_string(&*ast, |ast| unreachable_to_string(&*ast))
            }
            AstFragment::WherePredicates(ast) => {
                elems_to_string(&*ast, |ast| unreachable_to_string(&*ast))
            }
        }
    }
}
impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> {
    fn make_expr(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<Box<ast::Expr>> {
        Some(self.make(AstFragmentKind::Expr).make_expr())
    }
    fn make_pat(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<Box<ast::Pat>> {
        Some(self.make(AstFragmentKind::Pat).make_pat())
    }
    fn make_ty(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<Box<ast::Ty>> {
        Some(self.make(AstFragmentKind::Ty).make_ty())
    }
    fn make_stmts(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::Stmt; 1]>> {
        Some(self.make(AstFragmentKind::Stmts).make_stmts())
    }
    fn make_items(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[Box<ast::Item>; 1]>> {
        Some(self.make(AstFragmentKind::Items).make_items())
    }
    fn make_trait_items(self:
            Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
        Some(self.make(AstFragmentKind::TraitItems).make_trait_items())
    }
    fn make_impl_items(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
        Some(self.make(AstFragmentKind::ImplItems).make_impl_items())
    }
    fn make_trait_impl_items(self:
            Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[Box<ast::AssocItem>; 1]>> {
        Some(self.make(AstFragmentKind::TraitImplItems).make_trait_impl_items())
    }
    fn make_foreign_items(self:
            Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[Box<ast::ForeignItem>; 1]>> {
        Some(self.make(AstFragmentKind::ForeignItems).make_foreign_items())
    }
    fn make_arms(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::Arm; 1]>> {
        Some(self.make(AstFragmentKind::Arms).make_arms())
    }
    fn make_expr_fields(self:
            Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::ExprField; 1]>> {
        Some(self.make(AstFragmentKind::ExprFields).make_expr_fields())
    }
    fn make_pat_fields(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::PatField; 1]>> {
        Some(self.make(AstFragmentKind::PatFields).make_pat_fields())
    }
    fn make_generic_params(self:
            Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::GenericParam; 1]>> {
        Some(self.make(AstFragmentKind::GenericParams).make_generic_params())
    }
    fn make_params(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::Param; 1]>> {
        Some(self.make(AstFragmentKind::Params).make_params())
    }
    fn make_field_defs(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::FieldDef; 1]>> {
        Some(self.make(AstFragmentKind::FieldDefs).make_field_defs())
    }
    fn make_variants(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::Variant; 1]>> {
        Some(self.make(AstFragmentKind::Variants).make_variants())
    }
    fn make_where_predicates(self:
            Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<SmallVec<[ast::WherePredicate; 1]>> {
        Some(self.make(AstFragmentKind::WherePredicates).make_where_predicates())
    }
    fn make_crate(self: Box<crate::mbe::macro_rules::ParserAnyMacro<'a>>)
        -> Option<ast::Crate> {
        Some(self.make(AstFragmentKind::Crate).make_crate())
    }
}ast_fragments! {
196    Expr(Box<ast::Expr>) {
197        "expression";
198        one fn visit_expr; fn visit_expr; fn pprust::expr_to_string;
199        fn make_expr;
200    }
201    Pat(Box<ast::Pat>) {
202        "pattern";
203        one fn visit_pat; fn visit_pat; fn pprust::pat_to_string;
204        fn make_pat;
205    }
206    Ty(Box<ast::Ty>) {
207        "type";
208        one fn visit_ty; fn visit_ty; fn pprust::ty_to_string;
209        fn make_ty;
210    }
211    Stmts(SmallVec<[ast::Stmt; 1]>) {
212        "statement";
213        many fn flat_map_stmt; fn visit_stmt(); fn pprust::stmt_to_string;
214        fn make_stmts;
215    }
216    Items(SmallVec<[Box<ast::Item>; 1]>) {
217        "item";
218        many fn flat_map_item; fn visit_item(); fn pprust::item_to_string;
219        fn make_items;
220    }
221    TraitItems(SmallVec<[Box<ast::AssocItem>; 1]>) {
222        "trait item";
223        many fn flat_map_assoc_item; fn visit_assoc_item(AssocCtxt::Trait);
224            fn pprust::assoc_item_to_string;
225        fn make_trait_items;
226    }
227    ImplItems(SmallVec<[Box<ast::AssocItem>; 1]>) {
228        "impl item";
229        many fn flat_map_assoc_item; fn visit_assoc_item(AssocCtxt::Impl { of_trait: false });
230            fn pprust::assoc_item_to_string;
231        fn make_impl_items;
232    }
233    TraitImplItems(SmallVec<[Box<ast::AssocItem>; 1]>) {
234        "impl item";
235        many fn flat_map_assoc_item; fn visit_assoc_item(AssocCtxt::Impl { of_trait: true });
236            fn pprust::assoc_item_to_string;
237        fn make_trait_impl_items;
238    }
239    ForeignItems(SmallVec<[Box<ast::ForeignItem>; 1]>) {
240        "foreign item";
241        many fn flat_map_foreign_item; fn visit_foreign_item(); fn pprust::foreign_item_to_string;
242        fn make_foreign_items;
243    }
244    Arms(SmallVec<[ast::Arm; 1]>) {
245        "match arm";
246        many fn flat_map_arm; fn visit_arm(); fn unreachable_to_string;
247        fn make_arms;
248    }
249    ExprFields(SmallVec<[ast::ExprField; 1]>) {
250        "field expression";
251        many fn flat_map_expr_field; fn visit_expr_field(); fn unreachable_to_string;
252        fn make_expr_fields;
253    }
254    PatFields(SmallVec<[ast::PatField; 1]>) {
255        "field pattern";
256        many fn flat_map_pat_field; fn visit_pat_field(); fn unreachable_to_string;
257        fn make_pat_fields;
258    }
259    GenericParams(SmallVec<[ast::GenericParam; 1]>) {
260        "generic parameter";
261        many fn flat_map_generic_param; fn visit_generic_param(); fn unreachable_to_string;
262        fn make_generic_params;
263    }
264    Params(SmallVec<[ast::Param; 1]>) {
265        "function parameter";
266        many fn flat_map_param; fn visit_param(); fn unreachable_to_string;
267        fn make_params;
268    }
269    FieldDefs(SmallVec<[ast::FieldDef; 1]>) {
270        "field";
271        many fn flat_map_field_def; fn visit_field_def(); fn unreachable_to_string;
272        fn make_field_defs;
273    }
274    Variants(SmallVec<[ast::Variant; 1]>) {
275        "variant"; many fn flat_map_variant; fn visit_variant(); fn unreachable_to_string;
276        fn make_variants;
277    }
278    WherePredicates(SmallVec<[ast::WherePredicate; 1]>) {
279        "where predicate";
280        many fn flat_map_where_predicate; fn visit_where_predicate(); fn unreachable_to_string;
281        fn make_where_predicates;
282    }
283    Crate(ast::Crate) {
284        "crate";
285        one fn visit_crate; fn visit_crate; fn unreachable_to_string;
286        fn make_crate;
287    }
288}
289
290pub enum SupportsMacroExpansion {
291    No,
292    Yes { supports_inner_attrs: bool },
293}
294
295impl AstFragmentKind {
296    pub(crate) fn dummy(self, span: Span, guar: ErrorGuaranteed) -> AstFragment {
297        self.make_from(DummyResult::any(span, guar)).expect("couldn't create a dummy AST fragment")
298    }
299
300    pub fn supports_macro_expansion(self) -> SupportsMacroExpansion {
301        match self {
302            AstFragmentKind::OptExpr
303            | AstFragmentKind::Expr
304            | AstFragmentKind::MethodReceiverExpr
305            | AstFragmentKind::Stmts
306            | AstFragmentKind::Ty
307            | AstFragmentKind::Pat => SupportsMacroExpansion::Yes { supports_inner_attrs: false },
308            AstFragmentKind::Items
309            | AstFragmentKind::TraitItems
310            | AstFragmentKind::ImplItems
311            | AstFragmentKind::TraitImplItems
312            | AstFragmentKind::ForeignItems
313            | AstFragmentKind::Crate => SupportsMacroExpansion::Yes { supports_inner_attrs: true },
314            AstFragmentKind::Arms
315            | AstFragmentKind::ExprFields
316            | AstFragmentKind::PatFields
317            | AstFragmentKind::GenericParams
318            | AstFragmentKind::Params
319            | AstFragmentKind::FieldDefs
320            | AstFragmentKind::Variants
321            | AstFragmentKind::WherePredicates => SupportsMacroExpansion::No,
322        }
323    }
324
325    pub(crate) fn expect_from_annotatables(
326        self,
327        items: impl IntoIterator<Item = Annotatable>,
328    ) -> AstFragment {
329        let mut items = items.into_iter();
330        match self {
331            AstFragmentKind::Arms => {
332                AstFragment::Arms(items.map(Annotatable::expect_arm).collect())
333            }
334            AstFragmentKind::ExprFields => {
335                AstFragment::ExprFields(items.map(Annotatable::expect_expr_field).collect())
336            }
337            AstFragmentKind::PatFields => {
338                AstFragment::PatFields(items.map(Annotatable::expect_pat_field).collect())
339            }
340            AstFragmentKind::GenericParams => {
341                AstFragment::GenericParams(items.map(Annotatable::expect_generic_param).collect())
342            }
343            AstFragmentKind::Params => {
344                AstFragment::Params(items.map(Annotatable::expect_param).collect())
345            }
346            AstFragmentKind::FieldDefs => {
347                AstFragment::FieldDefs(items.map(Annotatable::expect_field_def).collect())
348            }
349            AstFragmentKind::Variants => {
350                AstFragment::Variants(items.map(Annotatable::expect_variant).collect())
351            }
352            AstFragmentKind::WherePredicates => AstFragment::WherePredicates(
353                items.map(Annotatable::expect_where_predicate).collect(),
354            ),
355            AstFragmentKind::Items => {
356                AstFragment::Items(items.map(Annotatable::expect_item).collect())
357            }
358            AstFragmentKind::ImplItems => {
359                AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
360            }
361            AstFragmentKind::TraitImplItems => {
362                AstFragment::TraitImplItems(items.map(Annotatable::expect_impl_item).collect())
363            }
364            AstFragmentKind::TraitItems => {
365                AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
366            }
367            AstFragmentKind::ForeignItems => {
368                AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect())
369            }
370            AstFragmentKind::Stmts => {
371                AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect())
372            }
373            AstFragmentKind::Expr => AstFragment::Expr(
374                items.next().expect("expected exactly one expression").expect_expr(),
375            ),
376            AstFragmentKind::MethodReceiverExpr => AstFragment::MethodReceiverExpr(
377                items.next().expect("expected exactly one expression").expect_expr(),
378            ),
379            AstFragmentKind::OptExpr => {
380                AstFragment::OptExpr(items.next().map(Annotatable::expect_expr))
381            }
382            AstFragmentKind::Crate => {
383                AstFragment::Crate(items.next().expect("expected exactly one crate").expect_crate())
384            }
385            AstFragmentKind::Pat | AstFragmentKind::Ty => {
386                {
    ::core::panicking::panic_fmt(format_args!("patterns and types aren\'t annotatable"));
}panic!("patterns and types aren't annotatable")
387            }
388        }
389    }
390}
391
392pub struct Invocation {
393    pub kind: InvocationKind,
394    pub fragment_kind: AstFragmentKind,
395    pub expansion_data: ExpansionData,
396}
397
398pub enum InvocationKind {
399    Bang {
400        mac: Box<ast::MacCall>,
401        span: Span,
402    },
403    Attr {
404        attr: ast::Attribute,
405        /// Re-insertion position for inert attributes.
406        pos: usize,
407        item: Annotatable,
408        /// Required for resolving derive helper attributes.
409        derives: Vec<ast::Path>,
410    },
411    Derive {
412        path: ast::Path,
413        is_const: bool,
414        item: Annotatable,
415    },
416    GlobDelegation {
417        item: Box<ast::AssocItem>,
418        /// Whether this is a trait impl or an inherent impl
419        of_trait: bool,
420    },
421}
422
423impl InvocationKind {
424    fn placeholder_visibility(&self) -> Option<ast::Visibility> {
425        // HACK: For unnamed fields placeholders should have the same visibility as the actual
426        // fields because for tuple structs/variants resolve determines visibilities of their
427        // constructor using these field visibilities before attributes on them are expanded.
428        // The assumption is that the attribute expansion cannot change field visibilities,
429        // and it holds because only inert attributes are supported in this position.
430        match self {
431            InvocationKind::Attr { item: Annotatable::FieldDef(field), .. }
432            | InvocationKind::Derive { item: Annotatable::FieldDef(field), .. }
433                if field.ident.is_none() =>
434            {
435                Some(field.vis.clone())
436            }
437            _ => None,
438        }
439    }
440}
441
442impl Invocation {
443    pub fn span(&self) -> Span {
444        match &self.kind {
445            InvocationKind::Bang { span, .. } => *span,
446            InvocationKind::Attr { attr, .. } => attr.span,
447            InvocationKind::Derive { path, .. } => path.span,
448            InvocationKind::GlobDelegation { item, .. } => item.span,
449        }
450    }
451
452    fn span_mut(&mut self) -> &mut Span {
453        match &mut self.kind {
454            InvocationKind::Bang { span, .. } => span,
455            InvocationKind::Attr { attr, .. } => &mut attr.span,
456            InvocationKind::Derive { path, .. } => &mut path.span,
457            InvocationKind::GlobDelegation { item, .. } => &mut item.span,
458        }
459    }
460}
461
462pub struct MacroExpander<'a, 'b> {
463    pub cx: &'a mut ExtCtxt<'b>,
464    monotonic: bool, // cf. `cx.monotonic_expander()`
465}
466
467impl<'a, 'b> MacroExpander<'a, 'b> {
468    pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
469        MacroExpander { cx, monotonic }
470    }
471
472    pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate {
473        let file_path = match self.cx.source_map().span_to_filename(krate.spans.inner_span) {
474            FileName::Real(name) => name
475                .into_local_path()
476                .expect("attempting to resolve a file path in an external file"),
477            other => PathBuf::from(other.prefer_local_unconditionally().to_string()),
478        };
479        let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
480        self.cx.root_path = dir_path.clone();
481        self.cx.current_expansion.module = Rc::new(ModuleData {
482            mod_path: <[_]>::into_vec(::alloc::boxed::box_new([Ident::with_dummy_span(self.cx.ecfg.crate_name)]))vec![Ident::with_dummy_span(self.cx.ecfg.crate_name)],
483            file_path_stack: <[_]>::into_vec(::alloc::boxed::box_new([file_path]))vec![file_path],
484            dir_path,
485        });
486        let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate();
487        match (&krate.id, &ast::CRATE_NODE_ID) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(krate.id, ast::CRATE_NODE_ID);
488        self.cx.trace_macros_diag();
489        krate
490    }
491
492    /// Recursively expand all macro invocations in this AST fragment.
493    pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
494        let orig_expansion_data = self.cx.current_expansion.clone();
495        let orig_force_mode = self.cx.force_mode;
496
497        // Collect all macro invocations and replace them with placeholders.
498        let (mut fragment_with_placeholders, mut invocations) =
499            self.collect_invocations(input_fragment, &[]);
500
501        // Optimization: if we resolve all imports now,
502        // we'll be able to immediately resolve most of imported macros.
503        self.resolve_imports();
504
505        // Resolve paths in all invocations and produce output expanded fragments for them, but
506        // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
507        // The output fragments also go through expansion recursively until no invocations are left.
508        // Unresolved macros produce dummy outputs as a recovery measure.
509        invocations.reverse();
510        let mut expanded_fragments = Vec::new();
511        let mut undetermined_invocations = Vec::new();
512        let (mut progress, mut force) = (false, !self.monotonic);
513        loop {
514            let Some((invoc, ext)) = invocations.pop() else {
515                self.resolve_imports();
516                if undetermined_invocations.is_empty() {
517                    break;
518                }
519                invocations = mem::take(&mut undetermined_invocations);
520                force = !progress;
521                progress = false;
522                if force && self.monotonic {
523                    self.cx.dcx().span_delayed_bug(
524                        invocations.last().unwrap().0.span(),
525                        "expansion entered force mode without producing any errors",
526                    );
527                }
528                continue;
529            };
530
531            let ext = match ext {
532                Some(ext) => ext,
533                None => {
534                    let eager_expansion_root = if self.monotonic {
535                        invoc.expansion_data.id
536                    } else {
537                        orig_expansion_data.id
538                    };
539                    match self.cx.resolver.resolve_macro_invocation(
540                        &invoc,
541                        eager_expansion_root,
542                        force,
543                    ) {
544                        Ok(ext) => ext,
545                        Err(Indeterminate) => {
546                            // Cannot resolve, will retry this invocation later.
547                            undetermined_invocations.push((invoc, None));
548                            continue;
549                        }
550                    }
551                }
552            };
553
554            let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
555            let depth = depth - orig_expansion_data.depth;
556            self.cx.current_expansion = invoc.expansion_data.clone();
557            self.cx.force_mode = force;
558
559            let fragment_kind = invoc.fragment_kind;
560            match self.expand_invoc(invoc, &ext.kind) {
561                ExpandResult::Ready(fragment) => {
562                    let mut derive_invocations = Vec::new();
563                    let derive_placeholders = self
564                        .cx
565                        .resolver
566                        .take_derive_resolutions(expn_id)
567                        .map(|derives| {
568                            derive_invocations.reserve(derives.len());
569                            derives
570                                .into_iter()
571                                .map(|DeriveResolution { path, item, exts: _, is_const }| {
572                                    // FIXME: Consider using the derive resolutions (`_exts`)
573                                    // instead of enqueuing the derives to be resolved again later.
574                                    // Note that this can result in duplicate diagnostics.
575                                    let expn_id = LocalExpnId::fresh_empty();
576                                    derive_invocations.push((
577                                        Invocation {
578                                            kind: InvocationKind::Derive { path, item, is_const },
579                                            fragment_kind,
580                                            expansion_data: ExpansionData {
581                                                id: expn_id,
582                                                ..self.cx.current_expansion.clone()
583                                            },
584                                        },
585                                        None,
586                                    ));
587                                    NodeId::placeholder_from_expn_id(expn_id)
588                                })
589                                .collect::<Vec<_>>()
590                        })
591                        .unwrap_or_default();
592
593                    let (expanded_fragment, collected_invocations) =
594                        self.collect_invocations(fragment, &derive_placeholders);
595                    // We choose to expand any derive invocations associated with this macro
596                    // invocation *before* any macro invocations collected from the output
597                    // fragment.
598                    derive_invocations.extend(collected_invocations);
599
600                    progress = true;
601                    if expanded_fragments.len() < depth {
602                        expanded_fragments.push(Vec::new());
603                    }
604                    expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
605                    invocations.extend(derive_invocations.into_iter().rev());
606                }
607                ExpandResult::Retry(invoc) => {
608                    if force {
609                        self.cx.dcx().span_bug(
610                            invoc.span(),
611                            "expansion entered force mode but is still stuck",
612                        );
613                    } else {
614                        // Cannot expand, will retry this invocation later.
615                        undetermined_invocations.push((invoc, Some(ext)));
616                    }
617                }
618            }
619        }
620
621        self.cx.current_expansion = orig_expansion_data;
622        self.cx.force_mode = orig_force_mode;
623
624        // Finally incorporate all the expanded macros into the input AST fragment.
625        let mut placeholder_expander = PlaceholderExpander::default();
626        while let Some(expanded_fragments) = expanded_fragments.pop() {
627            for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
628                placeholder_expander
629                    .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
630            }
631        }
632        fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
633        fragment_with_placeholders
634    }
635
636    fn resolve_imports(&mut self) {
637        if self.monotonic {
638            self.cx.resolver.resolve_imports();
639        }
640    }
641
642    /// Collects all macro invocations reachable at this time in this AST fragment, and replace
643    /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
644    /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
645    /// prepares data for resolving paths of macro invocations.
646    fn collect_invocations(
647        &mut self,
648        mut fragment: AstFragment,
649        extra_placeholders: &[NodeId],
650    ) -> (AstFragment, Vec<(Invocation, Option<Arc<SyntaxExtension>>)>) {
651        // Resolve `$crate`s in the fragment for pretty-printing.
652        self.cx.resolver.resolve_dollar_crates();
653
654        let mut invocations = {
655            let mut collector = InvocationCollector {
656                // Non-derive macro invocations cannot see the results of cfg expansion - they
657                // will either be removed along with the item, or invoked before the cfg/cfg_attr
658                // attribute is expanded. Therefore, we don't need to configure the tokens
659                // Derive macros *can* see the results of cfg-expansion - they are handled
660                // specially in `fully_expand_fragment`
661                cx: self.cx,
662                invocations: Vec::new(),
663                monotonic: self.monotonic,
664            };
665            fragment.mut_visit_with(&mut collector);
666            fragment.add_placeholders(extra_placeholders);
667            collector.invocations
668        };
669
670        if self.monotonic {
671            self.cx
672                .resolver
673                .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
674
675            if self.cx.sess.opts.incremental.is_some() {
676                for (invoc, _) in invocations.iter_mut() {
677                    let expn_id = invoc.expansion_data.id;
678                    let parent_def = self.cx.resolver.invocation_parent(expn_id);
679                    let span = invoc.span_mut();
680                    *span = span.with_parent(Some(parent_def));
681                }
682            }
683        }
684
685        (fragment, invocations)
686    }
687
688    fn error_recursion_limit_reached(&mut self) -> ErrorGuaranteed {
689        let expn_data = self.cx.current_expansion.id.expn_data();
690        let suggested_limit = match self.cx.ecfg.recursion_limit {
691            Limit(0) => Limit(2),
692            limit => limit * 2,
693        };
694
695        let guar = self.cx.dcx().emit_err(RecursionLimitReached {
696            span: expn_data.call_site,
697            descr: expn_data.kind.descr(),
698            suggested_limit,
699            crate_name: self.cx.ecfg.crate_name,
700        });
701
702        self.cx.macro_error_and_trace_macros_diag();
703        guar
704    }
705
706    /// A macro's expansion does not fit in this fragment kind.
707    /// For example, a non-type macro in a type position.
708    fn error_wrong_fragment_kind(
709        &mut self,
710        kind: AstFragmentKind,
711        mac: &ast::MacCall,
712        span: Span,
713    ) -> ErrorGuaranteed {
714        let guar =
715            self.cx.dcx().emit_err(WrongFragmentKind { span, kind: kind.name(), name: &mac.path });
716        self.cx.macro_error_and_trace_macros_diag();
717        guar
718    }
719
720    fn expand_invoc(
721        &mut self,
722        invoc: Invocation,
723        ext: &SyntaxExtensionKind,
724    ) -> ExpandResult<AstFragment, Invocation> {
725        let recursion_limit = match self.cx.reduced_recursion_limit {
726            Some((limit, _)) => limit,
727            None => self.cx.ecfg.recursion_limit,
728        };
729
730        if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) {
731            let guar = match self.cx.reduced_recursion_limit {
732                Some((_, guar)) => guar,
733                None => self.error_recursion_limit_reached(),
734            };
735
736            // Reduce the recursion limit by half each time it triggers.
737            self.cx.reduced_recursion_limit = Some((recursion_limit / 2, guar));
738
739            return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span(), guar));
740        }
741
742        let macro_stats = self.cx.sess.opts.unstable_opts.macro_stats;
743
744        let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
745        ExpandResult::Ready(match invoc.kind {
746            InvocationKind::Bang { mac, span } => {
747                if let SyntaxExtensionKind::Bang(expander) = ext {
748                    match expander.expand(self.cx, span, mac.args.tokens.clone()) {
749                        Ok(tok_result) => {
750                            let fragment =
751                                self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span);
752                            if macro_stats {
753                                update_bang_macro_stats(
754                                    self.cx,
755                                    fragment_kind,
756                                    span,
757                                    mac,
758                                    &fragment,
759                                );
760                            }
761                            fragment
762                        }
763                        Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
764                    }
765                } else if let Some(expander) = ext.as_legacy_bang() {
766                    let tok_result = match expander.expand(self.cx, span, mac.args.tokens.clone()) {
767                        ExpandResult::Ready(tok_result) => tok_result,
768                        ExpandResult::Retry(_) => {
769                            // retry the original
770                            return ExpandResult::Retry(Invocation {
771                                kind: InvocationKind::Bang { mac, span },
772                                ..invoc
773                            });
774                        }
775                    };
776                    if let Some(fragment) = fragment_kind.make_from(tok_result) {
777                        if macro_stats {
778                            update_bang_macro_stats(self.cx, fragment_kind, span, mac, &fragment);
779                        }
780                        fragment
781                    } else {
782                        let guar = self.error_wrong_fragment_kind(fragment_kind, &mac, span);
783                        fragment_kind.dummy(span, guar)
784                    }
785                } else {
786                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
787                }
788            }
789            InvocationKind::Attr { attr, pos, mut item, derives } => {
790                if let Some(expander) = ext.as_attr() {
791                    self.gate_proc_macro_input(&item);
792                    self.gate_proc_macro_attr_item(span, &item);
793                    let tokens = match &item {
794                        // FIXME: Collect tokens and use them instead of generating
795                        // fake ones. These are unstable, so it needs to be
796                        // fixed prior to stabilization
797                        // Fake tokens when we are invoking an inner attribute, and
798                        // we are invoking it on an out-of-line module or crate.
799                        Annotatable::Crate(krate) => {
800                            rustc_parse::fake_token_stream_for_crate(&self.cx.sess.psess, krate)
801                        }
802                        Annotatable::Item(item_inner)
803                            if #[allow(non_exhaustive_omitted_patterns)] match attr.style {
    AttrStyle::Inner => true,
    _ => false,
}matches!(attr.style, AttrStyle::Inner)
804                                && #[allow(non_exhaustive_omitted_patterns)] match item_inner.kind {
    ItemKind::Mod(_, _,
        ModKind::Unloaded | ModKind::Loaded(_, Inline::No { .. }, _)) => true,
    _ => false,
}matches!(
805                                    item_inner.kind,
806                                    ItemKind::Mod(
807                                        _,
808                                        _,
809                                        ModKind::Unloaded
810                                            | ModKind::Loaded(_, Inline::No { .. }, _),
811                                    )
812                                ) =>
813                        {
814                            rustc_parse::fake_token_stream_for_item(&self.cx.sess.psess, item_inner)
815                        }
816                        _ => item.to_tokens(),
817                    };
818                    let attr_item = attr.get_normal_item();
819                    let safety = attr_item.unsafety;
820                    if let AttrArgs::Eq { .. } = attr_item.args.unparsed_ref().unwrap() {
821                        self.cx.dcx().emit_err(UnsupportedKeyValue { span });
822                    }
823                    let inner_tokens = attr_item.args.unparsed_ref().unwrap().inner_tokens();
824                    match expander.expand_with_safety(self.cx, safety, span, inner_tokens, tokens) {
825                        Ok(tok_result) => {
826                            let fragment = self.parse_ast_fragment(
827                                tok_result,
828                                fragment_kind,
829                                &attr_item.path,
830                                span,
831                            );
832                            if macro_stats {
833                                update_attr_macro_stats(
834                                    self.cx,
835                                    fragment_kind,
836                                    span,
837                                    &attr_item.path,
838                                    &attr,
839                                    item,
840                                    &fragment,
841                                );
842                            }
843                            fragment
844                        }
845                        Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
846                    }
847                } else if let SyntaxExtensionKind::LegacyAttr(expander) = ext {
848                    // `LegacyAttr` is only used for builtin attribute macros, which have their
849                    // safety checked by `check_builtin_meta_item`, so we don't need to check
850                    // `unsafety` here.
851                    match validate_attr::parse_meta(&self.cx.sess.psess, &attr) {
852                        Ok(meta) => {
853                            let item_clone = macro_stats.then(|| item.clone());
854                            let items = match expander.expand(self.cx, span, &meta, item, false) {
855                                ExpandResult::Ready(items) => items,
856                                ExpandResult::Retry(item) => {
857                                    // Reassemble the original invocation for retrying.
858                                    return ExpandResult::Retry(Invocation {
859                                        kind: InvocationKind::Attr { attr, pos, item, derives },
860                                        ..invoc
861                                    });
862                                }
863                            };
864                            if #[allow(non_exhaustive_omitted_patterns)] match fragment_kind {
    AstFragmentKind::Expr | AstFragmentKind::MethodReceiverExpr => true,
    _ => false,
}matches!(
865                                fragment_kind,
866                                AstFragmentKind::Expr | AstFragmentKind::MethodReceiverExpr
867                            ) && items.is_empty()
868                            {
869                                let guar = self.cx.dcx().emit_err(RemoveExprNotSupported { span });
870                                fragment_kind.dummy(span, guar)
871                            } else {
872                                let fragment = fragment_kind.expect_from_annotatables(items);
873                                if macro_stats {
874                                    update_attr_macro_stats(
875                                        self.cx,
876                                        fragment_kind,
877                                        span,
878                                        &meta.path,
879                                        &attr,
880                                        item_clone.unwrap(),
881                                        &fragment,
882                                    );
883                                }
884                                fragment
885                            }
886                        }
887                        Err(err) => {
888                            let _guar = err.emit();
889                            fragment_kind.expect_from_annotatables(iter::once(item))
890                        }
891                    }
892                } else if let SyntaxExtensionKind::NonMacroAttr = ext {
893                    // `-Zmacro-stats` ignores these because they don't do any real expansion.
894                    self.cx.expanded_inert_attrs.mark(&attr);
895                    item.visit_attrs(|attrs| attrs.insert(pos, attr));
896                    fragment_kind.expect_from_annotatables(iter::once(item))
897                } else {
898                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
899                }
900            }
901            InvocationKind::Derive { path, item, is_const } => match ext {
902                SyntaxExtensionKind::Derive(expander)
903                | SyntaxExtensionKind::LegacyDerive(expander) => {
904                    if let SyntaxExtensionKind::Derive(..) = ext {
905                        self.gate_proc_macro_input(&item);
906                    }
907                    // The `MetaItem` representing the trait to derive can't
908                    // have an unsafe around it (as of now).
909                    let meta = ast::MetaItem {
910                        unsafety: ast::Safety::Default,
911                        kind: MetaItemKind::Word,
912                        span,
913                        path,
914                    };
915                    let items = match expander.expand(self.cx, span, &meta, item, is_const) {
916                        ExpandResult::Ready(items) => items,
917                        ExpandResult::Retry(item) => {
918                            // Reassemble the original invocation for retrying.
919                            return ExpandResult::Retry(Invocation {
920                                kind: InvocationKind::Derive { path: meta.path, item, is_const },
921                                ..invoc
922                            });
923                        }
924                    };
925                    let fragment = fragment_kind.expect_from_annotatables(items);
926                    if macro_stats {
927                        update_derive_macro_stats(
928                            self.cx,
929                            fragment_kind,
930                            span,
931                            &meta.path,
932                            &fragment,
933                        );
934                    }
935                    fragment
936                }
937                SyntaxExtensionKind::MacroRules(expander)
938                    if expander.kinds().contains(MacroKinds::DERIVE) =>
939                {
940                    if is_const {
941                        let guar = self
942                            .cx
943                            .dcx()
944                            .span_err(span, "macro `derive` does not support const derives");
945                        return ExpandResult::Ready(fragment_kind.dummy(span, guar));
946                    }
947                    let body = item.to_tokens();
948                    match expander.expand_derive(self.cx, span, &body) {
949                        Ok(tok_result) => {
950                            let fragment =
951                                self.parse_ast_fragment(tok_result, fragment_kind, &path, span);
952                            if macro_stats {
953                                update_derive_macro_stats(
954                                    self.cx,
955                                    fragment_kind,
956                                    span,
957                                    &path,
958                                    &fragment,
959                                );
960                            }
961                            fragment
962                        }
963                        Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
964                    }
965                }
966                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
967            },
968            InvocationKind::GlobDelegation { item, of_trait } => {
969                let AssocItemKind::DelegationMac(deleg) = &item.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
970                let suffixes = match ext {
971                    SyntaxExtensionKind::GlobDelegation(expander) => match expander.expand(self.cx)
972                    {
973                        ExpandResult::Ready(suffixes) => suffixes,
974                        ExpandResult::Retry(()) => {
975                            // Reassemble the original invocation for retrying.
976                            return ExpandResult::Retry(Invocation {
977                                kind: InvocationKind::GlobDelegation { item, of_trait },
978                                ..invoc
979                            });
980                        }
981                    },
982                    SyntaxExtensionKind::Bang(..) => {
983                        let msg = "expanded a dummy glob delegation";
984                        let guar = self.cx.dcx().span_delayed_bug(span, msg);
985                        return ExpandResult::Ready(fragment_kind.dummy(span, guar));
986                    }
987                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
988                };
989
990                type Node = AstNodeWrapper<Box<ast::AssocItem>, ImplItemTag>;
991                let single_delegations = build_single_delegations::<Node>(
992                    self.cx, deleg, &item, &suffixes, item.span, true,
993                );
994                // `-Zmacro-stats` ignores these because they don't seem important.
995                fragment_kind.expect_from_annotatables(single_delegations.map(|item| {
996                    Annotatable::AssocItem(Box::new(item), AssocCtxt::Impl { of_trait })
997                }))
998            }
999        })
1000    }
1001
1002    fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
1003        let kind = match item {
1004            Annotatable::Item(_)
1005            | Annotatable::AssocItem(..)
1006            | Annotatable::ForeignItem(_)
1007            | Annotatable::Crate(..) => return,
1008            Annotatable::Stmt(stmt) => {
1009                // Attributes are stable on item statements,
1010                // but unstable on all other kinds of statements
1011                if stmt.is_item() {
1012                    return;
1013                }
1014                "statements"
1015            }
1016            Annotatable::Expr(_) => "expressions",
1017            Annotatable::Arm(..)
1018            | Annotatable::ExprField(..)
1019            | Annotatable::PatField(..)
1020            | Annotatable::GenericParam(..)
1021            | Annotatable::Param(..)
1022            | Annotatable::FieldDef(..)
1023            | Annotatable::Variant(..)
1024            | Annotatable::WherePredicate(..) => { ::core::panicking::panic_fmt(format_args!("unexpected annotatable")); }panic!("unexpected annotatable"),
1025        };
1026        if self.cx.ecfg.features.proc_macro_hygiene() {
1027            return;
1028        }
1029        feature_err(
1030            &self.cx.sess,
1031            sym::proc_macro_hygiene,
1032            span,
1033            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("custom attributes cannot be applied to {0}",
                kind))
    })format!("custom attributes cannot be applied to {kind}"),
1034        )
1035        .emit();
1036    }
1037
1038    fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
1039        struct GateProcMacroInput<'a> {
1040            sess: &'a Session,
1041        }
1042
1043        impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
1044            fn visit_item(&mut self, item: &'ast ast::Item) {
1045                match &item.kind {
1046                    ItemKind::Mod(_, _, mod_kind)
1047                        if !#[allow(non_exhaustive_omitted_patterns)] match mod_kind {
    ModKind::Loaded(_, Inline::Yes, _) => true,
    _ => false,
}matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _)) =>
1048                    {
1049                        feature_err(
1050                            self.sess,
1051                            sym::proc_macro_hygiene,
1052                            item.span,
1053                            fluent_generated::expand_file_modules_in_proc_macro_input_are_unstable,
1054                        )
1055                        .emit();
1056                    }
1057                    _ => {}
1058                }
1059
1060                visit::walk_item(self, item);
1061            }
1062        }
1063
1064        if !self.cx.ecfg.features.proc_macro_hygiene() {
1065            annotatable.visit_with(&mut GateProcMacroInput { sess: &self.cx.sess });
1066        }
1067    }
1068
1069    fn parse_ast_fragment(
1070        &mut self,
1071        toks: TokenStream,
1072        kind: AstFragmentKind,
1073        path: &ast::Path,
1074        span: Span,
1075    ) -> AstFragment {
1076        let mut parser = self.cx.new_parser_from_tts(toks);
1077        match parse_ast_fragment(&mut parser, kind) {
1078            Ok(fragment) => {
1079                ensure_complete_parse(&parser, path, kind.name(), span);
1080                fragment
1081            }
1082            Err(mut err) => {
1083                if err.span.is_dummy() {
1084                    err.span(span);
1085                }
1086                annotate_err_with_kind(&mut err, kind, span);
1087                let guar = err.emit();
1088                self.cx.macro_error_and_trace_macros_diag();
1089                kind.dummy(span, guar)
1090            }
1091        }
1092    }
1093}
1094
1095pub fn parse_ast_fragment<'a>(
1096    this: &mut Parser<'a>,
1097    kind: AstFragmentKind,
1098) -> PResult<'a, AstFragment> {
1099    Ok(match kind {
1100        AstFragmentKind::Items => {
1101            let mut items = SmallVec::new();
1102            while let Some(item) = this.parse_item(ForceCollect::No, AllowConstBlockItems::Yes)? {
1103                items.push(item);
1104            }
1105            AstFragment::Items(items)
1106        }
1107        AstFragmentKind::TraitItems => {
1108            let mut items = SmallVec::new();
1109            while let Some(item) = this.parse_trait_item(ForceCollect::No)? {
1110                items.extend(item);
1111            }
1112            AstFragment::TraitItems(items)
1113        }
1114        AstFragmentKind::ImplItems => {
1115            let mut items = SmallVec::new();
1116            while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
1117                items.extend(item);
1118            }
1119            AstFragment::ImplItems(items)
1120        }
1121        AstFragmentKind::TraitImplItems => {
1122            let mut items = SmallVec::new();
1123            while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
1124                items.extend(item);
1125            }
1126            AstFragment::TraitImplItems(items)
1127        }
1128        AstFragmentKind::ForeignItems => {
1129            let mut items = SmallVec::new();
1130            while let Some(item) = this.parse_foreign_item(ForceCollect::No)? {
1131                items.extend(item);
1132            }
1133            AstFragment::ForeignItems(items)
1134        }
1135        AstFragmentKind::Stmts => {
1136            let mut stmts = SmallVec::new();
1137            // Won't make progress on a `}`.
1138            while this.token != token::Eof && this.token != token::CloseBrace {
1139                if let Some(stmt) = this.parse_full_stmt(AttemptLocalParseRecovery::Yes)? {
1140                    stmts.push(stmt);
1141                }
1142            }
1143            AstFragment::Stmts(stmts)
1144        }
1145        AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
1146        AstFragmentKind::MethodReceiverExpr => AstFragment::MethodReceiverExpr(this.parse_expr()?),
1147        AstFragmentKind::OptExpr => {
1148            if this.token != token::Eof {
1149                AstFragment::OptExpr(Some(this.parse_expr()?))
1150            } else {
1151                AstFragment::OptExpr(None)
1152            }
1153        }
1154        AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
1155        AstFragmentKind::Pat => AstFragment::Pat(Box::new(this.parse_pat_allow_top_guard(
1156            None,
1157            RecoverComma::No,
1158            RecoverColon::Yes,
1159            CommaRecoveryMode::LikelyTuple,
1160        )?)),
1161        AstFragmentKind::Crate => AstFragment::Crate(this.parse_crate_mod()?),
1162        AstFragmentKind::Arms
1163        | AstFragmentKind::ExprFields
1164        | AstFragmentKind::PatFields
1165        | AstFragmentKind::GenericParams
1166        | AstFragmentKind::Params
1167        | AstFragmentKind::FieldDefs
1168        | AstFragmentKind::Variants
1169        | AstFragmentKind::WherePredicates => {
    ::core::panicking::panic_fmt(format_args!("unexpected AST fragment kind"));
}panic!("unexpected AST fragment kind"),
1170    })
1171}
1172
1173pub(crate) fn ensure_complete_parse<'a>(
1174    parser: &Parser<'a>,
1175    macro_path: &ast::Path,
1176    kind_name: &str,
1177    span: Span,
1178) {
1179    if parser.token != token::Eof {
1180        let descr = token_descr(&parser.token);
1181        // Avoid emitting backtrace info twice.
1182        let def_site_span = parser.token.span.with_ctxt(SyntaxContext::root());
1183
1184        let semi_span = parser.psess.source_map().next_point(span);
1185        let add_semicolon = match &parser.psess.source_map().span_to_snippet(semi_span) {
1186            Ok(snippet) if &snippet[..] != ";" && kind_name == "expression" => {
1187                Some(span.shrink_to_hi())
1188            }
1189            _ => None,
1190        };
1191
1192        let expands_to_match_arm = kind_name == "pattern" && parser.token == token::FatArrow;
1193
1194        parser.dcx().emit_err(IncompleteParse {
1195            span: def_site_span,
1196            descr,
1197            label_span: span,
1198            macro_path,
1199            kind_name,
1200            expands_to_match_arm,
1201            add_semicolon,
1202        });
1203    }
1204}
1205
1206/// Wraps a call to `walk_*` / `walk_flat_map_*`
1207/// for an AST node that supports attributes
1208/// (see the `Annotatable` enum)
1209/// This method assigns a `NodeId`, and sets that `NodeId`
1210/// as our current 'lint node id'. If a macro call is found
1211/// inside this AST node, we will use this AST node's `NodeId`
1212/// to emit lints associated with that macro (allowing
1213/// `#[allow]` / `#[deny]` to be applied close to
1214/// the macro invocation).
1215///
1216/// Do *not* call this for a macro AST node
1217/// (e.g. `ExprKind::MacCall`) - we cannot emit lints
1218/// at these AST nodes, since they are removed and
1219/// replaced with the result of macro expansion.
1220///
1221/// All other `NodeId`s are assigned by `visit_id`.
1222/// * `self` is the 'self' parameter for the current method,
1223/// * `id` is a mutable reference to the `NodeId` field
1224///    of the current AST node.
1225/// * `closure` is a closure that executes the
1226///   `walk_*` / `walk_flat_map_*` method
1227///   for the current AST node.
1228macro_rules! assign_id {
1229    ($self:ident, $id:expr, $closure:expr) => {{
1230        let old_id = $self.cx.current_expansion.lint_node_id;
1231        if $self.monotonic {
1232            debug_assert_eq!(*$id, ast::DUMMY_NODE_ID);
1233            let new_id = $self.cx.resolver.next_node_id();
1234            *$id = new_id;
1235            $self.cx.current_expansion.lint_node_id = new_id;
1236        }
1237        let ret = ($closure)();
1238        $self.cx.current_expansion.lint_node_id = old_id;
1239        ret
1240    }};
1241}
1242
1243enum AddSemicolon {
1244    Yes,
1245    No,
1246}
1247
1248/// A trait implemented for all `AstFragment` nodes and providing all pieces
1249/// of functionality used by `InvocationCollector`.
1250trait InvocationCollectorNode: HasAttrs + HasNodeId + Sized {
1251    type OutputTy = SmallVec<[Self; 1]>;
1252    type ItemKind = ItemKind;
1253    const KIND: AstFragmentKind;
1254    fn to_annotatable(self) -> Annotatable;
1255    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy;
1256    fn descr() -> &'static str {
1257        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1258    }
1259    fn walk_flat_map(self, _collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1260        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1261    }
1262    fn walk(&mut self, _collector: &mut InvocationCollector<'_, '_>) {
1263        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1264    }
1265    fn is_mac_call(&self) -> bool {
1266        false
1267    }
1268    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1269        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1270    }
1271    fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1272        None
1273    }
1274    fn delegation_item_kind(_deleg: Box<ast::Delegation>) -> Self::ItemKind {
1275        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1276    }
1277    fn from_item(_item: ast::Item<Self::ItemKind>) -> Self {
1278        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1279    }
1280    fn flatten_outputs(_outputs: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1281        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1282    }
1283    fn pre_flat_map_node_collect_attr(_cfg: &StripUnconfigured<'_>, _attr: &ast::Attribute) {}
1284    fn post_flat_map_node_collect_bang(_output: &mut Self::OutputTy, _add_semicolon: AddSemicolon) {
1285    }
1286    fn wrap_flat_map_node_walk_flat_map(
1287        node: Self,
1288        collector: &mut InvocationCollector<'_, '_>,
1289        walk_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1290    ) -> Result<Self::OutputTy, Self> {
1291        Ok(walk_flat_map(node, collector))
1292    }
1293    fn expand_cfg_false(
1294        &mut self,
1295        collector: &mut InvocationCollector<'_, '_>,
1296        _pos: usize,
1297        span: Span,
1298    ) {
1299        collector.cx.dcx().emit_err(RemoveNodeNotSupported { span, descr: Self::descr() });
1300    }
1301
1302    /// All of the identifiers (items) declared by this node.
1303    /// This is an approximation and should only be used for diagnostics.
1304    fn declared_idents(&self) -> Vec<Ident> {
1305        ::alloc::vec::Vec::new()vec![]
1306    }
1307}
1308
1309impl InvocationCollectorNode for Box<ast::Item> {
1310    const KIND: AstFragmentKind = AstFragmentKind::Items;
1311    fn to_annotatable(self) -> Annotatable {
1312        Annotatable::Item(self)
1313    }
1314    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1315        fragment.make_items()
1316    }
1317    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1318        walk_flat_map_item(collector, self)
1319    }
1320    fn is_mac_call(&self) -> bool {
1321        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ItemKind::MacCall(..) => true,
    _ => false,
}matches!(self.kind, ItemKind::MacCall(..))
1322    }
1323    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1324        match self.kind {
1325            ItemKind::MacCall(mac) => (mac, self.attrs, AddSemicolon::No),
1326            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1327        }
1328    }
1329    fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1330        match &self.kind {
1331            ItemKind::DelegationMac(deleg) => Some((deleg, self)),
1332            _ => None,
1333        }
1334    }
1335    fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1336        ItemKind::Delegation(deleg)
1337    }
1338    fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1339        Box::new(item)
1340    }
1341    fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1342        items.flatten().collect()
1343    }
1344    fn wrap_flat_map_node_walk_flat_map(
1345        mut node: Self,
1346        collector: &mut InvocationCollector<'_, '_>,
1347        walk_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy,
1348    ) -> Result<Self::OutputTy, Self> {
1349        if !#[allow(non_exhaustive_omitted_patterns)] match node.kind {
    ItemKind::Mod(..) => true,
    _ => false,
}matches!(node.kind, ItemKind::Mod(..)) {
1350            return Ok(walk_flat_map(node, collector));
1351        }
1352
1353        // Work around borrow checker not seeing through `P`'s deref.
1354        let (span, mut attrs) = (node.span, mem::take(&mut node.attrs));
1355        let ItemKind::Mod(_, ident, ref mut mod_kind) = node.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1356        let ecx = &mut collector.cx;
1357        let (file_path, dir_path, dir_ownership) = match mod_kind {
1358            ModKind::Loaded(_, inline, _) => {
1359                // Inline `mod foo { ... }`, but we still need to push directories.
1360                let (dir_path, dir_ownership) = mod_dir_path(
1361                    ecx.sess,
1362                    ident,
1363                    &attrs,
1364                    &ecx.current_expansion.module,
1365                    ecx.current_expansion.dir_ownership,
1366                    *inline,
1367                );
1368                // If the module was parsed from an external file, recover its path.
1369                // This lets `parse_external_mod` catch cycles if it's self-referential.
1370                let file_path = match inline {
1371                    Inline::Yes => None,
1372                    Inline::No { .. } => mod_file_path_from_attr(ecx.sess, &attrs, &dir_path),
1373                };
1374                node.attrs = attrs;
1375                (file_path, dir_path, dir_ownership)
1376            }
1377            ModKind::Unloaded => {
1378                // We have an outline `mod foo;` so we need to parse the file.
1379                let old_attrs_len = attrs.len();
1380                let ParsedExternalMod {
1381                    items,
1382                    spans,
1383                    file_path,
1384                    dir_path,
1385                    dir_ownership,
1386                    had_parse_error,
1387                } = parse_external_mod(
1388                    ecx.sess,
1389                    ident,
1390                    span,
1391                    &ecx.current_expansion.module,
1392                    ecx.current_expansion.dir_ownership,
1393                    &mut attrs,
1394                );
1395
1396                if let Some(lint_store) = ecx.lint_store {
1397                    lint_store.pre_expansion_lint(
1398                        ecx.sess,
1399                        ecx.ecfg.features,
1400                        ecx.resolver.registered_tools(),
1401                        ecx.current_expansion.lint_node_id,
1402                        &attrs,
1403                        &items,
1404                        ident.name,
1405                    );
1406                }
1407
1408                *mod_kind = ModKind::Loaded(items, Inline::No { had_parse_error }, spans);
1409                node.attrs = attrs;
1410                if node.attrs.len() > old_attrs_len {
1411                    // If we loaded an out-of-line module and added some inner attributes,
1412                    // then we need to re-configure it and re-collect attributes for
1413                    // resolution and expansion.
1414                    return Err(node);
1415                }
1416                (Some(file_path), dir_path, dir_ownership)
1417            }
1418        };
1419
1420        // Set the module info before we flat map.
1421        let mut module = ecx.current_expansion.module.with_dir_path(dir_path);
1422        module.mod_path.push(ident);
1423        if let Some(file_path) = file_path {
1424            module.file_path_stack.push(file_path);
1425        }
1426
1427        let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module));
1428        let orig_dir_ownership =
1429            mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership);
1430
1431        let res = Ok(walk_flat_map(node, collector));
1432
1433        collector.cx.current_expansion.dir_ownership = orig_dir_ownership;
1434        collector.cx.current_expansion.module = orig_module;
1435        res
1436    }
1437
1438    fn declared_idents(&self) -> Vec<Ident> {
1439        if let ItemKind::Use(ut) = &self.kind {
1440            fn collect_use_tree_leaves(ut: &ast::UseTree, idents: &mut Vec<Ident>) {
1441                match &ut.kind {
1442                    ast::UseTreeKind::Glob => {}
1443                    ast::UseTreeKind::Simple(_) => idents.push(ut.ident()),
1444                    ast::UseTreeKind::Nested { items, .. } => {
1445                        for (ut, _) in items {
1446                            collect_use_tree_leaves(ut, idents);
1447                        }
1448                    }
1449                }
1450            }
1451            let mut idents = Vec::new();
1452            collect_use_tree_leaves(&ut, &mut idents);
1453            idents
1454        } else {
1455            self.kind.ident().into_iter().collect()
1456        }
1457    }
1458}
1459
1460struct TraitItemTag;
1461impl InvocationCollectorNode for AstNodeWrapper<Box<ast::AssocItem>, TraitItemTag> {
1462    type OutputTy = SmallVec<[Box<ast::AssocItem>; 1]>;
1463    type ItemKind = AssocItemKind;
1464    const KIND: AstFragmentKind = AstFragmentKind::TraitItems;
1465    fn to_annotatable(self) -> Annotatable {
1466        Annotatable::AssocItem(self.wrapped, AssocCtxt::Trait)
1467    }
1468    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1469        fragment.make_trait_items()
1470    }
1471    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1472        walk_flat_map_assoc_item(collector, self.wrapped, AssocCtxt::Trait)
1473    }
1474    fn is_mac_call(&self) -> bool {
1475        #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
    AssocItemKind::MacCall(..) => true,
    _ => false,
}matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1476    }
1477    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1478        let item = self.wrapped;
1479        match item.kind {
1480            AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1481            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1482        }
1483    }
1484    fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1485        match &self.wrapped.kind {
1486            AssocItemKind::DelegationMac(deleg) => Some((deleg, &self.wrapped)),
1487            _ => None,
1488        }
1489    }
1490    fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1491        AssocItemKind::Delegation(deleg)
1492    }
1493    fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1494        AstNodeWrapper::new(Box::new(item), TraitItemTag)
1495    }
1496    fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1497        items.flatten().collect()
1498    }
1499}
1500
1501struct ImplItemTag;
1502impl InvocationCollectorNode for AstNodeWrapper<Box<ast::AssocItem>, ImplItemTag> {
1503    type OutputTy = SmallVec<[Box<ast::AssocItem>; 1]>;
1504    type ItemKind = AssocItemKind;
1505    const KIND: AstFragmentKind = AstFragmentKind::ImplItems;
1506    fn to_annotatable(self) -> Annotatable {
1507        Annotatable::AssocItem(self.wrapped, AssocCtxt::Impl { of_trait: false })
1508    }
1509    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1510        fragment.make_impl_items()
1511    }
1512    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1513        walk_flat_map_assoc_item(collector, self.wrapped, AssocCtxt::Impl { of_trait: false })
1514    }
1515    fn is_mac_call(&self) -> bool {
1516        #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
    AssocItemKind::MacCall(..) => true,
    _ => false,
}matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1517    }
1518    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1519        let item = self.wrapped;
1520        match item.kind {
1521            AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1522            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1523        }
1524    }
1525    fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1526        match &self.wrapped.kind {
1527            AssocItemKind::DelegationMac(deleg) => Some((deleg, &self.wrapped)),
1528            _ => None,
1529        }
1530    }
1531    fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1532        AssocItemKind::Delegation(deleg)
1533    }
1534    fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1535        AstNodeWrapper::new(Box::new(item), ImplItemTag)
1536    }
1537    fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1538        items.flatten().collect()
1539    }
1540}
1541
1542struct TraitImplItemTag;
1543impl InvocationCollectorNode for AstNodeWrapper<Box<ast::AssocItem>, TraitImplItemTag> {
1544    type OutputTy = SmallVec<[Box<ast::AssocItem>; 1]>;
1545    type ItemKind = AssocItemKind;
1546    const KIND: AstFragmentKind = AstFragmentKind::TraitImplItems;
1547    fn to_annotatable(self) -> Annotatable {
1548        Annotatable::AssocItem(self.wrapped, AssocCtxt::Impl { of_trait: true })
1549    }
1550    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1551        fragment.make_trait_impl_items()
1552    }
1553    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1554        walk_flat_map_assoc_item(collector, self.wrapped, AssocCtxt::Impl { of_trait: true })
1555    }
1556    fn is_mac_call(&self) -> bool {
1557        #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
    AssocItemKind::MacCall(..) => true,
    _ => false,
}matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1558    }
1559    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1560        let item = self.wrapped;
1561        match item.kind {
1562            AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1563            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1564        }
1565    }
1566    fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1567        match &self.wrapped.kind {
1568            AssocItemKind::DelegationMac(deleg) => Some((deleg, &self.wrapped)),
1569            _ => None,
1570        }
1571    }
1572    fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1573        AssocItemKind::Delegation(deleg)
1574    }
1575    fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1576        AstNodeWrapper::new(Box::new(item), TraitImplItemTag)
1577    }
1578    fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1579        items.flatten().collect()
1580    }
1581}
1582
1583impl InvocationCollectorNode for Box<ast::ForeignItem> {
1584    const KIND: AstFragmentKind = AstFragmentKind::ForeignItems;
1585    fn to_annotatable(self) -> Annotatable {
1586        Annotatable::ForeignItem(self)
1587    }
1588    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1589        fragment.make_foreign_items()
1590    }
1591    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1592        walk_flat_map_foreign_item(collector, self)
1593    }
1594    fn is_mac_call(&self) -> bool {
1595        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ForeignItemKind::MacCall(..) => true,
    _ => false,
}matches!(self.kind, ForeignItemKind::MacCall(..))
1596    }
1597    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1598        match self.kind {
1599            ForeignItemKind::MacCall(mac) => (mac, self.attrs, AddSemicolon::No),
1600            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1601        }
1602    }
1603}
1604
1605impl InvocationCollectorNode for ast::Variant {
1606    const KIND: AstFragmentKind = AstFragmentKind::Variants;
1607    fn to_annotatable(self) -> Annotatable {
1608        Annotatable::Variant(self)
1609    }
1610    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1611        fragment.make_variants()
1612    }
1613    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1614        walk_flat_map_variant(collector, self)
1615    }
1616}
1617
1618impl InvocationCollectorNode for ast::WherePredicate {
1619    const KIND: AstFragmentKind = AstFragmentKind::WherePredicates;
1620    fn to_annotatable(self) -> Annotatable {
1621        Annotatable::WherePredicate(self)
1622    }
1623    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1624        fragment.make_where_predicates()
1625    }
1626    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1627        walk_flat_map_where_predicate(collector, self)
1628    }
1629}
1630
1631impl InvocationCollectorNode for ast::FieldDef {
1632    const KIND: AstFragmentKind = AstFragmentKind::FieldDefs;
1633    fn to_annotatable(self) -> Annotatable {
1634        Annotatable::FieldDef(self)
1635    }
1636    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1637        fragment.make_field_defs()
1638    }
1639    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1640        walk_flat_map_field_def(collector, self)
1641    }
1642}
1643
1644impl InvocationCollectorNode for ast::PatField {
1645    const KIND: AstFragmentKind = AstFragmentKind::PatFields;
1646    fn to_annotatable(self) -> Annotatable {
1647        Annotatable::PatField(self)
1648    }
1649    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1650        fragment.make_pat_fields()
1651    }
1652    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1653        walk_flat_map_pat_field(collector, self)
1654    }
1655}
1656
1657impl InvocationCollectorNode for ast::ExprField {
1658    const KIND: AstFragmentKind = AstFragmentKind::ExprFields;
1659    fn to_annotatable(self) -> Annotatable {
1660        Annotatable::ExprField(self)
1661    }
1662    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1663        fragment.make_expr_fields()
1664    }
1665    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1666        walk_flat_map_expr_field(collector, self)
1667    }
1668}
1669
1670impl InvocationCollectorNode for ast::Param {
1671    const KIND: AstFragmentKind = AstFragmentKind::Params;
1672    fn to_annotatable(self) -> Annotatable {
1673        Annotatable::Param(self)
1674    }
1675    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1676        fragment.make_params()
1677    }
1678    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1679        walk_flat_map_param(collector, self)
1680    }
1681}
1682
1683impl InvocationCollectorNode for ast::GenericParam {
1684    const KIND: AstFragmentKind = AstFragmentKind::GenericParams;
1685    fn to_annotatable(self) -> Annotatable {
1686        Annotatable::GenericParam(self)
1687    }
1688    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1689        fragment.make_generic_params()
1690    }
1691    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1692        walk_flat_map_generic_param(collector, self)
1693    }
1694}
1695
1696impl InvocationCollectorNode for ast::Arm {
1697    const KIND: AstFragmentKind = AstFragmentKind::Arms;
1698    fn to_annotatable(self) -> Annotatable {
1699        Annotatable::Arm(self)
1700    }
1701    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1702        fragment.make_arms()
1703    }
1704    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1705        walk_flat_map_arm(collector, self)
1706    }
1707}
1708
1709impl InvocationCollectorNode for ast::Stmt {
1710    const KIND: AstFragmentKind = AstFragmentKind::Stmts;
1711    fn to_annotatable(self) -> Annotatable {
1712        Annotatable::Stmt(Box::new(self))
1713    }
1714    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1715        fragment.make_stmts()
1716    }
1717    fn walk_flat_map(self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1718        walk_flat_map_stmt(collector, self)
1719    }
1720    fn is_mac_call(&self) -> bool {
1721        match &self.kind {
1722            StmtKind::MacCall(..) => true,
1723            StmtKind::Item(item) => #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ItemKind::MacCall(..) => true,
    _ => false,
}matches!(item.kind, ItemKind::MacCall(..)),
1724            StmtKind::Semi(expr) => #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::MacCall(..) => true,
    _ => false,
}matches!(expr.kind, ExprKind::MacCall(..)),
1725            StmtKind::Expr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1726            StmtKind::Let(..) | StmtKind::Empty => false,
1727        }
1728    }
1729    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1730        // We pull macro invocations (both attributes and fn-like macro calls) out of their
1731        // `StmtKind`s and treat them as statement macro invocations, not as items or expressions.
1732        let (add_semicolon, mac, attrs) = match self.kind {
1733            StmtKind::MacCall(mac) => {
1734                let ast::MacCallStmt { mac, style, attrs, .. } = *mac;
1735                (style == MacStmtStyle::Semicolon, mac, attrs)
1736            }
1737            StmtKind::Item(item) => match *item {
1738                ast::Item { kind: ItemKind::MacCall(mac), attrs, .. } => {
1739                    (mac.args.need_semicolon(), mac, attrs)
1740                }
1741                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1742            },
1743            StmtKind::Semi(expr) => match *expr {
1744                ast::Expr { kind: ExprKind::MacCall(mac), attrs, .. } => {
1745                    (mac.args.need_semicolon(), mac, attrs)
1746                }
1747                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1748            },
1749            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1750        };
1751        (mac, attrs, if add_semicolon { AddSemicolon::Yes } else { AddSemicolon::No })
1752    }
1753    fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1754        match &self.kind {
1755            StmtKind::Item(item) => match &item.kind {
1756                ItemKind::DelegationMac(deleg) => Some((deleg, item)),
1757                _ => None,
1758            },
1759            _ => None,
1760        }
1761    }
1762    fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1763        ItemKind::Delegation(deleg)
1764    }
1765    fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1766        ast::Stmt { id: ast::DUMMY_NODE_ID, span: item.span, kind: StmtKind::Item(Box::new(item)) }
1767    }
1768    fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1769        items.flatten().collect()
1770    }
1771    fn post_flat_map_node_collect_bang(stmts: &mut Self::OutputTy, add_semicolon: AddSemicolon) {
1772        // If this is a macro invocation with a semicolon, then apply that
1773        // semicolon to the final statement produced by expansion.
1774        if #[allow(non_exhaustive_omitted_patterns)] match add_semicolon {
    AddSemicolon::Yes => true,
    _ => false,
}matches!(add_semicolon, AddSemicolon::Yes) {
1775            if let Some(stmt) = stmts.pop() {
1776                stmts.push(stmt.add_trailing_semicolon());
1777            }
1778        }
1779    }
1780}
1781
1782impl InvocationCollectorNode for ast::Crate {
1783    type OutputTy = ast::Crate;
1784    const KIND: AstFragmentKind = AstFragmentKind::Crate;
1785    fn to_annotatable(self) -> Annotatable {
1786        Annotatable::Crate(self)
1787    }
1788    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1789        fragment.make_crate()
1790    }
1791    fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1792        walk_crate(collector, self)
1793    }
1794    fn expand_cfg_false(
1795        &mut self,
1796        collector: &mut InvocationCollector<'_, '_>,
1797        pos: usize,
1798        _span: Span,
1799    ) {
1800        // Attributes above `cfg(FALSE)` are left in place, because we may want to configure
1801        // some global crate properties even on fully unconfigured crates.
1802        self.attrs.truncate(pos);
1803        // Standard prelude imports are left in the crate for backward compatibility.
1804        self.items.truncate(collector.cx.num_standard_library_imports);
1805    }
1806}
1807
1808impl InvocationCollectorNode for ast::Ty {
1809    type OutputTy = Box<ast::Ty>;
1810    const KIND: AstFragmentKind = AstFragmentKind::Ty;
1811    fn to_annotatable(self) -> Annotatable {
1812        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1813    }
1814    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1815        fragment.make_ty()
1816    }
1817    fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1818        // Save the pre-expanded name of this `ImplTrait`, so that later when defining
1819        // an APIT we use a name that doesn't have any placeholder fragments in it.
1820        if let ast::TyKind::ImplTrait(..) = self.kind {
1821            // HACK: pprust breaks strings with newlines when the type
1822            // gets too long. We don't want these to show up in compiler
1823            // output or built artifacts, so replace them here...
1824            // Perhaps we should instead format APITs more robustly.
1825            let name = Symbol::intern(&pprust::ty_to_string(self).replace('\n', " "));
1826            collector.cx.resolver.insert_impl_trait_name(self.id, name);
1827        }
1828        walk_ty(collector, self)
1829    }
1830    fn is_mac_call(&self) -> bool {
1831        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ast::TyKind::MacCall(..) => true,
    _ => false,
}matches!(self.kind, ast::TyKind::MacCall(..))
1832    }
1833    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1834        match self.kind {
1835            TyKind::MacCall(mac) => (mac, AttrVec::new(), AddSemicolon::No),
1836            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1837        }
1838    }
1839}
1840
1841impl InvocationCollectorNode for ast::Pat {
1842    type OutputTy = Box<ast::Pat>;
1843    const KIND: AstFragmentKind = AstFragmentKind::Pat;
1844    fn to_annotatable(self) -> Annotatable {
1845        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1846    }
1847    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1848        fragment.make_pat()
1849    }
1850    fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1851        walk_pat(collector, self)
1852    }
1853    fn is_mac_call(&self) -> bool {
1854        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    PatKind::MacCall(..) => true,
    _ => false,
}matches!(self.kind, PatKind::MacCall(..))
1855    }
1856    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1857        match self.kind {
1858            PatKind::MacCall(mac) => (mac, AttrVec::new(), AddSemicolon::No),
1859            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1860        }
1861    }
1862}
1863
1864impl InvocationCollectorNode for ast::Expr {
1865    type OutputTy = Box<ast::Expr>;
1866    const KIND: AstFragmentKind = AstFragmentKind::Expr;
1867    fn to_annotatable(self) -> Annotatable {
1868        Annotatable::Expr(Box::new(self))
1869    }
1870    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1871        fragment.make_expr()
1872    }
1873    fn descr() -> &'static str {
1874        "an expression"
1875    }
1876    fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1877        walk_expr(collector, self)
1878    }
1879    fn is_mac_call(&self) -> bool {
1880        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ExprKind::MacCall(..) => true,
    _ => false,
}matches!(self.kind, ExprKind::MacCall(..))
1881    }
1882    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1883        match self.kind {
1884            ExprKind::MacCall(mac) => (mac, self.attrs, AddSemicolon::No),
1885            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1886        }
1887    }
1888}
1889
1890struct OptExprTag;
1891impl InvocationCollectorNode for AstNodeWrapper<Box<ast::Expr>, OptExprTag> {
1892    type OutputTy = Option<Box<ast::Expr>>;
1893    const KIND: AstFragmentKind = AstFragmentKind::OptExpr;
1894    fn to_annotatable(self) -> Annotatable {
1895        Annotatable::Expr(self.wrapped)
1896    }
1897    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1898        fragment.make_opt_expr()
1899    }
1900    fn walk_flat_map(mut self, collector: &mut InvocationCollector<'_, '_>) -> Self::OutputTy {
1901        walk_expr(collector, &mut self.wrapped);
1902        Some(self.wrapped)
1903    }
1904    fn is_mac_call(&self) -> bool {
1905        #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
    ast::ExprKind::MacCall(..) => true,
    _ => false,
}matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
1906    }
1907    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1908        let node = self.wrapped;
1909        match node.kind {
1910            ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1911            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1912        }
1913    }
1914    fn pre_flat_map_node_collect_attr(cfg: &StripUnconfigured<'_>, attr: &ast::Attribute) {
1915        cfg.maybe_emit_expr_attr_err(attr);
1916    }
1917}
1918
1919/// This struct is a hack to workaround unstable of `stmt_expr_attributes`.
1920/// It can be removed once that feature is stabilized.
1921struct MethodReceiverTag;
1922
1923impl InvocationCollectorNode for AstNodeWrapper<ast::Expr, MethodReceiverTag> {
1924    type OutputTy = AstNodeWrapper<Box<ast::Expr>, MethodReceiverTag>;
1925    const KIND: AstFragmentKind = AstFragmentKind::MethodReceiverExpr;
1926    fn descr() -> &'static str {
1927        "an expression"
1928    }
1929    fn to_annotatable(self) -> Annotatable {
1930        Annotatable::Expr(Box::new(self.wrapped))
1931    }
1932    fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1933        AstNodeWrapper::new(fragment.make_method_receiver_expr(), MethodReceiverTag)
1934    }
1935    fn walk(&mut self, collector: &mut InvocationCollector<'_, '_>) {
1936        walk_expr(collector, &mut self.wrapped)
1937    }
1938    fn is_mac_call(&self) -> bool {
1939        #[allow(non_exhaustive_omitted_patterns)] match self.wrapped.kind {
    ast::ExprKind::MacCall(..) => true,
    _ => false,
}matches!(self.wrapped.kind, ast::ExprKind::MacCall(..))
1940    }
1941    fn take_mac_call(self) -> (Box<ast::MacCall>, ast::AttrVec, AddSemicolon) {
1942        let node = self.wrapped;
1943        match node.kind {
1944            ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No),
1945            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1946        }
1947    }
1948}
1949
1950fn build_single_delegations<'a, Node: InvocationCollectorNode>(
1951    ecx: &ExtCtxt<'_>,
1952    deleg: &'a ast::DelegationMac,
1953    item: &'a ast::Item<Node::ItemKind>,
1954    suffixes: &'a [(Ident, Option<Ident>)],
1955    item_span: Span,
1956    from_glob: bool,
1957) -> impl Iterator<Item = ast::Item<Node::ItemKind>> + 'a {
1958    if suffixes.is_empty() {
1959        // Report an error for now, to avoid keeping stem for resolution and
1960        // stability checks.
1961        let kind = String::from(if from_glob { "glob" } else { "list" });
1962        ecx.dcx().emit_err(EmptyDelegationMac { span: item.span, kind });
1963    }
1964
1965    suffixes.iter().map(move |&(ident, rename)| {
1966        let mut path = deleg.prefix.clone();
1967        path.segments.push(ast::PathSegment { ident, id: ast::DUMMY_NODE_ID, args: None });
1968
1969        ast::Item {
1970            attrs: item.attrs.clone(),
1971            id: ast::DUMMY_NODE_ID,
1972            span: if from_glob { item_span } else { ident.span },
1973            vis: item.vis.clone(),
1974            kind: Node::delegation_item_kind(Box::new(ast::Delegation {
1975                id: ast::DUMMY_NODE_ID,
1976                qself: deleg.qself.clone(),
1977                path,
1978                ident: rename.unwrap_or(ident),
1979                rename,
1980                body: deleg.body.clone(),
1981                from_glob,
1982            })),
1983            tokens: None,
1984        }
1985    })
1986}
1987
1988/// Required for `visit_node` obtained an owned `Node` from `&mut Node`.
1989trait DummyAstNode {
1990    fn dummy() -> Self;
1991}
1992
1993impl DummyAstNode for ast::Crate {
1994    fn dummy() -> Self {
1995        ast::Crate {
1996            attrs: Default::default(),
1997            items: Default::default(),
1998            spans: Default::default(),
1999            id: DUMMY_NODE_ID,
2000            is_placeholder: Default::default(),
2001        }
2002    }
2003}
2004
2005impl DummyAstNode for ast::Ty {
2006    fn dummy() -> Self {
2007        ast::Ty {
2008            id: DUMMY_NODE_ID,
2009            kind: TyKind::Dummy,
2010            span: Default::default(),
2011            tokens: Default::default(),
2012        }
2013    }
2014}
2015
2016impl DummyAstNode for ast::Pat {
2017    fn dummy() -> Self {
2018        ast::Pat {
2019            id: DUMMY_NODE_ID,
2020            kind: PatKind::Wild,
2021            span: Default::default(),
2022            tokens: Default::default(),
2023        }
2024    }
2025}
2026
2027impl DummyAstNode for ast::Expr {
2028    fn dummy() -> Self {
2029        ast::Expr::dummy()
2030    }
2031}
2032
2033impl DummyAstNode for AstNodeWrapper<ast::Expr, MethodReceiverTag> {
2034    fn dummy() -> Self {
2035        AstNodeWrapper::new(ast::Expr::dummy(), MethodReceiverTag)
2036    }
2037}
2038
2039struct InvocationCollector<'a, 'b> {
2040    cx: &'a mut ExtCtxt<'b>,
2041    invocations: Vec<(Invocation, Option<Arc<SyntaxExtension>>)>,
2042    monotonic: bool,
2043}
2044
2045impl<'a, 'b> InvocationCollector<'a, 'b> {
2046    fn cfg(&self) -> StripUnconfigured<'_> {
2047        StripUnconfigured {
2048            sess: self.cx.sess,
2049            features: Some(self.cx.ecfg.features),
2050            config_tokens: false,
2051            lint_node_id: self.cx.current_expansion.lint_node_id,
2052        }
2053    }
2054
2055    fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
2056        let expn_id = LocalExpnId::fresh_empty();
2057        if #[allow(non_exhaustive_omitted_patterns)] match kind {
    InvocationKind::GlobDelegation { .. } => true,
    _ => false,
}matches!(kind, InvocationKind::GlobDelegation { .. }) {
2058            // In resolver we need to know which invocation ids are delegations early,
2059            // before their `ExpnData` is filled.
2060            self.cx.resolver.register_glob_delegation(expn_id);
2061        }
2062        let vis = kind.placeholder_visibility();
2063        self.invocations.push((
2064            Invocation {
2065                kind,
2066                fragment_kind,
2067                expansion_data: ExpansionData {
2068                    id: expn_id,
2069                    depth: self.cx.current_expansion.depth + 1,
2070                    ..self.cx.current_expansion.clone()
2071                },
2072            },
2073            None,
2074        ));
2075        placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
2076    }
2077
2078    fn collect_bang(&mut self, mac: Box<ast::MacCall>, kind: AstFragmentKind) -> AstFragment {
2079        // cache the macro call span so that it can be
2080        // easily adjusted for incremental compilation
2081        let span = mac.span();
2082        self.collect(kind, InvocationKind::Bang { mac, span })
2083    }
2084
2085    fn collect_attr(
2086        &mut self,
2087        (attr, pos, derives): (ast::Attribute, usize, Vec<ast::Path>),
2088        item: Annotatable,
2089        kind: AstFragmentKind,
2090    ) -> AstFragment {
2091        self.collect(kind, InvocationKind::Attr { attr, pos, item, derives })
2092    }
2093
2094    fn collect_glob_delegation(
2095        &mut self,
2096        item: Box<ast::AssocItem>,
2097        of_trait: bool,
2098        kind: AstFragmentKind,
2099    ) -> AstFragment {
2100        self.collect(kind, InvocationKind::GlobDelegation { item, of_trait })
2101    }
2102
2103    /// If `item` is an attribute invocation, remove the attribute and return it together with
2104    /// its position and derives following it. We have to collect the derives in order to resolve
2105    /// legacy derive helpers (helpers written before derives that introduce them).
2106    fn take_first_attr(
2107        &self,
2108        item: &mut impl HasAttrs,
2109    ) -> Option<(ast::Attribute, usize, Vec<ast::Path>)> {
2110        let mut attr = None;
2111
2112        let mut cfg_pos = None;
2113        let mut attr_pos = None;
2114        for (pos, attr) in item.attrs().iter().enumerate() {
2115            if !attr.is_doc_comment() && !self.cx.expanded_inert_attrs.is_marked(attr) {
2116                let name = attr.name();
2117                if name == Some(sym::cfg) || name == Some(sym::cfg_attr) {
2118                    cfg_pos = Some(pos); // a cfg attr found, no need to search anymore
2119                    break;
2120                } else if attr_pos.is_none()
2121                    && !name.is_some_and(rustc_feature::is_builtin_attr_name)
2122                {
2123                    attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr
2124                }
2125            }
2126        }
2127
2128        item.visit_attrs(|attrs| {
2129            attr = Some(match (cfg_pos, attr_pos) {
2130                (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()),
2131                (_, Some(pos)) => {
2132                    let attr = attrs.remove(pos);
2133                    let following_derives = attrs[pos..]
2134                        .iter()
2135                        .filter(|a| a.has_name(sym::derive))
2136                        .flat_map(|a| a.meta_item_list().unwrap_or_default())
2137                        .filter_map(|meta_item_inner| match meta_item_inner {
2138                            MetaItemInner::MetaItem(ast::MetaItem {
2139                                kind: MetaItemKind::Word,
2140                                path,
2141                                ..
2142                            }) => Some(path),
2143                            _ => None,
2144                        })
2145                        .collect();
2146
2147                    (attr, pos, following_derives)
2148                }
2149                _ => return,
2150            });
2151        });
2152
2153        attr
2154    }
2155
2156    // Detect use of feature-gated or invalid attributes on macro invocations
2157    // since they will not be detected after macro expansion.
2158    fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) {
2159        let features = self.cx.ecfg.features;
2160        let mut attrs = attrs.iter().peekable();
2161        let mut span: Option<Span> = None;
2162        while let Some(attr) = attrs.next() {
2163            rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features);
2164            validate_attr::check_attr(&self.cx.sess.psess, attr);
2165            AttributeParser::parse_limited_all(
2166                self.cx.sess,
2167                slice::from_ref(attr),
2168                None,
2169                Target::MacroCall,
2170                call.span(),
2171                self.cx.current_expansion.lint_node_id,
2172                Some(self.cx.ecfg.features),
2173                ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
2174            );
2175
2176            let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
2177            span = Some(current_span);
2178
2179            if attrs.peek().is_some_and(|next_attr| next_attr.doc_str().is_some()) {
2180                continue;
2181            }
2182
2183            if attr.doc_str_and_fragment_kind().is_some() {
2184                self.cx.sess.psess.buffer_lint(
2185                    UNUSED_DOC_COMMENTS,
2186                    current_span,
2187                    self.cx.current_expansion.lint_node_id,
2188                    crate::errors::MacroCallUnusedDocComment { span: attr.span },
2189                );
2190            } else if rustc_attr_parsing::is_builtin_attr(attr)
2191                && !AttributeParser::<Early>::is_parsed_attribute(&attr.path())
2192            {
2193                let attr_name = attr.name().unwrap();
2194                self.cx.sess.psess.buffer_lint(
2195                    UNUSED_ATTRIBUTES,
2196                    attr.span,
2197                    self.cx.current_expansion.lint_node_id,
2198                    crate::errors::UnusedBuiltinAttribute {
2199                        attr_name,
2200                        macro_name: pprust::path_to_string(&call.path),
2201                        invoc_span: call.path.span,
2202                        attr_span: attr.span,
2203                    },
2204                );
2205            }
2206        }
2207    }
2208
2209    fn expand_cfg_true(
2210        &mut self,
2211        node: &mut (impl HasAttrs + HasNodeId),
2212        attr: ast::Attribute,
2213        pos: usize,
2214    ) -> EvalConfigResult {
2215        let Some(cfg) = AttributeParser::parse_single(
2216            self.cfg().sess,
2217            &attr,
2218            attr.span,
2219            self.cfg().lint_node_id,
2220            // Target doesn't matter for `cfg` parsing.
2221            Target::Crate,
2222            self.cfg().features,
2223            ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed },
2224            parse_cfg,
2225            &CFG_TEMPLATE,
2226        ) else {
2227            // Cfg attribute was not parsable, give up
2228            return EvalConfigResult::True;
2229        };
2230
2231        let res = eval_config_entry(self.cfg().sess, &cfg);
2232        if res.as_bool() {
2233            // A trace attribute left in AST in place of the original `cfg` attribute.
2234            // It can later be used by lints or other diagnostics.
2235            let mut trace_attr = attr_into_trace(attr, sym::cfg_trace);
2236            trace_attr.replace_args(AttrItemKind::Parsed(EarlyParsedAttribute::CfgTrace(cfg)));
2237            node.visit_attrs(|attrs| attrs.insert(pos, trace_attr));
2238        }
2239
2240        res
2241    }
2242
2243    fn expand_cfg_attr(&self, node: &mut impl HasAttrs, attr: &ast::Attribute, pos: usize) {
2244        node.visit_attrs(|attrs| {
2245            // Repeated `insert` calls is inefficient, but the number of
2246            // insertions is almost always 0 or 1 in practice.
2247            for cfg in self.cfg().expand_cfg_attr(attr, false).into_iter().rev() {
2248                attrs.insert(pos, cfg)
2249            }
2250        });
2251    }
2252
2253    fn flat_map_node<Node: InvocationCollectorNode<OutputTy: Default>>(
2254        &mut self,
2255        mut node: Node,
2256    ) -> Node::OutputTy {
2257        loop {
2258            return match self.take_first_attr(&mut node) {
2259                Some((attr, pos, derives)) => match attr.name() {
2260                    Some(sym::cfg) => {
2261                        let res = self.expand_cfg_true(&mut node, attr, pos);
2262                        match res {
2263                            EvalConfigResult::True => continue,
2264                            EvalConfigResult::False { reason, reason_span } => {
2265                                for ident in node.declared_idents() {
2266                                    self.cx.resolver.append_stripped_cfg_item(
2267                                        self.cx.current_expansion.lint_node_id,
2268                                        ident,
2269                                        reason.clone(),
2270                                        reason_span,
2271                                    )
2272                                }
2273                            }
2274                        }
2275
2276                        Default::default()
2277                    }
2278                    Some(sym::cfg_attr) => {
2279                        self.expand_cfg_attr(&mut node, &attr, pos);
2280                        continue;
2281                    }
2282                    _ => {
2283                        Node::pre_flat_map_node_collect_attr(&self.cfg(), &attr);
2284                        self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND)
2285                            .make_ast::<Node>()
2286                    }
2287                },
2288                None if node.is_mac_call() => {
2289                    let (mac, attrs, add_semicolon) = node.take_mac_call();
2290                    self.check_attributes(&attrs, &mac);
2291                    let mut res = self.collect_bang(mac, Node::KIND).make_ast::<Node>();
2292                    Node::post_flat_map_node_collect_bang(&mut res, add_semicolon);
2293                    res
2294                }
2295                None if let Some((deleg, item)) = node.delegation() => {
2296                    let Some(suffixes) = &deleg.suffixes else {
2297                        let traitless_qself =
2298                            #[allow(non_exhaustive_omitted_patterns)] match &deleg.qself {
    Some(qself) if qself.position == 0 => true,
    _ => false,
}matches!(&deleg.qself, Some(qself) if qself.position == 0);
2299                        let (item, of_trait) = match node.to_annotatable() {
2300                            Annotatable::AssocItem(item, AssocCtxt::Impl { of_trait }) => {
2301                                (item, of_trait)
2302                            }
2303                            ann @ (Annotatable::Item(_)
2304                            | Annotatable::AssocItem(..)
2305                            | Annotatable::Stmt(_)) => {
2306                                let span = ann.span();
2307                                self.cx.dcx().emit_err(GlobDelegationOutsideImpls { span });
2308                                return Default::default();
2309                            }
2310                            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2311                        };
2312                        if traitless_qself {
2313                            let span = item.span;
2314                            self.cx.dcx().emit_err(GlobDelegationTraitlessQpath { span });
2315                            return Default::default();
2316                        }
2317                        return self
2318                            .collect_glob_delegation(item, of_trait, Node::KIND)
2319                            .make_ast::<Node>();
2320                    };
2321
2322                    let single_delegations = build_single_delegations::<Node>(
2323                        self.cx, deleg, item, suffixes, item.span, false,
2324                    );
2325                    Node::flatten_outputs(single_delegations.map(|item| {
2326                        let mut item = Node::from_item(item);
2327                        {
    let old_id = self.cx.current_expansion.lint_node_id;
    if self.monotonic {
        if true {
            match (&*item.node_id_mut(), &ast::DUMMY_NODE_ID) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
        };
        let new_id = self.cx.resolver.next_node_id();
        *item.node_id_mut() = new_id;
        self.cx.current_expansion.lint_node_id = new_id;
    }
    let ret = (|| item.walk_flat_map(self))();
    self.cx.current_expansion.lint_node_id = old_id;
    ret
}assign_id!(self, item.node_id_mut(), || item.walk_flat_map(self))
2328                    }))
2329                }
2330                None => {
2331                    match Node::wrap_flat_map_node_walk_flat_map(node, self, |mut node, this| {
2332                        {
    let old_id = this.cx.current_expansion.lint_node_id;
    if this.monotonic {
        if true {
            match (&*node.node_id_mut(), &ast::DUMMY_NODE_ID) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
        };
        let new_id = this.cx.resolver.next_node_id();
        *node.node_id_mut() = new_id;
        this.cx.current_expansion.lint_node_id = new_id;
    }
    let ret = (|| node.walk_flat_map(this))();
    this.cx.current_expansion.lint_node_id = old_id;
    ret
}assign_id!(this, node.node_id_mut(), || node.walk_flat_map(this))
2333                    }) {
2334                        Ok(output) => output,
2335                        Err(returned_node) => {
2336                            node = returned_node;
2337                            continue;
2338                        }
2339                    }
2340                }
2341            };
2342        }
2343    }
2344
2345    fn visit_node<Node: InvocationCollectorNode<OutputTy: Into<Node>> + DummyAstNode>(
2346        &mut self,
2347        node: &mut Node,
2348    ) {
2349        loop {
2350            return match self.take_first_attr(node) {
2351                Some((attr, pos, derives)) => match attr.name() {
2352                    Some(sym::cfg) => {
2353                        let span = attr.span;
2354                        if self.expand_cfg_true(node, attr, pos).as_bool() {
2355                            continue;
2356                        }
2357
2358                        node.expand_cfg_false(self, pos, span);
2359                        continue;
2360                    }
2361                    Some(sym::cfg_attr) => {
2362                        self.expand_cfg_attr(node, &attr, pos);
2363                        continue;
2364                    }
2365                    _ => {
2366                        let n = mem::replace(node, Node::dummy());
2367                        *node = self
2368                            .collect_attr((attr, pos, derives), n.to_annotatable(), Node::KIND)
2369                            .make_ast::<Node>()
2370                            .into()
2371                    }
2372                },
2373                None if node.is_mac_call() => {
2374                    let n = mem::replace(node, Node::dummy());
2375                    let (mac, attrs, _) = n.take_mac_call();
2376                    self.check_attributes(&attrs, &mac);
2377
2378                    *node = self.collect_bang(mac, Node::KIND).make_ast::<Node>().into()
2379                }
2380                None if node.delegation().is_some() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2381                None => {
2382                    {
    let old_id = self.cx.current_expansion.lint_node_id;
    if self.monotonic {
        if true {
            match (&*node.node_id_mut(), &ast::DUMMY_NODE_ID) {
                (left_val, right_val) => {
                    if !(*left_val == *right_val) {
                        let kind = ::core::panicking::AssertKind::Eq;
                        ::core::panicking::assert_failed(kind, &*left_val,
                            &*right_val, ::core::option::Option::None);
                    }
                }
            };
        };
        let new_id = self.cx.resolver.next_node_id();
        *node.node_id_mut() = new_id;
        self.cx.current_expansion.lint_node_id = new_id;
    }
    let ret = (|| node.walk(self))();
    self.cx.current_expansion.lint_node_id = old_id;
    ret
}assign_id!(self, node.node_id_mut(), || node.walk(self))
2383                }
2384            };
2385        }
2386    }
2387}
2388
2389impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
2390    fn flat_map_item(&mut self, node: Box<ast::Item>) -> SmallVec<[Box<ast::Item>; 1]> {
2391        self.flat_map_node(node)
2392    }
2393
2394    fn flat_map_assoc_item(
2395        &mut self,
2396        node: Box<ast::AssocItem>,
2397        ctxt: AssocCtxt,
2398    ) -> SmallVec<[Box<ast::AssocItem>; 1]> {
2399        match ctxt {
2400            AssocCtxt::Trait => self.flat_map_node(AstNodeWrapper::new(node, TraitItemTag)),
2401            AssocCtxt::Impl { of_trait: false, .. } => {
2402                self.flat_map_node(AstNodeWrapper::new(node, ImplItemTag))
2403            }
2404            AssocCtxt::Impl { of_trait: true, .. } => {
2405                self.flat_map_node(AstNodeWrapper::new(node, TraitImplItemTag))
2406            }
2407        }
2408    }
2409
2410    fn flat_map_foreign_item(
2411        &mut self,
2412        node: Box<ast::ForeignItem>,
2413    ) -> SmallVec<[Box<ast::ForeignItem>; 1]> {
2414        self.flat_map_node(node)
2415    }
2416
2417    fn flat_map_variant(&mut self, node: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
2418        self.flat_map_node(node)
2419    }
2420
2421    fn flat_map_where_predicate(
2422        &mut self,
2423        node: ast::WherePredicate,
2424    ) -> SmallVec<[ast::WherePredicate; 1]> {
2425        self.flat_map_node(node)
2426    }
2427
2428    fn flat_map_field_def(&mut self, node: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
2429        self.flat_map_node(node)
2430    }
2431
2432    fn flat_map_pat_field(&mut self, node: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
2433        self.flat_map_node(node)
2434    }
2435
2436    fn flat_map_expr_field(&mut self, node: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
2437        self.flat_map_node(node)
2438    }
2439
2440    fn flat_map_param(&mut self, node: ast::Param) -> SmallVec<[ast::Param; 1]> {
2441        self.flat_map_node(node)
2442    }
2443
2444    fn flat_map_generic_param(
2445        &mut self,
2446        node: ast::GenericParam,
2447    ) -> SmallVec<[ast::GenericParam; 1]> {
2448        self.flat_map_node(node)
2449    }
2450
2451    fn flat_map_arm(&mut self, node: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
2452        self.flat_map_node(node)
2453    }
2454
2455    fn flat_map_stmt(&mut self, node: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
2456        // FIXME: invocations in semicolon-less expressions positions are expanded as expressions,
2457        // changing that requires some compatibility measures.
2458        if node.is_expr() {
2459            // The only way that we can end up with a `MacCall` expression statement,
2460            // (as opposed to a `StmtKind::MacCall`) is if we have a macro as the
2461            // trailing expression in a block (e.g. `fn foo() { my_macro!() }`).
2462            // Record this information, so that we can report a more specific
2463            // `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint if needed.
2464            // See #78991 for an investigation of treating macros in this position
2465            // as statements, rather than expressions, during parsing.
2466            return match &node.kind {
2467                StmtKind::Expr(expr)
2468                    if #[allow(non_exhaustive_omitted_patterns)] match **expr {
    ast::Expr { kind: ExprKind::MacCall(..), .. } => true,
    _ => false,
}matches!(**expr, ast::Expr { kind: ExprKind::MacCall(..), .. }) =>
2469                {
2470                    self.cx.current_expansion.is_trailing_mac = true;
2471                    // Don't use `assign_id` for this statement - it may get removed
2472                    // entirely due to a `#[cfg]` on the contained expression
2473                    let res = walk_flat_map_stmt(self, node);
2474                    self.cx.current_expansion.is_trailing_mac = false;
2475                    res
2476                }
2477                _ => walk_flat_map_stmt(self, node),
2478            };
2479        }
2480
2481        self.flat_map_node(node)
2482    }
2483
2484    fn visit_crate(&mut self, node: &mut ast::Crate) {
2485        self.visit_node(node)
2486    }
2487
2488    fn visit_ty(&mut self, node: &mut ast::Ty) {
2489        self.visit_node(node)
2490    }
2491
2492    fn visit_pat(&mut self, node: &mut ast::Pat) {
2493        self.visit_node(node)
2494    }
2495
2496    fn visit_expr(&mut self, node: &mut ast::Expr) {
2497        // FIXME: Feature gating is performed inconsistently between `Expr` and `OptExpr`.
2498        if let Some(attr) = node.attrs.first() {
2499            self.cfg().maybe_emit_expr_attr_err(attr);
2500        }
2501        ensure_sufficient_stack(|| self.visit_node(node))
2502    }
2503
2504    fn visit_method_receiver_expr(&mut self, node: &mut ast::Expr) {
2505        self.visit_node(AstNodeWrapper::from_mut(node, MethodReceiverTag))
2506    }
2507
2508    fn filter_map_expr(&mut self, node: Box<ast::Expr>) -> Option<Box<ast::Expr>> {
2509        self.flat_map_node(AstNodeWrapper::new(node, OptExprTag))
2510    }
2511
2512    fn visit_block(&mut self, node: &mut ast::Block) {
2513        let orig_dir_ownership = mem::replace(
2514            &mut self.cx.current_expansion.dir_ownership,
2515            DirOwnership::UnownedViaBlock,
2516        );
2517        walk_block(self, node);
2518        self.cx.current_expansion.dir_ownership = orig_dir_ownership;
2519    }
2520
2521    fn visit_id(&mut self, id: &mut NodeId) {
2522        // We may have already assigned a `NodeId`
2523        // by calling `assign_id`
2524        if self.monotonic && *id == ast::DUMMY_NODE_ID {
2525            *id = self.cx.resolver.next_node_id();
2526        }
2527    }
2528}
2529
2530pub struct ExpansionConfig<'feat> {
2531    pub crate_name: Symbol,
2532    pub features: &'feat Features,
2533    pub recursion_limit: Limit,
2534    pub trace_mac: bool,
2535    /// If false, strip `#[test]` nodes
2536    pub should_test: bool,
2537    /// If true, use verbose debugging for `proc_macro::Span`
2538    pub span_debug: bool,
2539    /// If true, show backtraces for proc-macro panics
2540    pub proc_macro_backtrace: bool,
2541}
2542
2543impl ExpansionConfig<'_> {
2544    pub fn default(crate_name: Symbol, features: &Features) -> ExpansionConfig<'_> {
2545        ExpansionConfig {
2546            crate_name,
2547            features,
2548            // FIXME should this limit be configurable?
2549            recursion_limit: Limit::new(1024),
2550            trace_mac: false,
2551            should_test: false,
2552            span_debug: false,
2553            proc_macro_backtrace: false,
2554        }
2555    }
2556}