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