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