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