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