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