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