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