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