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