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