]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/expand.rs
9fcd918cef1746050dc7b1c95e824cfdf4efca4c
[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, ParseSess};
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::{self, 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                     let result =
581                         self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span);
582                     self.gate_proc_macro_expansion(span, &result);
583                     result
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_attr_item(span, &item);
609                     let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
610                         Annotatable::Item(item) => token::NtItem(item),
611                         Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
612                         Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
613                         Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
614                         Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
615                         Annotatable::Expr(expr) => token::NtExpr(expr),
616                         Annotatable::Arm(..)
617                         | Annotatable::Field(..)
618                         | Annotatable::FieldPat(..)
619                         | Annotatable::GenericParam(..)
620                         | Annotatable::Param(..)
621                         | Annotatable::StructField(..)
622                         | Annotatable::Variant(..)
623                             => panic!("unexpected annotatable"),
624                     })), DUMMY_SP).into();
625                     let input = self.extract_proc_macro_attr_input(attr.item.tokens, span);
626                     let tok_result = expander.expand(self.cx, span, input, item_tok);
627                     let res =
628                         self.parse_ast_fragment(tok_result, fragment_kind, &attr.item.path, span);
629                     self.gate_proc_macro_expansion(span, &res);
630                     res
631                 }
632                 SyntaxExtensionKind::LegacyAttr(expander) => {
633                     match attr.parse_meta(self.cx.parse_sess) {
634                         Ok(meta) => {
635                             let item = expander.expand(self.cx, span, &meta, item);
636                             fragment_kind.expect_from_annotatables(item)
637                         }
638                         Err(mut err) => {
639                             err.emit();
640                             fragment_kind.dummy(span)
641                         }
642                     }
643                 }
644                 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
645                     attr::mark_known(&attr);
646                     if *mark_used {
647                         attr::mark_used(&attr);
648                     }
649                     item.visit_attrs(|attrs| attrs.push(attr));
650                     fragment_kind.expect_from_annotatables(iter::once(item))
651                 }
652                 _ => unreachable!()
653             }
654             InvocationKind::Derive { path, item } => match ext {
655                 SyntaxExtensionKind::Derive(expander) |
656                 SyntaxExtensionKind::LegacyDerive(expander) => {
657                     if !item.derive_allowed() {
658                         return fragment_kind.dummy(span);
659                     }
660                     let meta = ast::MetaItem { kind: ast::MetaItemKind::Word, span, path };
661                     let items = expander.expand(self.cx, span, &meta, item);
662                     fragment_kind.expect_from_annotatables(items)
663                 }
664                 _ => unreachable!()
665             }
666             InvocationKind::DeriveContainer { .. } => unreachable!()
667         }
668     }
669
670     fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
671         let mut trees = tokens.trees();
672         match trees.next() {
673             Some(TokenTree::Delimited(_, _, tts)) => {
674                 if trees.next().is_none() {
675                     return tts.into()
676                 }
677             }
678             Some(TokenTree::Token(..)) => {}
679             None => return TokenStream::default(),
680         }
681         self.cx.span_err(span, "custom attribute invocations must be \
682             of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
683             followed by a delimiter token");
684         TokenStream::default()
685     }
686
687     fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
688         let (kind, gate) = match *item {
689             Annotatable::Item(ref item) => {
690                 match item.kind {
691                     ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
692                     ItemKind::Mod(_) => ("modules", sym::proc_macro_hygiene),
693                     _ => return,
694                 }
695             }
696             Annotatable::TraitItem(_) => return,
697             Annotatable::ImplItem(_) => return,
698             Annotatable::ForeignItem(_) => return,
699             Annotatable::Stmt(_) |
700             Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
701             Annotatable::Stmt(_) => ("statements", sym::proc_macro_hygiene),
702             Annotatable::Expr(_) => ("expressions", sym::proc_macro_hygiene),
703             Annotatable::Arm(..)
704             | Annotatable::Field(..)
705             | Annotatable::FieldPat(..)
706             | Annotatable::GenericParam(..)
707             | Annotatable::Param(..)
708             | Annotatable::StructField(..)
709             | Annotatable::Variant(..)
710             => panic!("unexpected annotatable"),
711         };
712         emit_feature_err(
713             self.cx.parse_sess,
714             gate,
715             span,
716             GateIssue::Language,
717             &format!("custom attributes cannot be applied to {}", kind),
718         );
719     }
720
721     fn gate_proc_macro_expansion(&self, span: Span, fragment: &AstFragment) {
722         if self.cx.ecfg.proc_macro_hygiene() {
723             return
724         }
725
726         fragment.visit_with(&mut DisallowMacros {
727             span,
728             parse_sess: self.cx.parse_sess,
729         });
730
731         struct DisallowMacros<'a> {
732             span: Span,
733             parse_sess: &'a ParseSess,
734         }
735
736         impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
737             fn visit_item(&mut self, i: &'ast ast::Item) {
738                 if let ast::ItemKind::MacroDef(_) = i.kind {
739                     emit_feature_err(
740                         self.parse_sess,
741                         sym::proc_macro_hygiene,
742                         self.span,
743                         GateIssue::Language,
744                         "procedural macros cannot expand to macro definitions",
745                     );
746                 }
747                 visit::walk_item(self, i);
748             }
749
750             fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
751                 // ...
752             }
753         }
754     }
755
756     fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
757         let kind = match kind {
758             AstFragmentKind::Expr |
759             AstFragmentKind::OptExpr => "expressions",
760             AstFragmentKind::Pat => "patterns",
761             AstFragmentKind::Stmts => "statements",
762             AstFragmentKind::Ty |
763             AstFragmentKind::Items |
764             AstFragmentKind::TraitItems |
765             AstFragmentKind::ImplItems |
766             AstFragmentKind::ForeignItems => return,
767             AstFragmentKind::Arms
768             | AstFragmentKind::Fields
769             | AstFragmentKind::FieldPats
770             | AstFragmentKind::GenericParams
771             | AstFragmentKind::Params
772             | AstFragmentKind::StructFields
773             | AstFragmentKind::Variants
774                 => panic!("unexpected AST fragment kind"),
775         };
776         if self.cx.ecfg.proc_macro_hygiene() {
777             return
778         }
779         emit_feature_err(
780             self.cx.parse_sess,
781             sym::proc_macro_hygiene,
782             span,
783             GateIssue::Language,
784             &format!("procedural macros cannot be expanded to {}", kind),
785         );
786     }
787
788     fn parse_ast_fragment(
789         &mut self,
790         toks: TokenStream,
791         kind: AstFragmentKind,
792         path: &Path,
793         span: Span,
794     ) -> AstFragment {
795         let mut parser = self.cx.new_parser_from_tts(toks);
796         match parser.parse_ast_fragment(kind, false) {
797             Ok(fragment) => {
798                 parser.ensure_complete_parse(path, kind.name(), span);
799                 fragment
800             }
801             Err(mut err) => {
802                 err.set_span(span);
803                 annotate_err_with_kind(&mut err, kind, span);
804                 err.emit();
805                 self.cx.trace_macros_diag();
806                 kind.dummy(span)
807             }
808         }
809     }
810 }
811
812 impl<'a> Parser<'a> {
813     pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
814                               -> PResult<'a, AstFragment> {
815         Ok(match kind {
816             AstFragmentKind::Items => {
817                 let mut items = SmallVec::new();
818                 while let Some(item) = self.parse_item()? {
819                     items.push(item);
820                 }
821                 AstFragment::Items(items)
822             }
823             AstFragmentKind::TraitItems => {
824                 let mut items = SmallVec::new();
825                 while self.token != token::Eof {
826                     items.push(self.parse_trait_item(&mut false)?);
827                 }
828                 AstFragment::TraitItems(items)
829             }
830             AstFragmentKind::ImplItems => {
831                 let mut items = SmallVec::new();
832                 while self.token != token::Eof {
833                     items.push(self.parse_impl_item(&mut false)?);
834                 }
835                 AstFragment::ImplItems(items)
836             }
837             AstFragmentKind::ForeignItems => {
838                 let mut items = SmallVec::new();
839                 while self.token != token::Eof {
840                     items.push(self.parse_foreign_item(DUMMY_SP)?);
841                 }
842                 AstFragment::ForeignItems(items)
843             }
844             AstFragmentKind::Stmts => {
845                 let mut stmts = SmallVec::new();
846                 while self.token != token::Eof &&
847                       // won't make progress on a `}`
848                       self.token != token::CloseDelim(token::Brace) {
849                     if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
850                         stmts.push(stmt);
851                     }
852                 }
853                 AstFragment::Stmts(stmts)
854             }
855             AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
856             AstFragmentKind::OptExpr => {
857                 if self.token != token::Eof {
858                     AstFragment::OptExpr(Some(self.parse_expr()?))
859                 } else {
860                     AstFragment::OptExpr(None)
861                 }
862             },
863             AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
864             AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat(None)?),
865             AstFragmentKind::Arms
866             | AstFragmentKind::Fields
867             | AstFragmentKind::FieldPats
868             | AstFragmentKind::GenericParams
869             | AstFragmentKind::Params
870             | AstFragmentKind::StructFields
871             | AstFragmentKind::Variants
872                 => panic!("unexpected AST fragment kind"),
873         })
874     }
875
876     pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
877         if self.token != token::Eof {
878             let msg = format!("macro expansion ignores token `{}` and any following",
879                               self.this_token_to_string());
880             // Avoid emitting backtrace info twice.
881             let def_site_span = self.token.span.with_ctxt(SyntaxContext::root());
882             let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
883             err.span_label(span, "caused by the macro expansion here");
884             let msg = format!(
885                 "the usage of `{}!` is likely invalid in {} context",
886                 pprust::path_to_string(&macro_path),
887                 kind_name,
888             );
889             err.note(&msg);
890             let semi_span = self.sess.source_map().next_point(span);
891
892             let semi_full_span = semi_span.to(self.sess.source_map().next_point(semi_span));
893             match self.sess.source_map().span_to_snippet(semi_full_span) {
894                 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
895                     err.span_suggestion(
896                         semi_span,
897                         "you might be missing a semicolon here",
898                         ";".to_owned(),
899                         Applicability::MaybeIncorrect,
900                     );
901                 }
902                 _ => {}
903             }
904             err.emit();
905         }
906     }
907 }
908
909 struct InvocationCollector<'a, 'b> {
910     cx: &'a mut ExtCtxt<'b>,
911     cfg: StripUnconfigured<'a>,
912     invocations: Vec<Invocation>,
913     monotonic: bool,
914 }
915
916 impl<'a, 'b> InvocationCollector<'a, 'b> {
917     fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
918         // Expansion data for all the collected invocations is set upon their resolution,
919         // with exception of the derive container case which is not resolved and can get
920         // its expansion data immediately.
921         let expn_data = match &kind {
922             InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
923                 parent: self.cx.current_expansion.id,
924                 ..ExpnData::default(
925                     ExpnKind::Macro(MacroKind::Attr, sym::derive),
926                     item.span(), self.cx.parse_sess.edition,
927                 )
928             }),
929             _ => None,
930         };
931         let expn_id = ExpnId::fresh(expn_data);
932         self.invocations.push(Invocation {
933             kind,
934             fragment_kind,
935             expansion_data: ExpansionData {
936                 id: expn_id,
937                 depth: self.cx.current_expansion.depth + 1,
938                 ..self.cx.current_expansion.clone()
939             },
940         });
941         placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
942     }
943
944     fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
945         self.collect(kind, InvocationKind::Bang { mac, span })
946     }
947
948     fn collect_attr(&mut self,
949                     attr: Option<ast::Attribute>,
950                     derives: Vec<Path>,
951                     item: Annotatable,
952                     kind: AstFragmentKind,
953                     after_derive: bool)
954                     -> AstFragment {
955         self.collect(kind, match attr {
956             Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
957             None => InvocationKind::DeriveContainer { derives, item },
958         })
959     }
960
961     fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
962                        -> Option<ast::Attribute> {
963         let attr = attrs.iter()
964                         .position(|a| {
965                             if a.path == sym::derive {
966                                 *after_derive = true;
967                             }
968                             !attr::is_known(a) && !is_builtin_attr(a)
969                         })
970                         .map(|i| attrs.remove(i));
971         if let Some(attr) = &attr {
972             if !self.cx.ecfg.custom_inner_attributes() &&
973                attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
974                 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
975                                  attr.span, GateIssue::Language,
976                                  "non-builtin inner attributes are unstable");
977             }
978         }
979         attr
980     }
981
982     /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
983     fn classify_item<T>(&mut self, item: &mut T)
984                         -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
985         where T: HasAttrs,
986     {
987         let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
988
989         item.visit_attrs(|mut attrs| {
990             attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
991             traits = collect_derives(&mut self.cx, &mut attrs);
992         });
993
994         (attr, traits, after_derive)
995     }
996
997     /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
998     /// to the unused-attributes lint (making it an error on statements and expressions
999     /// is a breaking change)
1000     fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
1001                                      -> (Option<ast::Attribute>, /* after_derive */ bool) {
1002         let (mut attr, mut after_derive) = (None, false);
1003
1004         nonitem.visit_attrs(|mut attrs| {
1005             attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1006         });
1007
1008         (attr, after_derive)
1009     }
1010
1011     fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1012         self.cfg.configure(node)
1013     }
1014
1015     // Detect use of feature-gated or invalid attributes on macro invocations
1016     // since they will not be detected after macro expansion.
1017     fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1018         let features = self.cx.ecfg.features.unwrap();
1019         for attr in attrs.iter() {
1020             feature_gate::check_attribute(attr, self.cx.parse_sess, features);
1021
1022             // macros are expanded before any lint passes so this warning has to be hardcoded
1023             if attr.path == sym::derive {
1024                 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1025                     .note("this may become a hard error in a future release")
1026                     .emit();
1027             }
1028         }
1029     }
1030 }
1031
1032 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
1033     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
1034         self.cfg.configure_expr(expr);
1035         visit_clobber(expr.deref_mut(), |mut expr| {
1036             self.cfg.configure_expr_kind(&mut expr.kind);
1037
1038             // ignore derives so they remain unused
1039             let (attr, after_derive) = self.classify_nonitem(&mut expr);
1040
1041             if attr.is_some() {
1042                 // Collect the invoc regardless of whether or not attributes are permitted here
1043                 // expansion will eat the attribute so it won't error later.
1044                 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1045
1046                 // AstFragmentKind::Expr requires the macro to emit an expression.
1047                 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1048                                           AstFragmentKind::Expr, after_derive)
1049                     .make_expr()
1050                     .into_inner()
1051             }
1052
1053             if let ast::ExprKind::Mac(mac) = expr.kind {
1054                 self.check_attributes(&expr.attrs);
1055                 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1056                     .make_expr()
1057                     .into_inner()
1058             } else {
1059                 noop_visit_expr(&mut expr, self);
1060                 expr
1061             }
1062         });
1063     }
1064
1065     fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
1066         let mut arm = configure!(self, arm);
1067
1068         let (attr, traits, after_derive) = self.classify_item(&mut arm);
1069         if attr.is_some() || !traits.is_empty() {
1070             return self.collect_attr(attr, traits, Annotatable::Arm(arm),
1071                                      AstFragmentKind::Arms, after_derive)
1072                                      .make_arms();
1073         }
1074
1075         noop_flat_map_arm(arm, self)
1076     }
1077
1078     fn flat_map_field(&mut self, field: ast::Field) -> SmallVec<[ast::Field; 1]> {
1079         let mut field = configure!(self, field);
1080
1081         let (attr, traits, after_derive) = self.classify_item(&mut field);
1082         if attr.is_some() || !traits.is_empty() {
1083             return self.collect_attr(attr, traits, Annotatable::Field(field),
1084                                      AstFragmentKind::Fields, after_derive)
1085                                      .make_fields();
1086         }
1087
1088         noop_flat_map_field(field, self)
1089     }
1090
1091     fn flat_map_field_pattern(&mut self, fp: ast::FieldPat) -> SmallVec<[ast::FieldPat; 1]> {
1092         let mut fp = configure!(self, fp);
1093
1094         let (attr, traits, after_derive) = self.classify_item(&mut fp);
1095         if attr.is_some() || !traits.is_empty() {
1096             return self.collect_attr(attr, traits, Annotatable::FieldPat(fp),
1097                                      AstFragmentKind::FieldPats, after_derive)
1098                                      .make_field_patterns();
1099         }
1100
1101         noop_flat_map_field_pattern(fp, self)
1102     }
1103
1104     fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
1105         let mut p = configure!(self, p);
1106
1107         let (attr, traits, after_derive) = self.classify_item(&mut p);
1108         if attr.is_some() || !traits.is_empty() {
1109             return self.collect_attr(attr, traits, Annotatable::Param(p),
1110                                      AstFragmentKind::Params, after_derive)
1111                                      .make_params();
1112         }
1113
1114         noop_flat_map_param(p, self)
1115     }
1116
1117     fn flat_map_struct_field(&mut self, sf: ast::StructField) -> SmallVec<[ast::StructField; 1]> {
1118         let mut sf = configure!(self, sf);
1119
1120         let (attr, traits, after_derive) = self.classify_item(&mut sf);
1121         if attr.is_some() || !traits.is_empty() {
1122             return self.collect_attr(attr, traits, Annotatable::StructField(sf),
1123                                      AstFragmentKind::StructFields, after_derive)
1124                                      .make_struct_fields();
1125         }
1126
1127         noop_flat_map_struct_field(sf, self)
1128     }
1129
1130     fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
1131         let mut variant = configure!(self, variant);
1132
1133         let (attr, traits, after_derive) = self.classify_item(&mut variant);
1134         if attr.is_some() || !traits.is_empty() {
1135             return self.collect_attr(attr, traits, Annotatable::Variant(variant),
1136                                      AstFragmentKind::Variants, after_derive)
1137                                      .make_variants();
1138         }
1139
1140         noop_flat_map_variant(variant, self)
1141     }
1142
1143     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1144         let expr = configure!(self, expr);
1145         expr.filter_map(|mut expr| {
1146             self.cfg.configure_expr_kind(&mut expr.kind);
1147
1148             // Ignore derives so they remain unused.
1149             let (attr, after_derive) = self.classify_nonitem(&mut expr);
1150
1151             if attr.is_some() {
1152                 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1153
1154                 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1155                                          AstFragmentKind::OptExpr, after_derive)
1156                     .make_opt_expr()
1157                     .map(|expr| expr.into_inner())
1158             }
1159
1160             if let ast::ExprKind::Mac(mac) = expr.kind {
1161                 self.check_attributes(&expr.attrs);
1162                 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1163                     .make_opt_expr()
1164                     .map(|expr| expr.into_inner())
1165             } else {
1166                 Some({ noop_visit_expr(&mut expr, self); expr })
1167             }
1168         })
1169     }
1170
1171     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
1172         self.cfg.configure_pat(pat);
1173         match pat.kind {
1174             PatKind::Mac(_) => {}
1175             _ => return noop_visit_pat(pat, self),
1176         }
1177
1178         visit_clobber(pat, |mut pat| {
1179             match mem::replace(&mut pat.kind, PatKind::Wild) {
1180                 PatKind::Mac(mac) =>
1181                     self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1182                 _ => unreachable!(),
1183             }
1184         });
1185     }
1186
1187     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1188         let mut stmt = configure!(self, stmt);
1189
1190         // we'll expand attributes on expressions separately
1191         if !stmt.is_expr() {
1192             let (attr, derives, after_derive) = if stmt.is_item() {
1193                 self.classify_item(&mut stmt)
1194             } else {
1195                 // ignore derives on non-item statements so it falls through
1196                 // to the unused-attributes lint
1197                 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1198                 (attr, vec![], after_derive)
1199             };
1200
1201             if attr.is_some() || !derives.is_empty() {
1202                 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1203                                          AstFragmentKind::Stmts, after_derive).make_stmts();
1204             }
1205         }
1206
1207         if let StmtKind::Mac(mac) = stmt.kind {
1208             let (mac, style, attrs) = mac.into_inner();
1209             self.check_attributes(&attrs);
1210             let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1211                                         .make_stmts();
1212
1213             // If this is a macro invocation with a semicolon, then apply that
1214             // semicolon to the final statement produced by expansion.
1215             if style == MacStmtStyle::Semicolon {
1216                 if let Some(stmt) = placeholder.pop() {
1217                     placeholder.push(stmt.add_trailing_semicolon());
1218                 }
1219             }
1220
1221             return placeholder;
1222         }
1223
1224         // The placeholder expander gives ids to statements, so we avoid folding the id here.
1225         let ast::Stmt { id, kind, span } = stmt;
1226         noop_flat_map_stmt_kind(kind, self).into_iter().map(|kind| {
1227             ast::Stmt { id, kind, span }
1228         }).collect()
1229
1230     }
1231
1232     fn visit_block(&mut self, block: &mut P<Block>) {
1233         let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1234         self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1235         noop_visit_block(block, self);
1236         self.cx.current_expansion.directory_ownership = old_directory_ownership;
1237     }
1238
1239     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1240         let mut item = configure!(self, item);
1241
1242         let (attr, traits, after_derive) = self.classify_item(&mut item);
1243         if attr.is_some() || !traits.is_empty() {
1244             return self.collect_attr(attr, traits, Annotatable::Item(item),
1245                                      AstFragmentKind::Items, after_derive).make_items();
1246         }
1247
1248         match item.kind {
1249             ast::ItemKind::Mac(..) => {
1250                 self.check_attributes(&item.attrs);
1251                 item.and_then(|item| match item.kind {
1252                     ItemKind::Mac(mac) => self.collect(
1253                         AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1254                     ).make_items(),
1255                     _ => unreachable!(),
1256                 })
1257             }
1258             ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1259                 if item.ident == Ident::invalid() {
1260                     return noop_flat_map_item(item, self);
1261                 }
1262
1263                 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1264                 let mut module = (*self.cx.current_expansion.module).clone();
1265                 module.mod_path.push(item.ident);
1266
1267                 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1268                 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1269                 // Thus, if `inner` is the dummy span, we know the module is inline.
1270                 let inline_module = item.span.contains(inner) || inner.is_dummy();
1271
1272                 if inline_module {
1273                     if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1274                         self.cx.current_expansion.directory_ownership =
1275                             DirectoryOwnership::Owned { relative: None };
1276                         module.directory.push(&*path.as_str());
1277                     } else {
1278                         module.directory.push(&*item.ident.as_str());
1279                     }
1280                 } else {
1281                     let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1282                     let mut path = match path {
1283                         FileName::Real(path) => path,
1284                         other => PathBuf::from(other.to_string()),
1285                     };
1286                     let directory_ownership = match path.file_name().unwrap().to_str() {
1287                         Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1288                         Some(_) => DirectoryOwnership::Owned {
1289                             relative: Some(item.ident),
1290                         },
1291                         None => DirectoryOwnership::UnownedViaMod(false),
1292                     };
1293                     path.pop();
1294                     module.directory = path;
1295                     self.cx.current_expansion.directory_ownership = directory_ownership;
1296                 }
1297
1298                 let orig_module =
1299                     mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1300                 let result = noop_flat_map_item(item, self);
1301                 self.cx.current_expansion.module = orig_module;
1302                 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1303                 result
1304             }
1305
1306             _ => noop_flat_map_item(item, self),
1307         }
1308     }
1309
1310     fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1311         let mut item = configure!(self, item);
1312
1313         let (attr, traits, after_derive) = self.classify_item(&mut item);
1314         if attr.is_some() || !traits.is_empty() {
1315             return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1316                                      AstFragmentKind::TraitItems, after_derive).make_trait_items()
1317         }
1318
1319         match item.kind {
1320             ast::TraitItemKind::Macro(mac) => {
1321                 let ast::TraitItem { attrs, span, .. } = item;
1322                 self.check_attributes(&attrs);
1323                 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1324             }
1325             _ => noop_flat_map_trait_item(item, self),
1326         }
1327     }
1328
1329     fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1330         let mut item = configure!(self, item);
1331
1332         let (attr, traits, after_derive) = self.classify_item(&mut item);
1333         if attr.is_some() || !traits.is_empty() {
1334             return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1335                                      AstFragmentKind::ImplItems, after_derive).make_impl_items();
1336         }
1337
1338         match item.kind {
1339             ast::ImplItemKind::Macro(mac) => {
1340                 let ast::ImplItem { attrs, span, .. } = item;
1341                 self.check_attributes(&attrs);
1342                 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1343             }
1344             _ => noop_flat_map_impl_item(item, self),
1345         }
1346     }
1347
1348     fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1349         match ty.kind {
1350             ast::TyKind::Mac(_) => {}
1351             _ => return noop_visit_ty(ty, self),
1352         };
1353
1354         visit_clobber(ty, |mut ty| {
1355             match mem::replace(&mut ty.kind, ast::TyKind::Err) {
1356                 ast::TyKind::Mac(mac) =>
1357                     self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1358                 _ => unreachable!(),
1359             }
1360         });
1361     }
1362
1363     fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1364         self.cfg.configure_foreign_mod(foreign_mod);
1365         noop_visit_foreign_mod(foreign_mod, self);
1366     }
1367
1368     fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1369         -> SmallVec<[ast::ForeignItem; 1]>
1370     {
1371         let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1372
1373         if attr.is_some() || !traits.is_empty() {
1374             return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1375                                      AstFragmentKind::ForeignItems, after_derive)
1376                                      .make_foreign_items();
1377         }
1378
1379         if let ast::ForeignItemKind::Macro(mac) = foreign_item.kind {
1380             self.check_attributes(&foreign_item.attrs);
1381             return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1382                 .make_foreign_items();
1383         }
1384
1385         noop_flat_map_foreign_item(foreign_item, self)
1386     }
1387
1388     fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1389         match item {
1390             ast::ItemKind::MacroDef(..) => {}
1391             _ => {
1392                 self.cfg.configure_item_kind(item);
1393                 noop_visit_item_kind(item, self);
1394             }
1395         }
1396     }
1397
1398     fn flat_map_generic_param(
1399         &mut self,
1400         param: ast::GenericParam
1401     ) -> SmallVec<[ast::GenericParam; 1]>
1402     {
1403         let mut param = configure!(self, param);
1404
1405         let (attr, traits, after_derive) = self.classify_item(&mut param);
1406         if attr.is_some() || !traits.is_empty() {
1407             return self.collect_attr(attr, traits, Annotatable::GenericParam(param),
1408                                      AstFragmentKind::GenericParams, after_derive)
1409                                      .make_generic_params();
1410         }
1411
1412         noop_flat_map_generic_param(param, self)
1413     }
1414
1415     fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1416         // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1417         // contents="file contents")]` attributes
1418         if !at.check_name(sym::doc) {
1419             return noop_visit_attribute(at, self);
1420         }
1421
1422         if let Some(list) = at.meta_item_list() {
1423             if !list.iter().any(|it| it.check_name(sym::include)) {
1424                 return noop_visit_attribute(at, self);
1425             }
1426
1427             let mut items = vec![];
1428
1429             for mut it in list {
1430                 if !it.check_name(sym::include) {
1431                     items.push({ noop_visit_meta_list_item(&mut it, self); it });
1432                     continue;
1433                 }
1434
1435                 if let Some(file) = it.value_str() {
1436                     let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1437                     self.check_attributes(slice::from_ref(at));
1438                     if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1439                         // avoid loading the file if they haven't enabled the feature
1440                         return noop_visit_attribute(at, self);
1441                     }
1442
1443                     let filename = self.cx.resolve_path(&*file.as_str(), it.span());
1444                     match self.cx.source_map().load_file(&filename) {
1445                         Ok(source_file) => {
1446                             let src = source_file.src.as_ref()
1447                                 .expect("freshly loaded file should have a source");
1448                             let src_interned = Symbol::intern(src.as_str());
1449
1450                             let include_info = vec![
1451                                 ast::NestedMetaItem::MetaItem(
1452                                     attr::mk_name_value_item_str(
1453                                         Ident::with_dummy_span(sym::file),
1454                                         file,
1455                                         DUMMY_SP,
1456                                     ),
1457                                 ),
1458                                 ast::NestedMetaItem::MetaItem(
1459                                     attr::mk_name_value_item_str(
1460                                         Ident::with_dummy_span(sym::contents),
1461                                         src_interned,
1462                                         DUMMY_SP,
1463                                     ),
1464                                 ),
1465                             ];
1466
1467                             let include_ident = Ident::with_dummy_span(sym::include);
1468                             let item = attr::mk_list_item(include_ident, include_info);
1469                             items.push(ast::NestedMetaItem::MetaItem(item));
1470                         }
1471                         Err(e) => {
1472                             let lit = it
1473                                 .meta_item()
1474                                 .and_then(|item| item.name_value_literal())
1475                                 .unwrap();
1476
1477                             if e.kind() == ErrorKind::InvalidData {
1478                                 self.cx
1479                                     .struct_span_err(
1480                                         lit.span,
1481                                         &format!("{} wasn't a utf-8 file", filename.display()),
1482                                     )
1483                                     .span_label(lit.span, "contains invalid utf-8")
1484                                     .emit();
1485                             } else {
1486                                 let mut err = self.cx.struct_span_err(
1487                                     lit.span,
1488                                     &format!("couldn't read {}: {}", filename.display(), e),
1489                                 );
1490                                 err.span_label(lit.span, "couldn't read file");
1491
1492                                 err.emit();
1493                             }
1494                         }
1495                     }
1496                 } else {
1497                     let mut err = self.cx.struct_span_err(
1498                         it.span(),
1499                         &format!("expected path to external documentation"),
1500                     );
1501
1502                     // Check if the user erroneously used `doc(include(...))` syntax.
1503                     let literal = it.meta_item_list().and_then(|list| {
1504                         if list.len() == 1 {
1505                             list[0].literal().map(|literal| &literal.kind)
1506                         } else {
1507                             None
1508                         }
1509                     });
1510
1511                     let (path, applicability) = match &literal {
1512                         Some(LitKind::Str(path, ..)) => {
1513                             (path.to_string(), Applicability::MachineApplicable)
1514                         }
1515                         _ => (String::from("<path>"), Applicability::HasPlaceholders),
1516                     };
1517
1518                     err.span_suggestion(
1519                         it.span(),
1520                         "provide a file path with `=`",
1521                         format!("include = \"{}\"", path),
1522                         applicability,
1523                     );
1524
1525                     err.emit();
1526                 }
1527             }
1528
1529             let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
1530             *at = attr::Attribute {
1531                 item: AttrItem { path: meta.path, tokens: meta.kind.tokens(meta.span) },
1532                 span: at.span,
1533                 id: at.id,
1534                 style: at.style,
1535                 is_sugared_doc: false,
1536             };
1537         } else {
1538             noop_visit_attribute(at, self)
1539         }
1540     }
1541
1542     fn visit_id(&mut self, id: &mut ast::NodeId) {
1543         if self.monotonic {
1544             debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1545             *id = self.cx.resolver.next_node_id()
1546         }
1547     }
1548
1549     fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1550         self.cfg.configure_fn_decl(&mut fn_decl);
1551         noop_visit_fn_decl(fn_decl, self);
1552     }
1553 }
1554
1555 pub struct ExpansionConfig<'feat> {
1556     pub crate_name: String,
1557     pub features: Option<&'feat Features>,
1558     pub recursion_limit: usize,
1559     pub trace_mac: bool,
1560     pub should_test: bool, // If false, strip `#[test]` nodes
1561     pub single_step: bool,
1562     pub keep_macs: bool,
1563 }
1564
1565 impl<'feat> ExpansionConfig<'feat> {
1566     pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1567         ExpansionConfig {
1568             crate_name,
1569             features: None,
1570             recursion_limit: 1024,
1571             trace_mac: false,
1572             should_test: false,
1573             single_step: false,
1574             keep_macs: false,
1575         }
1576     }
1577
1578     fn proc_macro_hygiene(&self) -> bool {
1579         self.features.map_or(false, |features| features.proc_macro_hygiene)
1580     }
1581     fn custom_inner_attributes(&self) -> bool {
1582         self.features.map_or(false, |features| features.custom_inner_attributes)
1583     }
1584 }