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