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