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