rustc_expand/
expand.rs

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