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