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