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.
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.
11 use ast::{self, Block, Ident, PatKind, Path};
12 use ast::{MacStmtStyle, StmtKind, ItemKind};
13 use attr::{self, HasAttrs};
14 use codemap::{ExpnInfo, NameAndSpan, MacroBang, MacroAttribute};
15 use config::{is_test_or_bench, StripUnconfigured};
17 use ext::derive::{add_derived_markers, collect_derives};
18 use ext::hygiene::Mark;
19 use ext::placeholders::{placeholder, PlaceholderExpander};
20 use feature_gate::{self, Features, is_builtin_attr};
23 use parse::{filemap_to_stream, ParseSess, DirectoryOwnership, PResult, token};
24 use parse::parser::Parser;
30 use syntax_pos::{Span, ExpnId, DUMMY_SP};
31 use tokenstream::TokenStream;
32 use util::small_vector::SmallVector;
35 use std::collections::HashMap;
37 use std::path::PathBuf;
40 macro_rules! expansions {
41 ($($kind:ident: $ty:ty [$($vec:ident, $ty_elt:ty)*], $kind_name:expr, .$make:ident,
42 $(.$fold:ident)* $(lift .$fold_elt:ident)*,
43 $(.$visit:ident)* $(lift .$visit_elt:ident)*;)*) => {
44 #[derive(Copy, Clone, PartialEq, Eq)]
45 pub enum ExpansionKind { OptExpr, $( $kind, )* }
46 pub enum Expansion { OptExpr(Option<P<ast::Expr>>), $( $kind($ty), )* }
49 pub fn name(self) -> &'static str {
51 ExpansionKind::OptExpr => "expression",
52 $( ExpansionKind::$kind => $kind_name, )*
56 fn make_from<'a>(self, result: Box<MacResult + 'a>) -> Option<Expansion> {
58 ExpansionKind::OptExpr => result.make_expr().map(Some).map(Expansion::OptExpr),
59 $( ExpansionKind::$kind => result.$make().map(Expansion::$kind), )*
65 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
67 Expansion::OptExpr(expr) => expr,
68 _ => panic!("Expansion::make_* called on the wrong kind of expansion"),
71 $( pub fn $make(self) -> $ty {
73 Expansion::$kind(ast) => ast,
74 _ => panic!("Expansion::make_* called on the wrong kind of expansion"),
78 pub fn fold_with<F: Folder>(self, folder: &mut F) -> Self {
79 use self::Expansion::*;
81 OptExpr(expr) => OptExpr(expr.and_then(|expr| folder.fold_opt_expr(expr))),
82 $($( $kind(ast) => $kind(folder.$fold(ast)), )*)*
84 $kind(ast.into_iter().flat_map(|ast| folder.$fold_elt(ast)).collect())
89 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
91 Expansion::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
92 Expansion::OptExpr(None) => {}
93 $($( Expansion::$kind(ref ast) => visitor.$visit(ast), )*)*
94 $($( Expansion::$kind(ref ast) => for ast in &ast[..] {
95 visitor.$visit_elt(ast);
101 impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
102 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
103 self.expand(Expansion::OptExpr(Some(expr))).make_opt_expr()
105 $($(fn $fold(&mut self, node: $ty) -> $ty {
106 self.expand(Expansion::$kind(node)).$make()
108 $($(fn $fold_elt(&mut self, node: $ty_elt) -> $ty {
109 self.expand(Expansion::$kind(SmallVector::one(node))).$make()
113 impl<'a> MacResult for ::ext::tt::macro_rules::ParserAnyMacro<'a> {
114 $(fn $make(self: Box<::ext::tt::macro_rules::ParserAnyMacro<'a>>) -> Option<$ty> {
115 Some(self.make(ExpansionKind::$kind).$make())
122 Expr: P<ast::Expr> [], "expression", .make_expr, .fold_expr, .visit_expr;
123 Pat: P<ast::Pat> [], "pattern", .make_pat, .fold_pat, .visit_pat;
124 Ty: P<ast::Ty> [], "type", .make_ty, .fold_ty, .visit_ty;
125 Stmts: SmallVector<ast::Stmt> [SmallVector, ast::Stmt],
126 "statement", .make_stmts, lift .fold_stmt, lift .visit_stmt;
127 Items: SmallVector<P<ast::Item>> [SmallVector, P<ast::Item>],
128 "item", .make_items, lift .fold_item, lift .visit_item;
129 TraitItems: SmallVector<ast::TraitItem> [SmallVector, ast::TraitItem],
130 "trait item", .make_trait_items, lift .fold_trait_item, lift .visit_trait_item;
131 ImplItems: SmallVector<ast::ImplItem> [SmallVector, ast::ImplItem],
132 "impl item", .make_impl_items, lift .fold_impl_item, lift .visit_impl_item;
136 fn dummy(self, span: Span) -> Expansion {
137 self.make_from(DummyResult::any(span)).unwrap()
140 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I) -> Expansion {
141 let items = items.into_iter();
143 ExpansionKind::Items =>
144 Expansion::Items(items.map(Annotatable::expect_item).collect()),
145 ExpansionKind::ImplItems =>
146 Expansion::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
147 ExpansionKind::TraitItems =>
148 Expansion::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
154 pub struct Invocation {
155 pub kind: InvocationKind,
156 expansion_kind: ExpansionKind,
157 pub expansion_data: ExpansionData,
160 pub enum InvocationKind {
163 ident: Option<Ident>,
167 attr: Option<ast::Attribute>,
178 fn span(&self) -> Span {
180 InvocationKind::Bang { span, .. } => span,
181 InvocationKind::Attr { attr: Some(ref attr), .. } => attr.span,
182 InvocationKind::Attr { attr: None, .. } => DUMMY_SP,
183 InvocationKind::Derive { ref path, .. } => path.span,
188 pub struct MacroExpander<'a, 'b:'a> {
189 pub cx: &'a mut ExtCtxt<'b>,
190 monotonic: bool, // c.f. `cx.monotonic_expander()`
193 impl<'a, 'b> MacroExpander<'a, 'b> {
194 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
195 MacroExpander { cx: cx, monotonic: monotonic }
198 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
199 self.cx.crate_root = std_inject::injected_crate_name(&krate);
200 let mut module = ModuleData {
201 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
202 directory: PathBuf::from(self.cx.codemap().span_to_filename(krate.span)),
204 module.directory.pop();
205 self.cx.current_expansion.module = Rc::new(module);
207 let krate_item = Expansion::Items(SmallVector::one(P(ast::Item {
210 node: ast::ItemKind::Mod(krate.module),
211 ident: keywords::Invalid.ident(),
212 id: ast::DUMMY_NODE_ID,
213 vis: ast::Visibility::Public,
216 match self.expand(krate_item).make_items().pop().unwrap().unwrap() {
217 ast::Item { attrs, node: ast::ItemKind::Mod(module), .. } => {
219 krate.module = module;
227 // Fully expand all the invocations in `expansion`.
228 fn expand(&mut self, expansion: Expansion) -> Expansion {
229 let orig_expansion_data = self.cx.current_expansion.clone();
230 self.cx.current_expansion.depth = 0;
232 let (expansion, mut invocations) = self.collect_invocations(expansion, &[]);
233 self.resolve_imports();
234 invocations.reverse();
236 let mut expansions = Vec::new();
237 let mut derives = HashMap::new();
238 let mut undetermined_invocations = Vec::new();
239 let (mut progress, mut force) = (false, !self.monotonic);
241 let mut invoc = if let Some(invoc) = invocations.pop() {
244 self.resolve_imports();
245 if undetermined_invocations.is_empty() { break }
246 invocations = mem::replace(&mut undetermined_invocations, Vec::new());
247 force = !mem::replace(&mut progress, false);
252 if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark };
253 let ext = match self.cx.resolver.resolve_invoc(&mut invoc, scope, force) {
254 Ok(ext) => Some(ext),
255 Err(Determinacy::Determined) => None,
256 Err(Determinacy::Undetermined) => {
257 undetermined_invocations.push(invoc);
263 let ExpansionData { depth, mark, .. } = invoc.expansion_data;
264 self.cx.current_expansion = invoc.expansion_data.clone();
266 self.cx.current_expansion.mark = scope;
267 // FIXME(jseyfried): Refactor out the following logic
268 let (expansion, new_invocations) = if let Some(ext) = ext {
269 if let Some(ext) = ext {
270 let expansion = self.expand_invoc(invoc, ext);
271 self.collect_invocations(expansion, &[])
272 } else if let InvocationKind::Attr { attr: None, traits, item } = invoc.kind {
274 .map_attrs(|mut attrs| { attrs.retain(|a| a.path != "derive"); attrs });
275 let item_with_markers =
276 add_derived_markers(&mut self.cx, &traits, item.clone());
277 let derives = derives.entry(invoc.expansion_data.mark).or_insert_with(Vec::new);
279 for path in &traits {
280 let mark = Mark::fresh();
282 let item = match self.cx.resolver.resolve_macro(
283 Mark::root(), path, MacroKind::Derive, false) {
284 Ok(ext) => match *ext {
285 SyntaxExtension::BuiltinDerive(..) => item_with_markers.clone(),
290 invocations.push(Invocation {
291 kind: InvocationKind::Derive { path: path.clone(), item: item },
292 expansion_kind: invoc.expansion_kind,
293 expansion_data: ExpansionData {
295 ..invoc.expansion_data.clone()
299 let expansion = invoc.expansion_kind
300 .expect_from_annotatables(::std::iter::once(item_with_markers));
301 self.collect_invocations(expansion, derives)
306 self.collect_invocations(invoc.expansion_kind.dummy(invoc.span()), &[])
309 if expansions.len() < depth {
310 expansions.push(Vec::new());
312 expansions[depth - 1].push((mark, expansion));
313 if !self.cx.ecfg.single_step {
314 invocations.extend(new_invocations.into_iter().rev());
318 self.cx.current_expansion = orig_expansion_data;
320 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
321 while let Some(expansions) = expansions.pop() {
322 for (mark, expansion) in expansions.into_iter().rev() {
323 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
324 placeholder_expander.add(mark.as_placeholder_id(), expansion, derives);
328 expansion.fold_with(&mut placeholder_expander)
331 fn resolve_imports(&mut self) {
333 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
334 self.cx.resolver.resolve_imports();
335 self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
339 fn collect_invocations(&mut self, expansion: Expansion, derives: &[Mark])
340 -> (Expansion, Vec<Invocation>) {
342 let mut collector = InvocationCollector {
343 cfg: StripUnconfigured {
344 should_test: self.cx.ecfg.should_test,
345 sess: self.cx.parse_sess,
346 features: self.cx.ecfg.features,
349 invocations: Vec::new(),
350 monotonic: self.monotonic,
352 (expansion.fold_with(&mut collector), collector.invocations)
356 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
357 let mark = self.cx.current_expansion.mark;
358 self.cx.resolver.visit_expansion(mark, &result.0, derives);
359 self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
365 fn expand_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
367 InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext),
368 InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext),
369 InvocationKind::Derive { .. } => self.expand_derive_invoc(invoc, ext),
373 fn expand_attr_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
374 let Invocation { expansion_kind: kind, .. } = invoc;
375 let (attr, item) = match invoc.kind {
376 InvocationKind::Attr { attr, item, .. } => (attr.unwrap(), item),
380 attr::mark_used(&attr);
381 self.cx.bt_push(ExpnInfo {
382 call_site: attr.span,
383 callee: NameAndSpan {
384 format: MacroAttribute(Symbol::intern(&format!("{}", attr.path))),
385 span: Some(attr.span),
386 allow_internal_unstable: false,
391 MultiModifier(ref mac) => {
392 let meta = panictry!(attr.parse_meta(&self.cx.parse_sess));
393 let item = mac.expand(self.cx, attr.span, &meta, item);
394 kind.expect_from_annotatables(item)
396 MultiDecorator(ref mac) => {
397 let mut items = Vec::new();
398 let meta = panictry!(attr.parse_meta(&self.cx.parse_sess));
399 mac.expand(self.cx, attr.span, &meta, &item, &mut |item| items.push(item));
401 kind.expect_from_annotatables(items)
403 SyntaxExtension::AttrProcMacro(ref mac) => {
404 let item_toks = stream_for_item(&item, &self.cx.parse_sess);
407 expn_id: self.cx.codemap().record_expansion(ExpnInfo {
408 call_site: attr.span,
409 callee: NameAndSpan {
410 format: MacroAttribute(Symbol::intern(&format!("{}", attr.path))),
412 allow_internal_unstable: false,
418 let tok_result = mac.expand(self.cx, attr.span, attr.tokens.clone(), item_toks);
419 self.parse_expansion(tok_result, kind, &attr.path, span)
421 SyntaxExtension::ProcMacroDerive(..) | SyntaxExtension::BuiltinDerive(..) => {
422 self.cx.span_err(attr.span, &format!("`{}` is a derive mode", attr.path));
423 kind.dummy(attr.span)
426 let msg = &format!("macro `{}` may not be used in attributes", attr.path);
427 self.cx.span_err(attr.span, &msg);
428 kind.dummy(attr.span)
433 /// Expand a macro invocation. Returns the result of expansion.
434 fn expand_bang_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
435 let (mark, kind) = (invoc.expansion_data.mark, invoc.expansion_kind);
436 let (mac, ident, span) = match invoc.kind {
437 InvocationKind::Bang { mac, ident, span } => (mac, ident, span),
440 let path = &mac.node.path;
442 let ident = ident.unwrap_or(keywords::Invalid.ident());
444 noop_fold_tts(mac.node.stream(), &mut Marker { mark: mark, expn_id: None });
445 let opt_expanded = match *ext {
446 NormalTT(ref expandfun, exp_span, allow_internal_unstable) => {
447 if ident.name != keywords::Invalid.name() {
449 format!("macro {}! expects no ident argument, given '{}'", path, ident);
450 self.cx.span_err(path.span, &msg);
451 return kind.dummy(span);
454 self.cx.bt_push(ExpnInfo {
456 callee: NameAndSpan {
457 format: MacroBang(Symbol::intern(&format!("{}", path))),
459 allow_internal_unstable: allow_internal_unstable,
463 kind.make_from(expandfun.expand(self.cx, span, marked_tts))
466 IdentTT(ref expander, tt_span, allow_internal_unstable) => {
467 if ident.name == keywords::Invalid.name() {
468 self.cx.span_err(path.span,
469 &format!("macro {}! expects an ident argument", path));
470 return kind.dummy(span);
473 self.cx.bt_push(ExpnInfo {
475 callee: NameAndSpan {
476 format: MacroBang(Symbol::intern(&format!("{}", path))),
478 allow_internal_unstable: allow_internal_unstable,
482 let input: Vec<_> = marked_tts.into_trees().collect();
483 kind.make_from(expander.expand(self.cx, span, ident, input))
486 MultiDecorator(..) | MultiModifier(..) | SyntaxExtension::AttrProcMacro(..) => {
487 self.cx.span_err(path.span,
488 &format!("`{}` can only be used in attributes", path));
489 return kind.dummy(span);
492 SyntaxExtension::ProcMacroDerive(..) | SyntaxExtension::BuiltinDerive(..) => {
493 self.cx.span_err(path.span, &format!("`{}` is a derive mode", path));
494 return kind.dummy(span);
497 SyntaxExtension::ProcMacro(ref expandfun) => {
498 if ident.name != keywords::Invalid.name() {
500 format!("macro {}! expects no ident argument, given '{}'", path, ident);
501 self.cx.span_err(path.span, &msg);
502 return kind.dummy(span);
505 self.cx.bt_push(ExpnInfo {
507 callee: NameAndSpan {
508 format: MacroBang(Symbol::intern(&format!("{}", path))),
509 // FIXME procedural macros do not have proper span info
510 // yet, when they do, we should use it here.
512 // FIXME probably want to follow macro_rules macros here.
513 allow_internal_unstable: false,
517 let tok_result = expandfun.expand(self.cx, span, marked_tts);
518 Some(self.parse_expansion(tok_result, kind, path, span))
522 let expanded = if let Some(expanded) = opt_expanded {
525 let msg = format!("non-{kind} macro in {kind} position: {name}",
526 name = path.segments[0].identifier.name, kind = kind.name());
527 self.cx.span_err(path.span, &msg);
528 return kind.dummy(span);
531 expanded.fold_with(&mut Marker {
533 expn_id: Some(self.cx.backtrace()),
537 /// Expand a derive invocation. Returns the result of expansion.
538 fn expand_derive_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
539 let Invocation { expansion_kind: kind, .. } = invoc;
540 let (path, item) = match invoc.kind {
541 InvocationKind::Derive { path, item } => (path, item),
545 let pretty_name = Symbol::intern(&format!("derive({})", path));
546 let span = path.span;
547 let attr = ast::Attribute {
548 path: path, tokens: TokenStream::empty(), span: span,
550 id: ast::AttrId(0), style: ast::AttrStyle::Outer, is_sugared_doc: false,
553 self.cx.bt_push(ExpnInfo {
555 callee: NameAndSpan {
556 format: MacroAttribute(pretty_name),
558 allow_internal_unstable: false,
563 SyntaxExtension::ProcMacroDerive(ref ext, _) => {
565 expn_id: self.cx.codemap().record_expansion(ExpnInfo {
567 callee: NameAndSpan {
568 format: MacroAttribute(pretty_name),
570 allow_internal_unstable: false,
575 let dummy = ast::MetaItem { // FIXME(jseyfried) avoid this
576 name: keywords::Invalid.name(),
578 node: ast::MetaItemKind::Word,
580 return kind.expect_from_annotatables(ext.expand(self.cx, span, &dummy, item));
582 SyntaxExtension::BuiltinDerive(func) => {
584 expn_id: self.cx.codemap().record_expansion(ExpnInfo {
586 callee: NameAndSpan {
587 format: MacroAttribute(pretty_name),
589 allow_internal_unstable: true,
594 let mut items = Vec::new();
595 func(self.cx, span, &attr.meta().unwrap(), &item, &mut |a| items.push(a));
596 return kind.expect_from_annotatables(items);
599 let msg = &format!("macro `{}` may not be used for derive attributes", attr.path);
600 self.cx.span_err(span, &msg);
606 fn parse_expansion(&mut self, toks: TokenStream, kind: ExpansionKind, path: &Path, span: Span)
608 let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
609 let expansion = match parser.parse_expansion(kind, false) {
610 Ok(expansion) => expansion,
613 return kind.dummy(span);
616 parser.ensure_complete_parse(path, kind.name(), span);
617 // FIXME better span info
618 expansion.fold_with(&mut ChangeSpan { span: span })
622 impl<'a> Parser<'a> {
623 pub fn parse_expansion(&mut self, kind: ExpansionKind, macro_legacy_warnings: bool)
624 -> PResult<'a, Expansion> {
626 ExpansionKind::Items => {
627 let mut items = SmallVector::new();
628 while let Some(item) = self.parse_item()? {
631 Expansion::Items(items)
633 ExpansionKind::TraitItems => {
634 let mut items = SmallVector::new();
635 while self.token != token::Eof {
636 items.push(self.parse_trait_item()?);
638 Expansion::TraitItems(items)
640 ExpansionKind::ImplItems => {
641 let mut items = SmallVector::new();
642 while self.token != token::Eof {
643 items.push(self.parse_impl_item()?);
645 Expansion::ImplItems(items)
647 ExpansionKind::Stmts => {
648 let mut stmts = SmallVector::new();
649 while self.token != token::Eof &&
650 // won't make progress on a `}`
651 self.token != token::CloseDelim(token::Brace) {
652 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
656 Expansion::Stmts(stmts)
658 ExpansionKind::Expr => Expansion::Expr(self.parse_expr()?),
659 ExpansionKind::OptExpr => Expansion::OptExpr(Some(self.parse_expr()?)),
660 ExpansionKind::Ty => Expansion::Ty(self.parse_ty_no_plus()?),
661 ExpansionKind::Pat => Expansion::Pat(self.parse_pat()?),
665 pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
666 if self.token != token::Eof {
667 let msg = format!("macro expansion ignores token `{}` and any following",
668 self.this_token_to_string());
669 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
670 let msg = format!("caused by the macro expansion here; the usage \
671 of `{}!` is likely invalid in {} context",
672 macro_path, kind_name);
673 err.span_note(span, &msg).emit();
678 struct InvocationCollector<'a, 'b: 'a> {
679 cx: &'a mut ExtCtxt<'b>,
680 cfg: StripUnconfigured<'a>,
681 invocations: Vec<Invocation>,
685 macro_rules! fully_configure {
686 ($this:ident, $node:ident, $noop_fold:ident) => {
687 match $noop_fold($node, &mut $this.cfg).pop() {
689 None => return SmallVector::new(),
694 impl<'a, 'b> InvocationCollector<'a, 'b> {
695 fn collect(&mut self, expansion_kind: ExpansionKind, kind: InvocationKind) -> Expansion {
696 let mark = Mark::fresh();
697 self.invocations.push(Invocation {
699 expansion_kind: expansion_kind,
700 expansion_data: ExpansionData {
702 depth: self.cx.current_expansion.depth + 1,
703 ..self.cx.current_expansion.clone()
706 placeholder(expansion_kind, mark.as_placeholder_id())
709 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: ExpansionKind) -> Expansion {
710 self.collect(kind, InvocationKind::Bang { mac: mac, ident: None, span: span })
713 fn collect_attr(&mut self,
714 attr: Option<ast::Attribute>,
719 if !traits.is_empty() &&
720 (kind == ExpansionKind::TraitItems || kind == ExpansionKind::ImplItems) {
721 self.cx.span_err(traits[0].span, "`derive` can be only be applied to items");
722 return kind.expect_from_annotatables(::std::iter::once(item));
724 self.collect(kind, InvocationKind::Attr { attr: attr, traits: traits, item: item })
727 // If `item` is an attr invocation, remove and return the macro attribute.
728 fn classify_item<T>(&mut self, mut item: T) -> (Option<ast::Attribute>, Vec<Path>, T)
731 let (mut attr, mut traits) = (None, Vec::new());
733 item = item.map_attrs(|mut attrs| {
734 if let Some(legacy_attr_invoc) = self.cx.resolver.find_legacy_attr_invoc(&mut attrs) {
735 attr = Some(legacy_attr_invoc);
739 if self.cx.ecfg.proc_macro_enabled() {
740 attr = find_attr_invoc(&mut attrs);
742 traits = collect_derives(&mut self.cx, &mut attrs);
749 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
750 self.cfg.configure(node)
753 // Detect use of feature-gated or invalid attributes on macro invocations
754 // since they will not be detected after macro expansion.
755 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
756 let codemap = &self.cx.parse_sess.codemap();
757 let features = self.cx.ecfg.features.unwrap();
758 for attr in attrs.iter() {
759 feature_gate::check_attribute(&attr, &self.cx.parse_sess, codemap, features);
764 pub fn find_attr_invoc(attrs: &mut Vec<ast::Attribute>) -> Option<ast::Attribute> {
765 for i in 0 .. attrs.len() {
766 if !attr::is_known(&attrs[i]) && !is_builtin_attr(&attrs[i]) {
767 return Some(attrs.remove(i));
774 // These are pretty nasty. Ideally, we would keep the tokens around, linked from
775 // the AST. However, we don't so we need to create new ones. Since the item might
776 // have come from a macro expansion (possibly only in part), we can't use the
779 // Therefore, we must use the pretty printer (yuck) to turn the AST node into a
780 // string, which we then re-tokenise (double yuck), but first we have to patch
781 // the pretty-printed string on to the end of the existing codemap (infinity-yuck).
782 fn stream_for_item(item: &Annotatable, parse_sess: &ParseSess) -> TokenStream {
783 let text = match *item {
784 Annotatable::Item(ref i) => pprust::item_to_string(i),
785 Annotatable::TraitItem(ref ti) => pprust::trait_item_to_string(ti),
786 Annotatable::ImplItem(ref ii) => pprust::impl_item_to_string(ii),
788 string_to_stream(text, parse_sess)
791 fn string_to_stream(text: String, parse_sess: &ParseSess) -> TokenStream {
792 let filename = String::from("<macro expansion>");
793 filemap_to_stream(parse_sess, parse_sess.codemap().new_filemap(filename, None, text))
796 impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
797 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
798 let mut expr = self.cfg.configure_expr(expr).unwrap();
799 expr.node = self.cfg.configure_expr_kind(expr.node);
801 if let ast::ExprKind::Mac(mac) = expr.node {
802 self.check_attributes(&expr.attrs);
803 self.collect_bang(mac, expr.span, ExpansionKind::Expr).make_expr()
805 P(noop_fold_expr(expr, self))
809 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
810 let mut expr = configure!(self, expr).unwrap();
811 expr.node = self.cfg.configure_expr_kind(expr.node);
813 if let ast::ExprKind::Mac(mac) = expr.node {
814 self.check_attributes(&expr.attrs);
815 self.collect_bang(mac, expr.span, ExpansionKind::OptExpr).make_opt_expr()
817 Some(P(noop_fold_expr(expr, self)))
821 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
822 let pat = self.cfg.configure_pat(pat);
824 PatKind::Mac(_) => {}
825 _ => return noop_fold_pat(pat, self),
828 pat.and_then(|pat| match pat.node {
829 PatKind::Mac(mac) => self.collect_bang(mac, pat.span, ExpansionKind::Pat).make_pat(),
834 fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
835 let stmt = match self.cfg.configure_stmt(stmt) {
837 None => return SmallVector::new(),
840 let (mac, style, attrs) = if let StmtKind::Mac(mac) = stmt.node {
843 // The placeholder expander gives ids to statements, so we avoid folding the id here.
844 let ast::Stmt { id, node, span } = stmt;
845 return noop_fold_stmt_kind(node, self).into_iter().map(|node| {
846 ast::Stmt { id: id, node: node, span: span }
850 self.check_attributes(&attrs);
851 let mut placeholder = self.collect_bang(mac, stmt.span, ExpansionKind::Stmts).make_stmts();
853 // If this is a macro invocation with a semicolon, then apply that
854 // semicolon to the final statement produced by expansion.
855 if style == MacStmtStyle::Semicolon {
856 if let Some(stmt) = placeholder.pop() {
857 placeholder.push(stmt.add_trailing_semicolon());
864 fn fold_block(&mut self, block: P<Block>) -> P<Block> {
865 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
866 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
867 let result = noop_fold_block(block, self);
868 self.cx.current_expansion.directory_ownership = old_directory_ownership;
872 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
873 let item = configure!(self, item);
875 let (attr, traits, mut item) = self.classify_item(item);
876 if attr.is_some() || !traits.is_empty() {
877 let item = Annotatable::Item(fully_configure!(self, item, noop_fold_item));
878 return self.collect_attr(attr, traits, item, ExpansionKind::Items).make_items();
882 ast::ItemKind::Mac(..) => {
883 self.check_attributes(&item.attrs);
884 item.and_then(|item| match item.node {
885 ItemKind::Mac(mac) => {
886 self.collect(ExpansionKind::Items, InvocationKind::Bang {
888 ident: Some(item.ident),
895 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
896 if item.ident == keywords::Invalid.ident() {
897 return noop_fold_item(item, self);
900 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
901 let mut module = (*self.cx.current_expansion.module).clone();
902 module.mod_path.push(item.ident);
904 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
905 // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`).
906 // Thus, if `inner` is the dummy span, we know the module is inline.
907 let inline_module = item.span.contains(inner) || inner == DUMMY_SP;
910 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") {
911 self.cx.current_expansion.directory_ownership = DirectoryOwnership::Owned;
912 module.directory.push(&*path.as_str());
914 module.directory.push(&*item.ident.name.as_str());
918 PathBuf::from(self.cx.parse_sess.codemap().span_to_filename(inner));
919 let directory_ownership = match path.file_name().unwrap().to_str() {
920 Some("mod.rs") => DirectoryOwnership::Owned,
921 _ => DirectoryOwnership::UnownedViaMod(false),
924 module.directory = path;
925 self.cx.current_expansion.directory_ownership = directory_ownership;
929 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
930 let result = noop_fold_item(item, self);
931 self.cx.current_expansion.module = orig_module;
932 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
935 // Ensure that test functions are accessible from the test harness.
936 ast::ItemKind::Fn(..) if self.cx.ecfg.should_test => {
937 if item.attrs.iter().any(|attr| is_test_or_bench(attr)) {
938 item = item.map(|mut item| { item.vis = ast::Visibility::Public; item });
940 noop_fold_item(item, self)
942 _ => noop_fold_item(item, self),
946 fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
947 let item = configure!(self, item);
949 let (attr, traits, item) = self.classify_item(item);
950 if attr.is_some() || !traits.is_empty() {
952 Annotatable::TraitItem(P(fully_configure!(self, item, noop_fold_trait_item)));
953 return self.collect_attr(attr, traits, item, ExpansionKind::TraitItems)
958 ast::TraitItemKind::Macro(mac) => {
959 let ast::TraitItem { attrs, span, .. } = item;
960 self.check_attributes(&attrs);
961 self.collect_bang(mac, span, ExpansionKind::TraitItems).make_trait_items()
963 _ => fold::noop_fold_trait_item(item, self),
967 fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
968 let item = configure!(self, item);
970 let (attr, traits, item) = self.classify_item(item);
971 if attr.is_some() || !traits.is_empty() {
972 let item = Annotatable::ImplItem(P(fully_configure!(self, item, noop_fold_impl_item)));
973 return self.collect_attr(attr, traits, item, ExpansionKind::ImplItems)
978 ast::ImplItemKind::Macro(mac) => {
979 let ast::ImplItem { attrs, span, .. } = item;
980 self.check_attributes(&attrs);
981 self.collect_bang(mac, span, ExpansionKind::ImplItems).make_impl_items()
983 _ => fold::noop_fold_impl_item(item, self),
987 fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> {
988 let ty = match ty.node {
989 ast::TyKind::Mac(_) => ty.unwrap(),
990 _ => return fold::noop_fold_ty(ty, self),
994 ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, ExpansionKind::Ty).make_ty(),
999 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
1000 noop_fold_foreign_mod(self.cfg.configure_foreign_mod(foreign_mod), self)
1003 fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
1005 ast::ItemKind::MacroDef(..) => item,
1006 _ => noop_fold_item_kind(self.cfg.configure_item_kind(item), self),
1010 fn new_id(&mut self, id: ast::NodeId) -> ast::NodeId {
1012 assert_eq!(id, ast::DUMMY_NODE_ID);
1013 self.cx.resolver.next_node_id()
1020 pub struct ExpansionConfig<'feat> {
1021 pub crate_name: String,
1022 pub features: Option<&'feat Features>,
1023 pub recursion_limit: usize,
1024 pub trace_mac: bool,
1025 pub should_test: bool, // If false, strip `#[test]` nodes
1026 pub single_step: bool,
1027 pub keep_macs: bool,
1030 macro_rules! feature_tests {
1031 ($( fn $getter:ident = $field:ident, )*) => {
1033 pub fn $getter(&self) -> bool {
1034 match self.features {
1035 Some(&Features { $field: true, .. }) => true,
1043 impl<'feat> ExpansionConfig<'feat> {
1044 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1046 crate_name: crate_name,
1048 recursion_limit: 64,
1057 fn enable_quotes = quote,
1058 fn enable_asm = asm,
1059 fn enable_log_syntax = log_syntax,
1060 fn enable_concat_idents = concat_idents,
1061 fn enable_trace_macros = trace_macros,
1062 fn enable_allow_internal_unstable = allow_internal_unstable,
1063 fn enable_custom_derive = custom_derive,
1064 fn proc_macro_enabled = proc_macro,
1068 // A Marker adds the given mark to the syntax context and
1069 // sets spans' `expn_id` to the given expn_id (unless it is `None`).
1070 struct Marker { mark: Mark, expn_id: Option<ExpnId> }
1072 impl Folder for Marker {
1073 fn fold_ident(&mut self, mut ident: Ident) -> Ident {
1074 ident.ctxt = ident.ctxt.apply_mark(self.mark);
1077 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1078 noop_fold_mac(mac, self)
1081 fn new_span(&mut self, mut span: Span) -> Span {
1082 if let Some(expn_id) = self.expn_id {
1083 span.expn_id = expn_id;