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