]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/expand.rs
Rollup merge of #81764 - jyn514:lint-links, r=GuillaumeGomez
[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, AttrStyle, 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 derive_placeholders = self
495                         .cx
496                         .resolver
497                         .take_derive_resolutions(expn_id)
498                         .map(|derives| {
499                             enum AnnotatableRef<'a> {
500                                 Item(&'a P<ast::Item>),
501                                 Stmt(&'a ast::Stmt),
502                             }
503                             let item = match &fragment {
504                                 AstFragment::Items(items) => match &items[..] {
505                                     [item] => AnnotatableRef::Item(item),
506                                     _ => unreachable!(),
507                                 },
508                                 AstFragment::Stmts(stmts) => match &stmts[..] {
509                                     [stmt] => AnnotatableRef::Stmt(stmt),
510                                     _ => unreachable!(),
511                                 },
512                                 _ => unreachable!(),
513                             };
514
515                             invocations.reserve(derives.len());
516                             derives
517                                 .into_iter()
518                                 .map(|(path, _exts)| {
519                                     // FIXME: Consider using the derive resolutions (`_exts`)
520                                     // instead of enqueuing the derives to be resolved again later.
521                                     let expn_id = ExpnId::fresh(None);
522                                     invocations.push((
523                                         Invocation {
524                                             kind: InvocationKind::Derive {
525                                                 path,
526                                                 item: match item {
527                                                     AnnotatableRef::Item(item) => {
528                                                         Annotatable::Item(item.clone())
529                                                     }
530                                                     AnnotatableRef::Stmt(stmt) => {
531                                                         Annotatable::Stmt(P(stmt.clone()))
532                                                     }
533                                                 },
534                                             },
535                                             fragment_kind,
536                                             expansion_data: ExpansionData {
537                                                 id: expn_id,
538                                                 ..self.cx.current_expansion.clone()
539                                             },
540                                         },
541                                         None,
542                                     ));
543                                     NodeId::placeholder_from_expn_id(expn_id)
544                                 })
545                                 .collect::<Vec<_>>()
546                         })
547                         .unwrap_or_default();
548
549                     self.collect_invocations(fragment, &derive_placeholders)
550                 }
551                 ExpandResult::Retry(invoc) => {
552                     if force {
553                         self.cx.span_bug(
554                             invoc.span(),
555                             "expansion entered force mode but is still stuck",
556                         );
557                     } else {
558                         // Cannot expand, will retry this invocation later.
559                         undetermined_invocations.push((invoc, Some(ext)));
560                         continue;
561                     }
562                 }
563             };
564
565             progress = true;
566             if expanded_fragments.len() < depth {
567                 expanded_fragments.push(Vec::new());
568             }
569             expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
570             invocations.extend(new_invocations.into_iter().rev());
571         }
572
573         self.cx.current_expansion = orig_expansion_data;
574         self.cx.force_mode = orig_force_mode;
575
576         // Finally incorporate all the expanded macros into the input AST fragment.
577         let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
578         while let Some(expanded_fragments) = expanded_fragments.pop() {
579             for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() {
580                 placeholder_expander
581                     .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment);
582             }
583         }
584         fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
585         fragment_with_placeholders
586     }
587
588     fn resolve_imports(&mut self) {
589         if self.monotonic {
590             self.cx.resolver.resolve_imports();
591         }
592     }
593
594     /// Collects all macro invocations reachable at this time in this AST fragment, and replace
595     /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
596     /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
597     /// prepares data for resolving paths of macro invocations.
598     fn collect_invocations(
599         &mut self,
600         mut fragment: AstFragment,
601         extra_placeholders: &[NodeId],
602     ) -> (AstFragment, Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>) {
603         // Resolve `$crate`s in the fragment for pretty-printing.
604         self.cx.resolver.resolve_dollar_crates();
605
606         let invocations = {
607             let mut collector = InvocationCollector {
608                 cfg: StripUnconfigured {
609                     sess: &self.cx.sess,
610                     features: self.cx.ecfg.features,
611                     modified: false,
612                 },
613                 cx: self.cx,
614                 invocations: Vec::new(),
615                 monotonic: self.monotonic,
616             };
617             fragment.mut_visit_with(&mut collector);
618             fragment.add_placeholders(extra_placeholders);
619             collector.invocations
620         };
621
622         if self.monotonic {
623             self.cx
624                 .resolver
625                 .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment);
626         }
627
628         (fragment, invocations)
629     }
630
631     fn error_recursion_limit_reached(&mut self) {
632         let expn_data = self.cx.current_expansion.id.expn_data();
633         let suggested_limit = self.cx.ecfg.recursion_limit * 2;
634         self.cx
635             .struct_span_err(
636                 expn_data.call_site,
637                 &format!("recursion limit reached while expanding `{}`", expn_data.kind.descr()),
638             )
639             .help(&format!(
640                 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate (`{}`)",
641                 suggested_limit, self.cx.ecfg.crate_name,
642             ))
643             .emit();
644         self.cx.trace_macros_diag();
645     }
646
647     /// A macro's expansion does not fit in this fragment kind.
648     /// For example, a non-type macro in a type position.
649     fn error_wrong_fragment_kind(&mut self, kind: AstFragmentKind, mac: &ast::MacCall, span: Span) {
650         let msg = format!(
651             "non-{kind} macro in {kind} position: {path}",
652             kind = kind.name(),
653             path = pprust::path_to_string(&mac.path),
654         );
655         self.cx.span_err(span, &msg);
656         self.cx.trace_macros_diag();
657     }
658
659     fn expand_invoc(
660         &mut self,
661         invoc: Invocation,
662         ext: &SyntaxExtensionKind,
663     ) -> ExpandResult<AstFragment, Invocation> {
664         let recursion_limit =
665             self.cx.reduced_recursion_limit.unwrap_or(self.cx.ecfg.recursion_limit);
666         if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) {
667             if self.cx.reduced_recursion_limit.is_none() {
668                 self.error_recursion_limit_reached();
669             }
670
671             // Reduce the recursion limit by half each time it triggers.
672             self.cx.reduced_recursion_limit = Some(recursion_limit / 2);
673
674             return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span()));
675         }
676
677         let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
678         ExpandResult::Ready(match invoc.kind {
679             InvocationKind::Bang { mac, .. } => match ext {
680                 SyntaxExtensionKind::Bang(expander) => {
681                     let tok_result = match expander.expand(self.cx, span, mac.args.inner_tokens()) {
682                         Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)),
683                         Ok(ts) => ts,
684                     };
685                     self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span)
686                 }
687                 SyntaxExtensionKind::LegacyBang(expander) => {
688                     let prev = self.cx.current_expansion.prior_type_ascription;
689                     self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription;
690                     let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens());
691                     let result = if let Some(result) = fragment_kind.make_from(tok_result) {
692                         result
693                     } else {
694                         self.error_wrong_fragment_kind(fragment_kind, &mac, span);
695                         fragment_kind.dummy(span)
696                     };
697                     self.cx.current_expansion.prior_type_ascription = prev;
698                     result
699                 }
700                 _ => unreachable!(),
701             },
702             InvocationKind::Attr { attr, pos, mut item, derives } => match ext {
703                 SyntaxExtensionKind::Attr(expander) => {
704                     self.gate_proc_macro_input(&item);
705                     self.gate_proc_macro_attr_item(span, &item);
706                     let tokens = match attr.style {
707                         AttrStyle::Outer => item.into_tokens(&self.cx.sess.parse_sess),
708                         // FIXME: Properly collect tokens for inner attributes
709                         AttrStyle::Inner => rustc_parse::fake_token_stream(
710                             &self.cx.sess.parse_sess,
711                             &item.into_nonterminal(),
712                         ),
713                     };
714                     let attr_item = attr.unwrap_normal_item();
715                     if let MacArgs::Eq(..) = attr_item.args {
716                         self.cx.span_err(span, "key-value macro attributes are not supported");
717                     }
718                     let inner_tokens = attr_item.args.inner_tokens();
719                     let tok_result = match expander.expand(self.cx, span, inner_tokens, tokens) {
720                         Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)),
721                         Ok(ts) => ts,
722                     };
723                     self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span)
724                 }
725                 SyntaxExtensionKind::LegacyAttr(expander) => {
726                     match validate_attr::parse_meta(&self.cx.sess.parse_sess, &attr) {
727                         Ok(meta) => {
728                             let items = match expander.expand(self.cx, span, &meta, item) {
729                                 ExpandResult::Ready(items) => items,
730                                 ExpandResult::Retry(item) => {
731                                     // Reassemble the original invocation for retrying.
732                                     return ExpandResult::Retry(Invocation {
733                                         kind: InvocationKind::Attr { attr, pos, item, derives },
734                                         ..invoc
735                                     });
736                                 }
737                             };
738                             if fragment_kind == AstFragmentKind::Expr && items.is_empty() {
739                                 let msg =
740                                     "removing an expression is not supported in this position";
741                                 self.cx.span_err(span, msg);
742                                 fragment_kind.dummy(span)
743                             } else {
744                                 fragment_kind.expect_from_annotatables(items)
745                             }
746                         }
747                         Err(mut err) => {
748                             err.emit();
749                             fragment_kind.dummy(span)
750                         }
751                     }
752                 }
753                 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
754                     self.cx.sess.mark_attr_known(&attr);
755                     if *mark_used {
756                         self.cx.sess.mark_attr_used(&attr);
757                     }
758                     item.visit_attrs(|attrs| attrs.insert(pos, attr));
759                     fragment_kind.expect_from_annotatables(iter::once(item))
760                 }
761                 _ => unreachable!(),
762             },
763             InvocationKind::Derive { path, item } => match ext {
764                 SyntaxExtensionKind::Derive(expander)
765                 | SyntaxExtensionKind::LegacyDerive(expander) => {
766                     if let SyntaxExtensionKind::Derive(..) = ext {
767                         self.gate_proc_macro_input(&item);
768                     }
769                     let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
770                     let items = match expander.expand(self.cx, span, &meta, item) {
771                         ExpandResult::Ready(items) => items,
772                         ExpandResult::Retry(item) => {
773                             // Reassemble the original invocation for retrying.
774                             return ExpandResult::Retry(Invocation {
775                                 kind: InvocationKind::Derive { path: meta.path, item },
776                                 ..invoc
777                             });
778                         }
779                     };
780                     fragment_kind.expect_from_annotatables(items)
781                 }
782                 _ => unreachable!(),
783             },
784         })
785     }
786
787     fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
788         let kind = match item {
789             Annotatable::Item(_)
790             | Annotatable::TraitItem(_)
791             | Annotatable::ImplItem(_)
792             | Annotatable::ForeignItem(_) => return,
793             Annotatable::Stmt(stmt) => {
794                 // Attributes are stable on item statements,
795                 // but unstable on all other kinds of statements
796                 if stmt.is_item() {
797                     return;
798                 }
799                 "statements"
800             }
801             Annotatable::Expr(_) => "expressions",
802             Annotatable::Arm(..)
803             | Annotatable::ExprField(..)
804             | Annotatable::PatField(..)
805             | Annotatable::GenericParam(..)
806             | Annotatable::Param(..)
807             | Annotatable::FieldDef(..)
808             | Annotatable::Variant(..) => panic!("unexpected annotatable"),
809         };
810         if self.cx.ecfg.proc_macro_hygiene() {
811             return;
812         }
813         feature_err(
814             &self.cx.sess.parse_sess,
815             sym::proc_macro_hygiene,
816             span,
817             &format!("custom attributes cannot be applied to {}", kind),
818         )
819         .emit();
820     }
821
822     fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
823         struct GateProcMacroInput<'a> {
824             parse_sess: &'a ParseSess,
825         }
826
827         impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
828             fn visit_item(&mut self, item: &'ast ast::Item) {
829                 match &item.kind {
830                     ast::ItemKind::Mod(_, mod_kind)
831                         if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _)) =>
832                     {
833                         feature_err(
834                             self.parse_sess,
835                             sym::proc_macro_hygiene,
836                             item.span,
837                             "non-inline modules in proc macro input are unstable",
838                         )
839                         .emit();
840                     }
841                     _ => {}
842                 }
843
844                 visit::walk_item(self, item);
845             }
846         }
847
848         if !self.cx.ecfg.proc_macro_hygiene() {
849             annotatable
850                 .visit_with(&mut GateProcMacroInput { parse_sess: &self.cx.sess.parse_sess });
851         }
852     }
853
854     fn parse_ast_fragment(
855         &mut self,
856         toks: TokenStream,
857         kind: AstFragmentKind,
858         path: &Path,
859         span: Span,
860     ) -> AstFragment {
861         let mut parser = self.cx.new_parser_from_tts(toks);
862         match parse_ast_fragment(&mut parser, kind) {
863             Ok(fragment) => {
864                 ensure_complete_parse(&mut parser, path, kind.name(), span);
865                 fragment
866             }
867             Err(mut err) => {
868                 if err.span.is_dummy() {
869                     err.set_span(span);
870                 }
871                 annotate_err_with_kind(&mut err, kind, span);
872                 err.emit();
873                 self.cx.trace_macros_diag();
874                 kind.dummy(span)
875             }
876         }
877     }
878 }
879
880 pub fn parse_ast_fragment<'a>(
881     this: &mut Parser<'a>,
882     kind: AstFragmentKind,
883 ) -> PResult<'a, AstFragment> {
884     Ok(match kind {
885         AstFragmentKind::Items => {
886             let mut items = SmallVec::new();
887             while let Some(item) = this.parse_item(ForceCollect::No)? {
888                 items.push(item);
889             }
890             AstFragment::Items(items)
891         }
892         AstFragmentKind::TraitItems => {
893             let mut items = SmallVec::new();
894             while let Some(item) = this.parse_trait_item()? {
895                 items.extend(item);
896             }
897             AstFragment::TraitItems(items)
898         }
899         AstFragmentKind::ImplItems => {
900             let mut items = SmallVec::new();
901             while let Some(item) = this.parse_impl_item()? {
902                 items.extend(item);
903             }
904             AstFragment::ImplItems(items)
905         }
906         AstFragmentKind::ForeignItems => {
907             let mut items = SmallVec::new();
908             while let Some(item) = this.parse_foreign_item()? {
909                 items.extend(item);
910             }
911             AstFragment::ForeignItems(items)
912         }
913         AstFragmentKind::Stmts => {
914             let mut stmts = SmallVec::new();
915             // Won't make progress on a `}`.
916             while this.token != token::Eof && this.token != token::CloseDelim(token::Brace) {
917                 if let Some(stmt) = this.parse_full_stmt(AttemptLocalParseRecovery::Yes)? {
918                     stmts.push(stmt);
919                 }
920             }
921             AstFragment::Stmts(stmts)
922         }
923         AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?),
924         AstFragmentKind::OptExpr => {
925             if this.token != token::Eof {
926                 AstFragment::OptExpr(Some(this.parse_expr()?))
927             } else {
928                 AstFragment::OptExpr(None)
929             }
930         }
931         AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?),
932         AstFragmentKind::Pat => {
933             AstFragment::Pat(this.parse_pat_allow_top_alt(None, RecoverComma::No)?)
934         }
935         AstFragmentKind::Arms
936         | AstFragmentKind::Fields
937         | AstFragmentKind::FieldPats
938         | AstFragmentKind::GenericParams
939         | AstFragmentKind::Params
940         | AstFragmentKind::StructFields
941         | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"),
942     })
943 }
944
945 pub fn ensure_complete_parse<'a>(
946     this: &mut Parser<'a>,
947     macro_path: &Path,
948     kind_name: &str,
949     span: Span,
950 ) {
951     if this.token != token::Eof {
952         let token = pprust::token_to_string(&this.token);
953         let msg = format!("macro expansion ignores token `{}` and any following", token);
954         // Avoid emitting backtrace info twice.
955         let def_site_span = this.token.span.with_ctxt(SyntaxContext::root());
956         let mut err = this.struct_span_err(def_site_span, &msg);
957         err.span_label(span, "caused by the macro expansion here");
958         let msg = format!(
959             "the usage of `{}!` is likely invalid in {} context",
960             pprust::path_to_string(macro_path),
961             kind_name,
962         );
963         err.note(&msg);
964         let semi_span = this.sess.source_map().next_point(span);
965
966         let semi_full_span = semi_span.to(this.sess.source_map().next_point(semi_span));
967         match this.sess.source_map().span_to_snippet(semi_full_span) {
968             Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
969                 err.span_suggestion(
970                     semi_span,
971                     "you might be missing a semicolon here",
972                     ";".to_owned(),
973                     Applicability::MaybeIncorrect,
974                 );
975             }
976             _ => {}
977         }
978         err.emit();
979     }
980 }
981
982 struct InvocationCollector<'a, 'b> {
983     cx: &'a mut ExtCtxt<'b>,
984     cfg: StripUnconfigured<'a>,
985     invocations: Vec<(Invocation, Option<Lrc<SyntaxExtension>>)>,
986     monotonic: bool,
987 }
988
989 impl<'a, 'b> InvocationCollector<'a, 'b> {
990     fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
991         let expn_id = ExpnId::fresh(None);
992         let vis = kind.placeholder_visibility();
993         self.invocations.push((
994             Invocation {
995                 kind,
996                 fragment_kind,
997                 expansion_data: ExpansionData {
998                     id: expn_id,
999                     depth: self.cx.current_expansion.depth + 1,
1000                     ..self.cx.current_expansion.clone()
1001                 },
1002             },
1003             None,
1004         ));
1005         placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis)
1006     }
1007
1008     fn collect_bang(
1009         &mut self,
1010         mac: ast::MacCall,
1011         span: Span,
1012         kind: AstFragmentKind,
1013     ) -> AstFragment {
1014         self.collect(kind, InvocationKind::Bang { mac, span })
1015     }
1016
1017     fn collect_attr(
1018         &mut self,
1019         (attr, pos, derives): (ast::Attribute, usize, Vec<Path>),
1020         item: Annotatable,
1021         kind: AstFragmentKind,
1022     ) -> AstFragment {
1023         self.collect(kind, InvocationKind::Attr { attr, pos, item, derives })
1024     }
1025
1026     /// If `item` is an attribute invocation, remove the attribute and return it together with
1027     /// its position and derives following it. We have to collect the derives in order to resolve
1028     /// legacy derive helpers (helpers written before derives that introduce them).
1029     fn take_first_attr(
1030         &mut self,
1031         item: &mut impl AstLike,
1032     ) -> Option<(ast::Attribute, usize, Vec<Path>)> {
1033         let mut attr = None;
1034
1035         item.visit_attrs(|attrs| {
1036             attr = attrs
1037                 .iter()
1038                 .position(|a| !self.cx.sess.is_attr_known(a) && !is_builtin_attr(a))
1039                 .map(|attr_pos| {
1040                     let attr = attrs.remove(attr_pos);
1041                     let following_derives = attrs[attr_pos..]
1042                         .iter()
1043                         .filter(|a| a.has_name(sym::derive))
1044                         .flat_map(|a| a.meta_item_list().unwrap_or_default())
1045                         .filter_map(|nested_meta| match nested_meta {
1046                             NestedMetaItem::MetaItem(ast::MetaItem {
1047                                 kind: MetaItemKind::Word,
1048                                 path,
1049                                 ..
1050                             }) => Some(path),
1051                             _ => None,
1052                         })
1053                         .collect();
1054
1055                     (attr, attr_pos, following_derives)
1056                 })
1057         });
1058
1059         attr
1060     }
1061
1062     fn configure<T: AstLike>(&mut self, node: T) -> Option<T> {
1063         self.cfg.configure(node)
1064     }
1065
1066     // Detect use of feature-gated or invalid attributes on macro invocations
1067     // since they will not be detected after macro expansion.
1068     fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1069         let features = self.cx.ecfg.features.unwrap();
1070         let mut attrs = attrs.iter().peekable();
1071         let mut span: Option<Span> = None;
1072         while let Some(attr) = attrs.next() {
1073             rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features);
1074             validate_attr::check_meta(&self.cx.sess.parse_sess, attr);
1075
1076             let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span };
1077             span = Some(current_span);
1078
1079             if attrs.peek().map_or(false, |next_attr| next_attr.doc_str().is_some()) {
1080                 continue;
1081             }
1082
1083             if attr.doc_str().is_some() {
1084                 self.cx.sess.parse_sess.buffer_lint_with_diagnostic(
1085                     &UNUSED_DOC_COMMENTS,
1086                     current_span,
1087                     ast::CRATE_NODE_ID,
1088                     "unused doc comment",
1089                     BuiltinLintDiagnostics::UnusedDocComment(attr.span),
1090                 );
1091             }
1092         }
1093     }
1094 }
1095
1096 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1097     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1098         self.cfg.configure_expr(expr);
1099         visit_clobber(expr.deref_mut(), |mut expr| {
1100             if let Some(attr) = self.take_first_attr(&mut expr) {
1101                 // Collect the invoc regardless of whether or not attributes are permitted here
1102                 // expansion will eat the attribute so it won't error later.
1103                 self.cfg.maybe_emit_expr_attr_err(&attr.0);
1104
1105                 // AstFragmentKind::Expr requires the macro to emit an expression.
1106                 return self
1107                     .collect_attr(attr, Annotatable::Expr(P(expr)), AstFragmentKind::Expr)
1108                     .make_expr()
1109                     .into_inner();
1110             }
1111
1112             if let ast::ExprKind::MacCall(mac) = expr.kind {
1113                 self.check_attributes(&expr.attrs);
1114                 self.collect_bang(mac, expr.span, AstFragmentKind::Expr).make_expr().into_inner()
1115             } else {
1116                 ensure_sufficient_stack(|| noop_visit_expr(&mut expr, self));
1117                 expr
1118             }
1119         });
1120     }
1121
1122     fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1123         let mut arm = configure!(self, arm);
1124
1125         if let Some(attr) = self.take_first_attr(&mut arm) {
1126             return self
1127                 .collect_attr(attr, Annotatable::Arm(arm), AstFragmentKind::Arms)
1128                 .make_arms();
1129         }
1130
1131         noop_flat_map_arm(arm, self)
1132     }
1133
1134     fn flat_map_expr_field(&mut self, field: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
1135         let mut field = configure!(self, field);
1136
1137         if let Some(attr) = self.take_first_attr(&mut field) {
1138             return self
1139                 .collect_attr(attr, Annotatable::ExprField(field), AstFragmentKind::Fields)
1140                 .make_expr_fields();
1141         }
1142
1143         noop_flat_map_expr_field(field, self)
1144     }
1145
1146     fn flat_map_pat_field(&mut self, fp: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
1147         let mut fp = configure!(self, fp);
1148
1149         if let Some(attr) = self.take_first_attr(&mut fp) {
1150             return self
1151                 .collect_attr(attr, Annotatable::PatField(fp), AstFragmentKind::FieldPats)
1152                 .make_pat_fields();
1153         }
1154
1155         noop_flat_map_pat_field(fp, self)
1156     }
1157
1158     fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1159         let mut p = configure!(self, p);
1160
1161         if let Some(attr) = self.take_first_attr(&mut p) {
1162             return self
1163                 .collect_attr(attr, Annotatable::Param(p), AstFragmentKind::Params)
1164                 .make_params();
1165         }
1166
1167         noop_flat_map_param(p, self)
1168     }
1169
1170     fn flat_map_field_def(&mut self, sf: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
1171         let mut sf = configure!(self, sf);
1172
1173         if let Some(attr) = self.take_first_attr(&mut sf) {
1174             return self
1175                 .collect_attr(attr, Annotatable::FieldDef(sf), AstFragmentKind::StructFields)
1176                 .make_field_defs();
1177         }
1178
1179         noop_flat_map_field_def(sf, self)
1180     }
1181
1182     fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1183         let mut variant = configure!(self, variant);
1184
1185         if let Some(attr) = self.take_first_attr(&mut variant) {
1186             return self
1187                 .collect_attr(attr, Annotatable::Variant(variant), AstFragmentKind::Variants)
1188                 .make_variants();
1189         }
1190
1191         noop_flat_map_variant(variant, self)
1192     }
1193
1194     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1195         let expr = configure!(self, expr);
1196         expr.filter_map(|mut expr| {
1197             if let Some(attr) = self.take_first_attr(&mut expr) {
1198                 self.cfg.maybe_emit_expr_attr_err(&attr.0);
1199
1200                 return self
1201                     .collect_attr(attr, Annotatable::Expr(P(expr)), AstFragmentKind::OptExpr)
1202                     .make_opt_expr()
1203                     .map(|expr| expr.into_inner());
1204             }
1205
1206             if let ast::ExprKind::MacCall(mac) = expr.kind {
1207                 self.check_attributes(&expr.attrs);
1208                 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1209                     .make_opt_expr()
1210                     .map(|expr| expr.into_inner())
1211             } else {
1212                 Some({
1213                     noop_visit_expr(&mut expr, self);
1214                     expr
1215                 })
1216             }
1217         })
1218     }
1219
1220     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1221         match pat.kind {
1222             PatKind::MacCall(_) => {}
1223             _ => return noop_visit_pat(pat, self),
1224         }
1225
1226         visit_clobber(pat, |mut pat| match mem::replace(&mut pat.kind, PatKind::Wild) {
1227             PatKind::MacCall(mac) => {
1228                 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat()
1229             }
1230             _ => unreachable!(),
1231         });
1232     }
1233
1234     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1235         let mut stmt = configure!(self, stmt);
1236
1237         // we'll expand attributes on expressions separately
1238         if !stmt.is_expr() {
1239             if let Some(attr) = self.take_first_attr(&mut stmt) {
1240                 return self
1241                     .collect_attr(attr, Annotatable::Stmt(P(stmt)), AstFragmentKind::Stmts)
1242                     .make_stmts();
1243             }
1244         }
1245
1246         if let StmtKind::MacCall(mac) = stmt.kind {
1247             let MacCallStmt { mac, style, attrs, tokens: _ } = mac.into_inner();
1248             self.check_attributes(&attrs);
1249             let mut placeholder =
1250                 self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts).make_stmts();
1251
1252             // If this is a macro invocation with a semicolon, then apply that
1253             // semicolon to the final statement produced by expansion.
1254             if style == MacStmtStyle::Semicolon {
1255                 if let Some(stmt) = placeholder.pop() {
1256                     placeholder.push(stmt.add_trailing_semicolon());
1257                 }
1258             }
1259
1260             return placeholder;
1261         }
1262
1263         // The placeholder expander gives ids to statements, so we avoid folding the id here.
1264         let ast::Stmt { id, kind, span } = stmt;
1265         noop_flat_map_stmt_kind(kind, self)
1266             .into_iter()
1267             .map(|kind| ast::Stmt { id, kind, span })
1268             .collect()
1269     }
1270
1271     fn visit_block(&mut self, block: &mut P<Block>) {
1272         let orig_dir_ownership = mem::replace(
1273             &mut self.cx.current_expansion.dir_ownership,
1274             DirOwnership::UnownedViaBlock,
1275         );
1276         noop_visit_block(block, self);
1277         self.cx.current_expansion.dir_ownership = orig_dir_ownership;
1278     }
1279
1280     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1281         let mut item = configure!(self, item);
1282
1283         if let Some(attr) = self.take_first_attr(&mut item) {
1284             return self
1285                 .collect_attr(attr, Annotatable::Item(item), AstFragmentKind::Items)
1286                 .make_items();
1287         }
1288
1289         let mut attrs = mem::take(&mut item.attrs); // We do this to please borrowck.
1290         let ident = item.ident;
1291         let span = item.span;
1292
1293         match item.kind {
1294             ast::ItemKind::MacCall(..) => {
1295                 item.attrs = attrs;
1296                 self.check_attributes(&item.attrs);
1297                 item.and_then(|item| match item.kind {
1298                     ItemKind::MacCall(mac) => {
1299                         self.collect_bang(mac, span, AstFragmentKind::Items).make_items()
1300                     }
1301                     _ => unreachable!(),
1302                 })
1303             }
1304             ast::ItemKind::Mod(_, ref mut mod_kind) if ident != Ident::invalid() => {
1305                 let (file_path, dir_path, dir_ownership) = match mod_kind {
1306                     ModKind::Loaded(_, inline, _) => {
1307                         // Inline `mod foo { ... }`, but we still need to push directories.
1308                         let (dir_path, dir_ownership) = mod_dir_path(
1309                             &self.cx.sess,
1310                             ident,
1311                             &attrs,
1312                             &self.cx.current_expansion.module,
1313                             self.cx.current_expansion.dir_ownership,
1314                             *inline,
1315                         );
1316                         item.attrs = attrs;
1317                         (None, dir_path, dir_ownership)
1318                     }
1319                     ModKind::Unloaded => {
1320                         // We have an outline `mod foo;` so we need to parse the file.
1321                         let old_attrs_len = attrs.len();
1322                         let ParsedExternalMod {
1323                             mut items,
1324                             inner_span,
1325                             file_path,
1326                             dir_path,
1327                             dir_ownership,
1328                         } = parse_external_mod(
1329                             &self.cx.sess,
1330                             ident,
1331                             span,
1332                             &self.cx.current_expansion.module,
1333                             self.cx.current_expansion.dir_ownership,
1334                             &mut attrs,
1335                         );
1336
1337                         if let Some(extern_mod_loaded) = self.cx.extern_mod_loaded {
1338                             (attrs, items) = extern_mod_loaded(ident, attrs, items, inner_span);
1339                         }
1340
1341                         *mod_kind = ModKind::Loaded(items, Inline::No, inner_span);
1342                         item.attrs = attrs;
1343                         if item.attrs.len() > old_attrs_len {
1344                             // If we loaded an out-of-line module and added some inner attributes,
1345                             // then we need to re-configure it and re-collect attributes for
1346                             // resolution and expansion.
1347                             item = configure!(self, item);
1348
1349                             if let Some(attr) = self.take_first_attr(&mut item) {
1350                                 return self
1351                                     .collect_attr(
1352                                         attr,
1353                                         Annotatable::Item(item),
1354                                         AstFragmentKind::Items,
1355                                     )
1356                                     .make_items();
1357                             }
1358                         }
1359                         (Some(file_path), dir_path, dir_ownership)
1360                     }
1361                 };
1362
1363                 // Set the module info before we flat map.
1364                 let mut module = self.cx.current_expansion.module.with_dir_path(dir_path);
1365                 module.mod_path.push(ident);
1366                 if let Some(file_path) = file_path {
1367                     module.file_path_stack.push(file_path);
1368                 }
1369
1370                 let orig_module =
1371                     mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1372                 let orig_dir_ownership =
1373                     mem::replace(&mut self.cx.current_expansion.dir_ownership, dir_ownership);
1374
1375                 let result = noop_flat_map_item(item, self);
1376
1377                 // Restore the module info.
1378                 self.cx.current_expansion.dir_ownership = orig_dir_ownership;
1379                 self.cx.current_expansion.module = orig_module;
1380
1381                 result
1382             }
1383             _ => {
1384                 item.attrs = attrs;
1385                 noop_flat_map_item(item, self)
1386             }
1387         }
1388     }
1389
1390     fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1391         let mut item = configure!(self, item);
1392
1393         if let Some(attr) = self.take_first_attr(&mut item) {
1394             return self
1395                 .collect_attr(attr, Annotatable::TraitItem(item), AstFragmentKind::TraitItems)
1396                 .make_trait_items();
1397         }
1398
1399         match item.kind {
1400             ast::AssocItemKind::MacCall(..) => {
1401                 self.check_attributes(&item.attrs);
1402                 item.and_then(|item| match item.kind {
1403                     ast::AssocItemKind::MacCall(mac) => self
1404                         .collect_bang(mac, item.span, AstFragmentKind::TraitItems)
1405                         .make_trait_items(),
1406                     _ => unreachable!(),
1407                 })
1408             }
1409             _ => noop_flat_map_assoc_item(item, self),
1410         }
1411     }
1412
1413     fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
1414         let mut item = configure!(self, item);
1415
1416         if let Some(attr) = self.take_first_attr(&mut item) {
1417             return self
1418                 .collect_attr(attr, Annotatable::ImplItem(item), AstFragmentKind::ImplItems)
1419                 .make_impl_items();
1420         }
1421
1422         match item.kind {
1423             ast::AssocItemKind::MacCall(..) => {
1424                 self.check_attributes(&item.attrs);
1425                 item.and_then(|item| match item.kind {
1426                     ast::AssocItemKind::MacCall(mac) => self
1427                         .collect_bang(mac, item.span, AstFragmentKind::ImplItems)
1428                         .make_impl_items(),
1429                     _ => unreachable!(),
1430                 })
1431             }
1432             _ => noop_flat_map_assoc_item(item, self),
1433         }
1434     }
1435
1436     fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1437         match ty.kind {
1438             ast::TyKind::MacCall(_) => {}
1439             _ => return noop_visit_ty(ty, self),
1440         };
1441
1442         visit_clobber(ty, |mut ty| match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1443             ast::TyKind::MacCall(mac) => {
1444                 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty()
1445             }
1446             _ => unreachable!(),
1447         });
1448     }
1449
1450     fn flat_map_foreign_item(
1451         &mut self,
1452         foreign_item: P<ast::ForeignItem>,
1453     ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
1454         let mut foreign_item = configure!(self, foreign_item);
1455
1456         if let Some(attr) = self.take_first_attr(&mut foreign_item) {
1457             return self
1458                 .collect_attr(
1459                     attr,
1460                     Annotatable::ForeignItem(foreign_item),
1461                     AstFragmentKind::ForeignItems,
1462                 )
1463                 .make_foreign_items();
1464         }
1465
1466         match foreign_item.kind {
1467             ast::ForeignItemKind::MacCall(..) => {
1468                 self.check_attributes(&foreign_item.attrs);
1469                 foreign_item.and_then(|item| match item.kind {
1470                     ast::ForeignItemKind::MacCall(mac) => self
1471                         .collect_bang(mac, item.span, AstFragmentKind::ForeignItems)
1472                         .make_foreign_items(),
1473                     _ => unreachable!(),
1474                 })
1475             }
1476             _ => noop_flat_map_foreign_item(foreign_item, self),
1477         }
1478     }
1479
1480     fn flat_map_generic_param(
1481         &mut self,
1482         param: ast::GenericParam,
1483     ) -> SmallVec<[ast::GenericParam; 1]> {
1484         let mut param = configure!(self, param);
1485
1486         if let Some(attr) = self.take_first_attr(&mut param) {
1487             return self
1488                 .collect_attr(
1489                     attr,
1490                     Annotatable::GenericParam(param),
1491                     AstFragmentKind::GenericParams,
1492                 )
1493                 .make_generic_params();
1494         }
1495
1496         noop_flat_map_generic_param(param, self)
1497     }
1498
1499     fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1500         // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1501         // contents="file contents")]` attributes
1502         if !self.cx.sess.check_name(at, sym::doc) {
1503             return noop_visit_attribute(at, self);
1504         }
1505
1506         if let Some(list) = at.meta_item_list() {
1507             if !list.iter().any(|it| it.has_name(sym::include)) {
1508                 return noop_visit_attribute(at, self);
1509             }
1510
1511             let mut items = vec![];
1512
1513             for mut it in list {
1514                 if !it.has_name(sym::include) {
1515                     items.push({
1516                         noop_visit_meta_list_item(&mut it, self);
1517                         it
1518                     });
1519                     continue;
1520                 }
1521
1522                 if let Some(file) = it.value_str() {
1523                     let err_count = self.cx.sess.parse_sess.span_diagnostic.err_count();
1524                     self.check_attributes(slice::from_ref(at));
1525                     if self.cx.sess.parse_sess.span_diagnostic.err_count() > err_count {
1526                         // avoid loading the file if they haven't enabled the feature
1527                         return noop_visit_attribute(at, self);
1528                     }
1529
1530                     let filename = match self.cx.resolve_path(&*file.as_str(), it.span()) {
1531                         Ok(filename) => filename,
1532                         Err(mut err) => {
1533                             err.emit();
1534                             continue;
1535                         }
1536                     };
1537
1538                     match self.cx.source_map().load_file(&filename) {
1539                         Ok(source_file) => {
1540                             let src = source_file
1541                                 .src
1542                                 .as_ref()
1543                                 .expect("freshly loaded file should have a source");
1544                             let src_interned = Symbol::intern(src.as_str());
1545
1546                             let include_info = vec![
1547                                 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1548                                     Ident::with_dummy_span(sym::file),
1549                                     file,
1550                                     DUMMY_SP,
1551                                 )),
1552                                 ast::NestedMetaItem::MetaItem(attr::mk_name_value_item_str(
1553                                     Ident::with_dummy_span(sym::contents),
1554                                     src_interned,
1555                                     DUMMY_SP,
1556                                 )),
1557                             ];
1558
1559                             let include_ident = Ident::with_dummy_span(sym::include);
1560                             let item = attr::mk_list_item(include_ident, include_info);
1561                             items.push(ast::NestedMetaItem::MetaItem(item));
1562                         }
1563                         Err(e) => {
1564                             let lit_span = it.name_value_literal_span().unwrap();
1565
1566                             if e.kind() == ErrorKind::InvalidData {
1567                                 self.cx
1568                                     .struct_span_err(
1569                                         lit_span,
1570                                         &format!("{} wasn't a utf-8 file", filename.display()),
1571                                     )
1572                                     .span_label(lit_span, "contains invalid utf-8")
1573                                     .emit();
1574                             } else {
1575                                 let mut err = self.cx.struct_span_err(
1576                                     lit_span,
1577                                     &format!("couldn't read {}: {}", filename.display(), e),
1578                                 );
1579                                 err.span_label(lit_span, "couldn't read file");
1580
1581                                 err.emit();
1582                             }
1583                         }
1584                     }
1585                 } else {
1586                     let mut err = self
1587                         .cx
1588                         .struct_span_err(it.span(), "expected path to external documentation");
1589
1590                     // Check if the user erroneously used `doc(include(...))` syntax.
1591                     let literal = it.meta_item_list().and_then(|list| {
1592                         if list.len() == 1 {
1593                             list[0].literal().map(|literal| &literal.kind)
1594                         } else {
1595                             None
1596                         }
1597                     });
1598
1599                     let (path, applicability) = match &literal {
1600                         Some(LitKind::Str(path, ..)) => {
1601                             (path.to_string(), Applicability::MachineApplicable)
1602                         }
1603                         _ => (String::from("<path>"), Applicability::HasPlaceholders),
1604                     };
1605
1606                     err.span_suggestion(
1607                         it.span(),
1608                         "provide a file path with `=`",
1609                         format!("include = \"{}\"", path),
1610                         applicability,
1611                     );
1612
1613                     err.emit();
1614                 }
1615             }
1616
1617             let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1618             *at = ast::Attribute {
1619                 kind: ast::AttrKind::Normal(
1620                     AttrItem { path: meta.path, args: meta.kind.mac_args(meta.span), tokens: None },
1621                     None,
1622                 ),
1623                 span: at.span,
1624                 id: at.id,
1625                 style: at.style,
1626             };
1627         } else {
1628             noop_visit_attribute(at, self)
1629         }
1630     }
1631
1632     fn visit_id(&mut self, id: &mut ast::NodeId) {
1633         if self.monotonic {
1634             debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1635             *id = self.cx.resolver.next_node_id()
1636         }
1637     }
1638 }
1639
1640 pub struct ExpansionConfig<'feat> {
1641     pub crate_name: String,
1642     pub features: Option<&'feat Features>,
1643     pub recursion_limit: Limit,
1644     pub trace_mac: bool,
1645     pub should_test: bool,          // If false, strip `#[test]` nodes
1646     pub span_debug: bool,           // If true, use verbose debugging for `proc_macro::Span`
1647     pub proc_macro_backtrace: bool, // If true, show backtraces for proc-macro panics
1648 }
1649
1650 impl<'feat> ExpansionConfig<'feat> {
1651     pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1652         ExpansionConfig {
1653             crate_name,
1654             features: None,
1655             recursion_limit: Limit::new(1024),
1656             trace_mac: false,
1657             should_test: false,
1658             span_debug: false,
1659             proc_macro_backtrace: false,
1660         }
1661     }
1662
1663     fn proc_macro_hygiene(&self) -> bool {
1664         self.features.map_or(false, |features| features.proc_macro_hygiene)
1665     }
1666 }