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