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