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