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