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