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