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