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