rustc_expand/
expand.rs

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