]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/expand.rs
Auto merge of #41282 - arielb1:missing-impl-item, r=petrochenkov
[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, NameAndSpan, MacroBang, MacroAttribute};
15 use config::{is_test_or_bench, StripUnconfigured};
16 use errors::FatalError;
17 use ext::base::*;
18 use ext::derive::{add_derived_markers, collect_derives};
19 use ext::hygiene::Mark;
20 use ext::placeholders::{placeholder, PlaceholderExpander};
21 use feature_gate::{self, Features, is_builtin_attr};
22 use fold;
23 use fold::*;
24 use parse::{filemap_to_stream, ParseSess, DirectoryOwnership, PResult, token};
25 use parse::parser::Parser;
26 use print::pprust;
27 use ptr::P;
28 use std_inject;
29 use symbol::Symbol;
30 use symbol::keywords;
31 use syntax_pos::{Span, DUMMY_SP};
32 use tokenstream::TokenStream;
33 use util::small_vector::SmallVector;
34 use visit::Visitor;
35
36 use std::collections::HashMap;
37 use std::mem;
38 use std::path::PathBuf;
39 use std::rc::Rc;
40
41 macro_rules! expansions {
42     ($($kind:ident: $ty:ty [$($vec:ident, $ty_elt:ty)*], $kind_name:expr, .$make:ident,
43             $(.$fold:ident)*  $(lift .$fold_elt:ident)*,
44             $(.$visit:ident)*  $(lift .$visit_elt:ident)*;)*) => {
45         #[derive(Copy, Clone, PartialEq, Eq)]
46         pub enum ExpansionKind { OptExpr, $( $kind, )*  }
47         pub enum Expansion { OptExpr(Option<P<ast::Expr>>), $( $kind($ty), )* }
48
49         impl ExpansionKind {
50             pub fn name(self) -> &'static str {
51                 match self {
52                     ExpansionKind::OptExpr => "expression",
53                     $( ExpansionKind::$kind => $kind_name, )*
54                 }
55             }
56
57             fn make_from<'a>(self, result: Box<MacResult + 'a>) -> Option<Expansion> {
58                 match self {
59                     ExpansionKind::OptExpr => result.make_expr().map(Some).map(Expansion::OptExpr),
60                     $( ExpansionKind::$kind => result.$make().map(Expansion::$kind), )*
61                 }
62             }
63         }
64
65         impl Expansion {
66             pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
67                 match self {
68                     Expansion::OptExpr(expr) => expr,
69                     _ => panic!("Expansion::make_* called on the wrong kind of expansion"),
70                 }
71             }
72             $( pub fn $make(self) -> $ty {
73                 match self {
74                     Expansion::$kind(ast) => ast,
75                     _ => panic!("Expansion::make_* called on the wrong kind of expansion"),
76                 }
77             } )*
78
79             pub fn fold_with<F: Folder>(self, folder: &mut F) -> Self {
80                 use self::Expansion::*;
81                 match self {
82                     OptExpr(expr) => OptExpr(expr.and_then(|expr| folder.fold_opt_expr(expr))),
83                     $($( $kind(ast) => $kind(folder.$fold(ast)), )*)*
84                     $($( $kind(ast) => {
85                         $kind(ast.into_iter().flat_map(|ast| folder.$fold_elt(ast)).collect())
86                     }, )*)*
87                 }
88             }
89
90             pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
91                 match *self {
92                     Expansion::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
93                     Expansion::OptExpr(None) => {}
94                     $($( Expansion::$kind(ref ast) => visitor.$visit(ast), )*)*
95                     $($( Expansion::$kind(ref ast) => for ast in &ast[..] {
96                         visitor.$visit_elt(ast);
97                     }, )*)*
98                 }
99             }
100         }
101
102         impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
103             fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
104                 self.expand(Expansion::OptExpr(Some(expr))).make_opt_expr()
105             }
106             $($(fn $fold(&mut self, node: $ty) -> $ty {
107                 self.expand(Expansion::$kind(node)).$make()
108             })*)*
109             $($(fn $fold_elt(&mut self, node: $ty_elt) -> $ty {
110                 self.expand(Expansion::$kind(SmallVector::one(node))).$make()
111             })*)*
112         }
113
114         impl<'a> MacResult for ::ext::tt::macro_rules::ParserAnyMacro<'a> {
115             $(fn $make(self: Box<::ext::tt::macro_rules::ParserAnyMacro<'a>>) -> Option<$ty> {
116                 Some(self.make(ExpansionKind::$kind).$make())
117             })*
118         }
119     }
120 }
121
122 expansions! {
123     Expr: P<ast::Expr> [], "expression", .make_expr, .fold_expr, .visit_expr;
124     Pat: P<ast::Pat>   [], "pattern",    .make_pat,  .fold_pat,  .visit_pat;
125     Ty: P<ast::Ty>     [], "type",       .make_ty,   .fold_ty,   .visit_ty;
126     Stmts: SmallVector<ast::Stmt> [SmallVector, ast::Stmt],
127         "statement",  .make_stmts,       lift .fold_stmt, lift .visit_stmt;
128     Items: SmallVector<P<ast::Item>> [SmallVector, P<ast::Item>],
129         "item",       .make_items,       lift .fold_item, lift .visit_item;
130     TraitItems: SmallVector<ast::TraitItem> [SmallVector, ast::TraitItem],
131         "trait item", .make_trait_items, lift .fold_trait_item, lift .visit_trait_item;
132     ImplItems: SmallVector<ast::ImplItem> [SmallVector, ast::ImplItem],
133         "impl item",  .make_impl_items,  lift .fold_impl_item,  lift .visit_impl_item;
134 }
135
136 impl ExpansionKind {
137     fn dummy(self, span: Span) -> Expansion {
138         self.make_from(DummyResult::any(span)).unwrap()
139     }
140
141     fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I) -> Expansion {
142         let items = items.into_iter();
143         match self {
144             ExpansionKind::Items =>
145                 Expansion::Items(items.map(Annotatable::expect_item).collect()),
146             ExpansionKind::ImplItems =>
147                 Expansion::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
148             ExpansionKind::TraitItems =>
149                 Expansion::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
150             _ => unreachable!(),
151         }
152     }
153 }
154
155 pub struct Invocation {
156     pub kind: InvocationKind,
157     expansion_kind: ExpansionKind,
158     pub expansion_data: ExpansionData,
159 }
160
161 pub enum InvocationKind {
162     Bang {
163         mac: ast::Mac,
164         ident: Option<Ident>,
165         span: Span,
166     },
167     Attr {
168         attr: Option<ast::Attribute>,
169         traits: Vec<Path>,
170         item: Annotatable,
171     },
172     Derive {
173         path: Path,
174         item: Annotatable,
175     },
176 }
177
178 impl Invocation {
179     fn span(&self) -> Span {
180         match self.kind {
181             InvocationKind::Bang { span, .. } => span,
182             InvocationKind::Attr { attr: Some(ref attr), .. } => attr.span,
183             InvocationKind::Attr { attr: None, .. } => DUMMY_SP,
184             InvocationKind::Derive { ref path, .. } => path.span,
185         }
186     }
187 }
188
189 pub struct MacroExpander<'a, 'b:'a> {
190     pub cx: &'a mut ExtCtxt<'b>,
191     monotonic: bool, // c.f. `cx.monotonic_expander()`
192 }
193
194 impl<'a, 'b> MacroExpander<'a, 'b> {
195     pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
196         MacroExpander { cx: cx, monotonic: monotonic }
197     }
198
199     pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
200         self.cx.crate_root = std_inject::injected_crate_name(&krate);
201         let mut module = ModuleData {
202             mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
203             directory: PathBuf::from(self.cx.codemap().span_to_filename(krate.span)),
204         };
205         module.directory.pop();
206         self.cx.current_expansion.module = Rc::new(module);
207
208         let krate_item = Expansion::Items(SmallVector::one(P(ast::Item {
209             attrs: krate.attrs,
210             span: krate.span,
211             node: ast::ItemKind::Mod(krate.module),
212             ident: keywords::Invalid.ident(),
213             id: ast::DUMMY_NODE_ID,
214             vis: ast::Visibility::Public,
215         })));
216
217         match self.expand(krate_item).make_items().pop().unwrap().unwrap() {
218             ast::Item { attrs, node: ast::ItemKind::Mod(module), .. } => {
219                 krate.attrs = attrs;
220                 krate.module = module;
221             },
222             _ => unreachable!(),
223         };
224
225         krate
226     }
227
228     // Fully expand all the invocations in `expansion`.
229     fn expand(&mut self, expansion: Expansion) -> Expansion {
230         let orig_expansion_data = self.cx.current_expansion.clone();
231         self.cx.current_expansion.depth = 0;
232
233         let (expansion, mut invocations) = self.collect_invocations(expansion, &[]);
234         self.resolve_imports();
235         invocations.reverse();
236
237         let mut expansions = Vec::new();
238         let mut derives = HashMap::new();
239         let mut undetermined_invocations = Vec::new();
240         let (mut progress, mut force) = (false, !self.monotonic);
241         loop {
242             let mut invoc = if let Some(invoc) = invocations.pop() {
243                 invoc
244             } else {
245                 self.resolve_imports();
246                 if undetermined_invocations.is_empty() { break }
247                 invocations = mem::replace(&mut undetermined_invocations, Vec::new());
248                 force = !mem::replace(&mut progress, false);
249                 continue
250             };
251
252             let scope =
253                 if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark };
254             let ext = match self.cx.resolver.resolve_invoc(&mut invoc, scope, force) {
255                 Ok(ext) => Some(ext),
256                 Err(Determinacy::Determined) => None,
257                 Err(Determinacy::Undetermined) => {
258                     undetermined_invocations.push(invoc);
259                     continue
260                 }
261             };
262
263             progress = true;
264             let ExpansionData { depth, mark, .. } = invoc.expansion_data;
265             self.cx.current_expansion = invoc.expansion_data.clone();
266
267             self.cx.current_expansion.mark = scope;
268             // FIXME(jseyfried): Refactor out the following logic
269             let (expansion, new_invocations) = if let Some(ext) = ext {
270                 if let Some(ext) = ext {
271                     let expansion = self.expand_invoc(invoc, ext);
272                     self.collect_invocations(expansion, &[])
273                 } else if let InvocationKind::Attr { attr: None, traits, item } = invoc.kind {
274                     let item = item
275                         .map_attrs(|mut attrs| { attrs.retain(|a| a.path != "derive"); attrs });
276                     let item_with_markers =
277                         add_derived_markers(&mut self.cx, item.span(), &traits, item.clone());
278                     let derives = derives.entry(invoc.expansion_data.mark).or_insert_with(Vec::new);
279
280                     for path in &traits {
281                         let mark = Mark::fresh();
282                         derives.push(mark);
283                         let item = match self.cx.resolver.resolve_macro(
284                                 Mark::root(), path, MacroKind::Derive, false) {
285                             Ok(ext) => match *ext {
286                                 SyntaxExtension::BuiltinDerive(..) => item_with_markers.clone(),
287                                 _ => item.clone(),
288                             },
289                             _ => item.clone(),
290                         };
291                         invocations.push(Invocation {
292                             kind: InvocationKind::Derive { path: path.clone(), item: item },
293                             expansion_kind: invoc.expansion_kind,
294                             expansion_data: ExpansionData {
295                                 mark: mark,
296                                 ..invoc.expansion_data.clone()
297                             },
298                         });
299                     }
300                     let expansion = invoc.expansion_kind
301                         .expect_from_annotatables(::std::iter::once(item_with_markers));
302                     self.collect_invocations(expansion, derives)
303                 } else {
304                     unreachable!()
305                 }
306             } else {
307                 self.collect_invocations(invoc.expansion_kind.dummy(invoc.span()), &[])
308             };
309
310             if expansions.len() < depth {
311                 expansions.push(Vec::new());
312             }
313             expansions[depth - 1].push((mark, expansion));
314             if !self.cx.ecfg.single_step {
315                 invocations.extend(new_invocations.into_iter().rev());
316             }
317         }
318
319         self.cx.current_expansion = orig_expansion_data;
320
321         let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
322         while let Some(expansions) = expansions.pop() {
323             for (mark, expansion) in expansions.into_iter().rev() {
324                 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
325                 placeholder_expander.add(NodeId::placeholder_from_mark(mark), expansion, derives);
326             }
327         }
328
329         expansion.fold_with(&mut placeholder_expander)
330     }
331
332     fn resolve_imports(&mut self) {
333         if self.monotonic {
334             let err_count = self.cx.parse_sess.span_diagnostic.err_count();
335             self.cx.resolver.resolve_imports();
336             self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
337         }
338     }
339
340     fn collect_invocations(&mut self, expansion: Expansion, derives: &[Mark])
341                            -> (Expansion, Vec<Invocation>) {
342         let result = {
343             let mut collector = InvocationCollector {
344                 cfg: StripUnconfigured {
345                     should_test: self.cx.ecfg.should_test,
346                     sess: self.cx.parse_sess,
347                     features: self.cx.ecfg.features,
348                 },
349                 cx: self.cx,
350                 invocations: Vec::new(),
351                 monotonic: self.monotonic,
352             };
353             (expansion.fold_with(&mut collector), collector.invocations)
354         };
355
356         if self.monotonic {
357             let err_count = self.cx.parse_sess.span_diagnostic.err_count();
358             let mark = self.cx.current_expansion.mark;
359             self.cx.resolver.visit_expansion(mark, &result.0, derives);
360             self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
361         }
362
363         result
364     }
365
366     fn expand_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
367         let result = match invoc.kind {
368             InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext),
369             InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext),
370             InvocationKind::Derive { .. } => self.expand_derive_invoc(invoc, ext),
371         };
372
373         if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
374             let info = self.cx.current_expansion.mark.expn_info().unwrap();
375             let suggested_limit = self.cx.ecfg.recursion_limit * 2;
376             let mut err = self.cx.struct_span_fatal(info.call_site,
377                 &format!("recursion limit reached while expanding the macro `{}`",
378                          info.callee.name()));
379             err.help(&format!(
380                 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
381                 suggested_limit));
382             err.emit();
383             panic!(FatalError);
384         }
385
386         result
387     }
388
389     fn expand_attr_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
390         let Invocation { expansion_kind: kind, .. } = invoc;
391         let (attr, item) = match invoc.kind {
392             InvocationKind::Attr { attr, item, .. } => (attr.unwrap(), item),
393             _ => unreachable!(),
394         };
395
396         attr::mark_used(&attr);
397         invoc.expansion_data.mark.set_expn_info(ExpnInfo {
398             call_site: attr.span,
399             callee: NameAndSpan {
400                 format: MacroAttribute(Symbol::intern(&format!("{}", attr.path))),
401                 span: None,
402                 allow_internal_unstable: false,
403             }
404         });
405
406         match *ext {
407             MultiModifier(ref mac) => {
408                 let meta = panictry!(attr.parse_meta(&self.cx.parse_sess));
409                 let item = mac.expand(self.cx, attr.span, &meta, item);
410                 kind.expect_from_annotatables(item)
411             }
412             MultiDecorator(ref mac) => {
413                 let mut items = Vec::new();
414                 let meta = panictry!(attr.parse_meta(&self.cx.parse_sess));
415                 mac.expand(self.cx, attr.span, &meta, &item, &mut |item| items.push(item));
416                 items.push(item);
417                 kind.expect_from_annotatables(items)
418             }
419             SyntaxExtension::AttrProcMacro(ref mac) => {
420                 let item_toks = stream_for_item(&item, &self.cx.parse_sess);
421
422                 let span = Span { ctxt: self.cx.backtrace(), ..attr.span };
423                 let tok_result = mac.expand(self.cx, attr.span, attr.tokens, item_toks);
424                 self.parse_expansion(tok_result, kind, &attr.path, span)
425             }
426             SyntaxExtension::ProcMacroDerive(..) | SyntaxExtension::BuiltinDerive(..) => {
427                 self.cx.span_err(attr.span, &format!("`{}` is a derive mode", attr.path));
428                 kind.dummy(attr.span)
429             }
430             _ => {
431                 let msg = &format!("macro `{}` may not be used in attributes", attr.path);
432                 self.cx.span_err(attr.span, &msg);
433                 kind.dummy(attr.span)
434             }
435         }
436     }
437
438     /// Expand a macro invocation. Returns the result of expansion.
439     fn expand_bang_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
440         let (mark, kind) = (invoc.expansion_data.mark, invoc.expansion_kind);
441         let (mac, ident, span) = match invoc.kind {
442             InvocationKind::Bang { mac, ident, span } => (mac, ident, span),
443             _ => unreachable!(),
444         };
445         let path = &mac.node.path;
446
447         let ident = ident.unwrap_or(keywords::Invalid.ident());
448         let marked_tts = noop_fold_tts(mac.node.stream(), &mut Marker(mark));
449         let opt_expanded = match *ext {
450             NormalTT(ref expandfun, exp_span, allow_internal_unstable) => {
451                 if ident.name != keywords::Invalid.name() {
452                     let msg =
453                         format!("macro {}! expects no ident argument, given '{}'", path, ident);
454                     self.cx.span_err(path.span, &msg);
455                     return kind.dummy(span);
456                 }
457
458                 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
459                     call_site: span,
460                     callee: NameAndSpan {
461                         format: MacroBang(Symbol::intern(&format!("{}", path))),
462                         span: exp_span,
463                         allow_internal_unstable: allow_internal_unstable,
464                     },
465                 });
466
467                 kind.make_from(expandfun.expand(self.cx, span, marked_tts))
468             }
469
470             IdentTT(ref expander, tt_span, allow_internal_unstable) => {
471                 if ident.name == keywords::Invalid.name() {
472                     self.cx.span_err(path.span,
473                                     &format!("macro {}! expects an ident argument", path));
474                     return kind.dummy(span);
475                 };
476
477                 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
478                     call_site: span,
479                     callee: NameAndSpan {
480                         format: MacroBang(Symbol::intern(&format!("{}", path))),
481                         span: tt_span,
482                         allow_internal_unstable: allow_internal_unstable,
483                     }
484                 });
485
486                 let input: Vec<_> = marked_tts.into_trees().collect();
487                 kind.make_from(expander.expand(self.cx, span, ident, input))
488             }
489
490             MultiDecorator(..) | MultiModifier(..) | SyntaxExtension::AttrProcMacro(..) => {
491                 self.cx.span_err(path.span,
492                                  &format!("`{}` can only be used in attributes", path));
493                 return kind.dummy(span);
494             }
495
496             SyntaxExtension::ProcMacroDerive(..) | SyntaxExtension::BuiltinDerive(..) => {
497                 self.cx.span_err(path.span, &format!("`{}` is a derive mode", path));
498                 return kind.dummy(span);
499             }
500
501             SyntaxExtension::ProcMacro(ref expandfun) => {
502                 if ident.name != keywords::Invalid.name() {
503                     let msg =
504                         format!("macro {}! expects no ident argument, given '{}'", path, ident);
505                     self.cx.span_err(path.span, &msg);
506                     return kind.dummy(span);
507                 }
508
509                 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
510                     call_site: span,
511                     callee: NameAndSpan {
512                         format: MacroBang(Symbol::intern(&format!("{}", path))),
513                         // FIXME procedural macros do not have proper span info
514                         // yet, when they do, we should use it here.
515                         span: None,
516                         // FIXME probably want to follow macro_rules macros here.
517                         allow_internal_unstable: false,
518                     },
519                 });
520
521                 let tok_result = expandfun.expand(self.cx, span, marked_tts);
522                 Some(self.parse_expansion(tok_result, kind, path, span))
523             }
524         };
525
526         let expanded = if let Some(expanded) = opt_expanded {
527             expanded
528         } else {
529             let msg = format!("non-{kind} macro in {kind} position: {name}",
530                               name = path.segments[0].identifier.name, kind = kind.name());
531             self.cx.span_err(path.span, &msg);
532             return kind.dummy(span);
533         };
534
535         expanded.fold_with(&mut Marker(mark))
536     }
537
538     /// Expand a derive invocation. Returns the result of expansion.
539     fn expand_derive_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
540         let Invocation { expansion_kind: kind, .. } = invoc;
541         let (path, item) = match invoc.kind {
542             InvocationKind::Derive { path, item } => (path, item),
543             _ => unreachable!(),
544         };
545
546         let pretty_name = Symbol::intern(&format!("derive({})", path));
547         let span = path.span;
548         let attr = ast::Attribute {
549             path: path, tokens: TokenStream::empty(), span: span,
550             // irrelevant:
551             id: ast::AttrId(0), style: ast::AttrStyle::Outer, is_sugared_doc: false,
552         };
553
554         let mut expn_info = ExpnInfo {
555             call_site: span,
556             callee: NameAndSpan {
557                 format: MacroAttribute(pretty_name),
558                 span: None,
559                 allow_internal_unstable: false,
560             }
561         };
562
563         match *ext {
564             SyntaxExtension::ProcMacroDerive(ref ext, _) => {
565                 invoc.expansion_data.mark.set_expn_info(expn_info);
566                 let span = Span { ctxt: self.cx.backtrace(), ..span };
567                 let dummy = ast::MetaItem { // FIXME(jseyfried) avoid this
568                     name: keywords::Invalid.name(),
569                     span: DUMMY_SP,
570                     node: ast::MetaItemKind::Word,
571                 };
572                 kind.expect_from_annotatables(ext.expand(self.cx, span, &dummy, item))
573             }
574             SyntaxExtension::BuiltinDerive(func) => {
575                 expn_info.callee.allow_internal_unstable = true;
576                 invoc.expansion_data.mark.set_expn_info(expn_info);
577                 let span = Span { ctxt: self.cx.backtrace(), ..span };
578                 let mut items = Vec::new();
579                 func(self.cx, span, &attr.meta().unwrap(), &item, &mut |a| items.push(a));
580                 kind.expect_from_annotatables(items)
581             }
582             _ => {
583                 let msg = &format!("macro `{}` may not be used for derive attributes", attr.path);
584                 self.cx.span_err(span, &msg);
585                 kind.dummy(span)
586             }
587         }
588     }
589
590     fn parse_expansion(&mut self, toks: TokenStream, kind: ExpansionKind, path: &Path, span: Span)
591                        -> Expansion {
592         let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
593         let expansion = match parser.parse_expansion(kind, false) {
594             Ok(expansion) => expansion,
595             Err(mut err) => {
596                 err.emit();
597                 return kind.dummy(span);
598             }
599         };
600         parser.ensure_complete_parse(path, kind.name(), span);
601         // FIXME better span info
602         expansion.fold_with(&mut ChangeSpan { span: span })
603     }
604 }
605
606 impl<'a> Parser<'a> {
607     pub fn parse_expansion(&mut self, kind: ExpansionKind, macro_legacy_warnings: bool)
608                            -> PResult<'a, Expansion> {
609         Ok(match kind {
610             ExpansionKind::Items => {
611                 let mut items = SmallVector::new();
612                 while let Some(item) = self.parse_item()? {
613                     items.push(item);
614                 }
615                 Expansion::Items(items)
616             }
617             ExpansionKind::TraitItems => {
618                 let mut items = SmallVector::new();
619                 while self.token != token::Eof {
620                     items.push(self.parse_trait_item(&mut false)?);
621                 }
622                 Expansion::TraitItems(items)
623             }
624             ExpansionKind::ImplItems => {
625                 let mut items = SmallVector::new();
626                 while self.token != token::Eof {
627                     items.push(self.parse_impl_item(&mut false)?);
628                 }
629                 Expansion::ImplItems(items)
630             }
631             ExpansionKind::Stmts => {
632                 let mut stmts = SmallVector::new();
633                 while self.token != token::Eof &&
634                       // won't make progress on a `}`
635                       self.token != token::CloseDelim(token::Brace) {
636                     if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
637                         stmts.push(stmt);
638                     }
639                 }
640                 Expansion::Stmts(stmts)
641             }
642             ExpansionKind::Expr => Expansion::Expr(self.parse_expr()?),
643             ExpansionKind::OptExpr => Expansion::OptExpr(Some(self.parse_expr()?)),
644             ExpansionKind::Ty => Expansion::Ty(self.parse_ty()?),
645             ExpansionKind::Pat => Expansion::Pat(self.parse_pat()?),
646         })
647     }
648
649     pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
650         if self.token != token::Eof {
651             let msg = format!("macro expansion ignores token `{}` and any following",
652                               self.this_token_to_string());
653             let mut err = self.diagnostic().struct_span_err(self.span, &msg);
654             let msg = format!("caused by the macro expansion here; the usage \
655                                of `{}!` is likely invalid in {} context",
656                                macro_path, kind_name);
657             err.span_note(span, &msg).emit();
658         }
659     }
660 }
661
662 struct InvocationCollector<'a, 'b: 'a> {
663     cx: &'a mut ExtCtxt<'b>,
664     cfg: StripUnconfigured<'a>,
665     invocations: Vec<Invocation>,
666     monotonic: bool,
667 }
668
669 macro_rules! fully_configure {
670     ($this:ident, $node:ident, $noop_fold:ident) => {
671         match $noop_fold($node, &mut $this.cfg).pop() {
672             Some(node) => node,
673             None => return SmallVector::new(),
674         }
675     }
676 }
677
678 impl<'a, 'b> InvocationCollector<'a, 'b> {
679     fn collect(&mut self, expansion_kind: ExpansionKind, kind: InvocationKind) -> Expansion {
680         let mark = Mark::fresh();
681         self.invocations.push(Invocation {
682             kind: kind,
683             expansion_kind: expansion_kind,
684             expansion_data: ExpansionData {
685                 mark: mark,
686                 depth: self.cx.current_expansion.depth + 1,
687                 ..self.cx.current_expansion.clone()
688             },
689         });
690         placeholder(expansion_kind, NodeId::placeholder_from_mark(mark))
691     }
692
693     fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: ExpansionKind) -> Expansion {
694         self.collect(kind, InvocationKind::Bang { mac: mac, ident: None, span: span })
695     }
696
697     fn collect_attr(&mut self,
698                     attr: Option<ast::Attribute>,
699                     traits: Vec<Path>,
700                     item: Annotatable,
701                     kind: ExpansionKind)
702                     -> Expansion {
703         if !traits.is_empty() &&
704            (kind == ExpansionKind::TraitItems || kind == ExpansionKind::ImplItems) {
705             self.cx.span_err(traits[0].span, "`derive` can be only be applied to items");
706             return kind.expect_from_annotatables(::std::iter::once(item));
707         }
708         self.collect(kind, InvocationKind::Attr { attr: attr, traits: traits, item: item })
709     }
710
711     // If `item` is an attr invocation, remove and return the macro attribute.
712     fn classify_item<T>(&mut self, mut item: T) -> (Option<ast::Attribute>, Vec<Path>, T)
713         where T: HasAttrs,
714     {
715         let (mut attr, mut traits) = (None, Vec::new());
716
717         item = item.map_attrs(|mut attrs| {
718             if let Some(legacy_attr_invoc) = self.cx.resolver.find_legacy_attr_invoc(&mut attrs) {
719                 attr = Some(legacy_attr_invoc);
720                 return attrs;
721             }
722
723             if self.cx.ecfg.proc_macro_enabled() {
724                 attr = find_attr_invoc(&mut attrs);
725             }
726             traits = collect_derives(&mut self.cx, &mut attrs);
727             attrs
728         });
729
730         (attr, traits, item)
731     }
732
733     fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
734         self.cfg.configure(node)
735     }
736
737     // Detect use of feature-gated or invalid attributes on macro invocations
738     // since they will not be detected after macro expansion.
739     fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
740         let features = self.cx.ecfg.features.unwrap();
741         for attr in attrs.iter() {
742             feature_gate::check_attribute(&attr, &self.cx.parse_sess, features);
743         }
744     }
745 }
746
747 pub fn find_attr_invoc(attrs: &mut Vec<ast::Attribute>) -> Option<ast::Attribute> {
748     for i in 0 .. attrs.len() {
749         if !attr::is_known(&attrs[i]) && !is_builtin_attr(&attrs[i]) {
750              return Some(attrs.remove(i));
751         }
752     }
753
754     None
755 }
756
757 // These are pretty nasty. Ideally, we would keep the tokens around, linked from
758 // the AST. However, we don't so we need to create new ones. Since the item might
759 // have come from a macro expansion (possibly only in part), we can't use the
760 // existing codemap.
761 //
762 // Therefore, we must use the pretty printer (yuck) to turn the AST node into a
763 // string, which we then re-tokenise (double yuck), but first we have to patch
764 // the pretty-printed string on to the end of the existing codemap (infinity-yuck).
765 fn stream_for_item(item: &Annotatable, parse_sess: &ParseSess) -> TokenStream {
766     let text = match *item {
767         Annotatable::Item(ref i) => pprust::item_to_string(i),
768         Annotatable::TraitItem(ref ti) => pprust::trait_item_to_string(ti),
769         Annotatable::ImplItem(ref ii) => pprust::impl_item_to_string(ii),
770     };
771     string_to_stream(text, parse_sess)
772 }
773
774 fn string_to_stream(text: String, parse_sess: &ParseSess) -> TokenStream {
775     let filename = String::from("<macro expansion>");
776     filemap_to_stream(parse_sess, parse_sess.codemap().new_filemap(filename, None, text))
777 }
778
779 impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
780     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
781         let mut expr = self.cfg.configure_expr(expr).unwrap();
782         expr.node = self.cfg.configure_expr_kind(expr.node);
783
784         if let ast::ExprKind::Mac(mac) = expr.node {
785             self.check_attributes(&expr.attrs);
786             self.collect_bang(mac, expr.span, ExpansionKind::Expr).make_expr()
787         } else {
788             P(noop_fold_expr(expr, self))
789         }
790     }
791
792     fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
793         let mut expr = configure!(self, expr).unwrap();
794         expr.node = self.cfg.configure_expr_kind(expr.node);
795
796         if let ast::ExprKind::Mac(mac) = expr.node {
797             self.check_attributes(&expr.attrs);
798             self.collect_bang(mac, expr.span, ExpansionKind::OptExpr).make_opt_expr()
799         } else {
800             Some(P(noop_fold_expr(expr, self)))
801         }
802     }
803
804     fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
805         let pat = self.cfg.configure_pat(pat);
806         match pat.node {
807             PatKind::Mac(_) => {}
808             _ => return noop_fold_pat(pat, self),
809         }
810
811         pat.and_then(|pat| match pat.node {
812             PatKind::Mac(mac) => self.collect_bang(mac, pat.span, ExpansionKind::Pat).make_pat(),
813             _ => unreachable!(),
814         })
815     }
816
817     fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
818         let stmt = match self.cfg.configure_stmt(stmt) {
819             Some(stmt) => stmt,
820             None => return SmallVector::new(),
821         };
822
823         let (mac, style, attrs) = if let StmtKind::Mac(mac) = stmt.node {
824             mac.unwrap()
825         } else {
826             // The placeholder expander gives ids to statements, so we avoid folding the id here.
827             let ast::Stmt { id, node, span } = stmt;
828             return noop_fold_stmt_kind(node, self).into_iter().map(|node| {
829                 ast::Stmt { id: id, node: node, span: span }
830             }).collect()
831         };
832
833         self.check_attributes(&attrs);
834         let mut placeholder = self.collect_bang(mac, stmt.span, ExpansionKind::Stmts).make_stmts();
835
836         // If this is a macro invocation with a semicolon, then apply that
837         // semicolon to the final statement produced by expansion.
838         if style == MacStmtStyle::Semicolon {
839             if let Some(stmt) = placeholder.pop() {
840                 placeholder.push(stmt.add_trailing_semicolon());
841             }
842         }
843
844         placeholder
845     }
846
847     fn fold_block(&mut self, block: P<Block>) -> P<Block> {
848         let old_directory_ownership = self.cx.current_expansion.directory_ownership;
849         self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
850         let result = noop_fold_block(block, self);
851         self.cx.current_expansion.directory_ownership = old_directory_ownership;
852         result
853     }
854
855     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
856         let item = configure!(self, item);
857
858         let (attr, traits, mut item) = self.classify_item(item);
859         if attr.is_some() || !traits.is_empty() {
860             let item = Annotatable::Item(fully_configure!(self, item, noop_fold_item));
861             return self.collect_attr(attr, traits, item, ExpansionKind::Items).make_items();
862         }
863
864         match item.node {
865             ast::ItemKind::Mac(..) => {
866                 self.check_attributes(&item.attrs);
867                 item.and_then(|item| match item.node {
868                     ItemKind::Mac(mac) => {
869                         self.collect(ExpansionKind::Items, InvocationKind::Bang {
870                             mac: mac,
871                             ident: Some(item.ident),
872                             span: item.span,
873                         }).make_items()
874                     }
875                     _ => unreachable!(),
876                 })
877             }
878             ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
879                 if item.ident == keywords::Invalid.ident() {
880                     return noop_fold_item(item, self);
881                 }
882
883                 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
884                 let mut module = (*self.cx.current_expansion.module).clone();
885                 module.mod_path.push(item.ident);
886
887                 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
888                 // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`).
889                 // Thus, if `inner` is the dummy span, we know the module is inline.
890                 let inline_module = item.span.contains(inner) || inner == DUMMY_SP;
891
892                 if inline_module {
893                     if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") {
894                         self.cx.current_expansion.directory_ownership = DirectoryOwnership::Owned;
895                         module.directory.push(&*path.as_str());
896                     } else {
897                         module.directory.push(&*item.ident.name.as_str());
898                     }
899                 } else {
900                     let mut path =
901                         PathBuf::from(self.cx.parse_sess.codemap().span_to_filename(inner));
902                     let directory_ownership = match path.file_name().unwrap().to_str() {
903                         Some("mod.rs") => DirectoryOwnership::Owned,
904                         _ => DirectoryOwnership::UnownedViaMod(false),
905                     };
906                     path.pop();
907                     module.directory = path;
908                     self.cx.current_expansion.directory_ownership = directory_ownership;
909                 }
910
911                 let orig_module =
912                     mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
913                 let result = noop_fold_item(item, self);
914                 self.cx.current_expansion.module = orig_module;
915                 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
916                 return result;
917             }
918             // Ensure that test functions are accessible from the test harness.
919             ast::ItemKind::Fn(..) if self.cx.ecfg.should_test => {
920                 if item.attrs.iter().any(|attr| is_test_or_bench(attr)) {
921                     item = item.map(|mut item| { item.vis = ast::Visibility::Public; item });
922                 }
923                 noop_fold_item(item, self)
924             }
925             _ => noop_fold_item(item, self),
926         }
927     }
928
929     fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
930         let item = configure!(self, item);
931
932         let (attr, traits, item) = self.classify_item(item);
933         if attr.is_some() || !traits.is_empty() {
934             let item =
935                 Annotatable::TraitItem(P(fully_configure!(self, item, noop_fold_trait_item)));
936             return self.collect_attr(attr, traits, item, ExpansionKind::TraitItems)
937                 .make_trait_items()
938         }
939
940         match item.node {
941             ast::TraitItemKind::Macro(mac) => {
942                 let ast::TraitItem { attrs, span, .. } = item;
943                 self.check_attributes(&attrs);
944                 self.collect_bang(mac, span, ExpansionKind::TraitItems).make_trait_items()
945             }
946             _ => fold::noop_fold_trait_item(item, self),
947         }
948     }
949
950     fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
951         let item = configure!(self, item);
952
953         let (attr, traits, item) = self.classify_item(item);
954         if attr.is_some() || !traits.is_empty() {
955             let item = Annotatable::ImplItem(P(fully_configure!(self, item, noop_fold_impl_item)));
956             return self.collect_attr(attr, traits, item, ExpansionKind::ImplItems)
957                 .make_impl_items();
958         }
959
960         match item.node {
961             ast::ImplItemKind::Macro(mac) => {
962                 let ast::ImplItem { attrs, span, .. } = item;
963                 self.check_attributes(&attrs);
964                 self.collect_bang(mac, span, ExpansionKind::ImplItems).make_impl_items()
965             }
966             _ => fold::noop_fold_impl_item(item, self),
967         }
968     }
969
970     fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> {
971         let ty = match ty.node {
972             ast::TyKind::Mac(_) => ty.unwrap(),
973             _ => return fold::noop_fold_ty(ty, self),
974         };
975
976         match ty.node {
977             ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, ExpansionKind::Ty).make_ty(),
978             _ => unreachable!(),
979         }
980     }
981
982     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
983         noop_fold_foreign_mod(self.cfg.configure_foreign_mod(foreign_mod), self)
984     }
985
986     fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
987         match item {
988             ast::ItemKind::MacroDef(..) => item,
989             _ => noop_fold_item_kind(self.cfg.configure_item_kind(item), self),
990         }
991     }
992
993     fn new_id(&mut self, id: ast::NodeId) -> ast::NodeId {
994         if self.monotonic {
995             assert_eq!(id, ast::DUMMY_NODE_ID);
996             self.cx.resolver.next_node_id()
997         } else {
998             id
999         }
1000     }
1001 }
1002
1003 pub struct ExpansionConfig<'feat> {
1004     pub crate_name: String,
1005     pub features: Option<&'feat Features>,
1006     pub recursion_limit: usize,
1007     pub trace_mac: bool,
1008     pub should_test: bool, // If false, strip `#[test]` nodes
1009     pub single_step: bool,
1010     pub keep_macs: bool,
1011 }
1012
1013 macro_rules! feature_tests {
1014     ($( fn $getter:ident = $field:ident, )*) => {
1015         $(
1016             pub fn $getter(&self) -> bool {
1017                 match self.features {
1018                     Some(&Features { $field: true, .. }) => true,
1019                     _ => false,
1020                 }
1021             }
1022         )*
1023     }
1024 }
1025
1026 impl<'feat> ExpansionConfig<'feat> {
1027     pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1028         ExpansionConfig {
1029             crate_name: crate_name,
1030             features: None,
1031             recursion_limit: 64,
1032             trace_mac: false,
1033             should_test: false,
1034             single_step: false,
1035             keep_macs: false,
1036         }
1037     }
1038
1039     feature_tests! {
1040         fn enable_quotes = quote,
1041         fn enable_asm = asm,
1042         fn enable_global_asm = global_asm,
1043         fn enable_log_syntax = log_syntax,
1044         fn enable_concat_idents = concat_idents,
1045         fn enable_trace_macros = trace_macros,
1046         fn enable_allow_internal_unstable = allow_internal_unstable,
1047         fn enable_custom_derive = custom_derive,
1048         fn proc_macro_enabled = proc_macro,
1049     }
1050 }
1051
1052 // A Marker adds the given mark to the syntax context.
1053 struct Marker(Mark);
1054
1055 impl Folder for Marker {
1056     fn fold_ident(&mut self, mut ident: Ident) -> Ident {
1057         ident.ctxt = ident.ctxt.apply_mark(self.0);
1058         ident
1059     }
1060
1061     fn new_span(&mut self, mut span: Span) -> Span {
1062         span.ctxt = span.ctxt.apply_mark(self.0);
1063         span
1064     }
1065
1066     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1067         noop_fold_mac(mac, self)
1068     }
1069 }