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