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