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