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