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};
12 use ast::{Name, MacStmtStyle, StmtKind, ItemKind};
13 use attr::{self, HasAttrs};
14 use codemap::{ExpnInfo, NameAndSpan, MacroBang, MacroAttribute};
15 use config::{is_test_or_bench, StripUnconfigured};
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::{self, Span, ExpnId};
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>,
168 traits: Vec<(Symbol, Span)>,
179 fn span(&self) -> Span {
181 InvocationKind::Bang { span, .. } => span,
182 InvocationKind::Attr { attr: Some(ref attr), .. } => attr.span,
183 InvocationKind::Attr { attr: None, .. } => syntax_pos::DUMMY_SP,
184 InvocationKind::Derive { span, .. } => span,
189 pub struct MacroExpander<'a, 'b:'a> {
190 pub cx: &'a mut ExtCtxt<'b>,
191 monotonic: bool, // c.f. `cx.monotonic_expander()`
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 }
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)),
205 module.directory.pop();
206 self.cx.current_expansion.module = Rc::new(module);
208 let krate_item = Expansion::Items(SmallVector::one(P(ast::Item {
211 node: ast::ItemKind::Mod(krate.module),
212 ident: keywords::Invalid.ident(),
213 id: ast::DUMMY_NODE_ID,
214 vis: ast::Visibility::Public,
217 match self.expand(krate_item).make_items().pop().unwrap().unwrap() {
218 ast::Item { attrs, node: ast::ItemKind::Mod(module), .. } => {
220 krate.module = module;
228 // Fully expand all the invocations in `expansion`.
229 fn expand(&mut self, expansion: Expansion) -> Expansion {
230 let orig_expansion_data = self.cx.current_expansion.clone();
231 self.cx.current_expansion.depth = 0;
233 let (expansion, mut invocations) = self.collect_invocations(expansion, &[]);
234 self.resolve_imports();
235 invocations.reverse();
237 let mut expansions = Vec::new();
238 let mut derives = HashMap::new();
239 let mut undetermined_invocations = Vec::new();
240 let (mut progress, mut force) = (false, !self.monotonic);
242 let mut invoc = if let Some(invoc) = invocations.pop() {
245 self.resolve_imports();
246 if undetermined_invocations.is_empty() { break }
247 invocations = mem::replace(&mut undetermined_invocations, Vec::new());
248 force = !mem::replace(&mut progress, false);
253 if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark };
254 let ext = match self.cx.resolver.resolve_invoc(&mut invoc, scope, force) {
255 Ok(ext) => Some(ext),
256 Err(Determinacy::Determined) => None,
257 Err(Determinacy::Undetermined) => {
258 undetermined_invocations.push(invoc);
264 let ExpansionData { depth, mark, .. } = invoc.expansion_data;
265 self.cx.current_expansion = invoc.expansion_data.clone();
267 self.cx.current_expansion.mark = scope;
268 // FIXME(jseyfried): Refactor out the following logic
269 let (expansion, new_invocations) = if let Some(ext) = ext {
270 if let Some(ext) = ext {
271 let expansion = self.expand_invoc(invoc, ext);
272 self.collect_invocations(expansion, &[])
273 } else if let InvocationKind::Attr { attr: None, traits, item } = invoc.kind {
275 .map_attrs(|mut attrs| { attrs.retain(|a| a.name() != "derive"); attrs });
276 let item_with_markers =
277 add_derived_markers(&mut self.cx, &traits, item.clone());
278 let derives = derives.entry(invoc.expansion_data.mark).or_insert_with(Vec::new);
280 for &(name, span) in &traits {
281 let mark = Mark::fresh();
283 let path = ast::Path::from_ident(span, Ident::with_empty_ctxt(name));
284 let item = match self.cx.resolver.resolve_macro(
285 Mark::root(), &path, MacroKind::Derive, false) {
286 Ok(ext) => match *ext {
287 SyntaxExtension::BuiltinDerive(..) => item_with_markers.clone(),
292 invocations.push(Invocation {
293 kind: InvocationKind::Derive { name: name, span: span, item: item },
294 expansion_kind: invoc.expansion_kind,
295 expansion_data: ExpansionData {
297 ..invoc.expansion_data.clone()
301 let expansion = invoc.expansion_kind
302 .expect_from_annotatables(::std::iter::once(item_with_markers));
303 self.collect_invocations(expansion, derives)
308 self.collect_invocations(invoc.expansion_kind.dummy(invoc.span()), &[])
311 if expansions.len() < depth {
312 expansions.push(Vec::new());
314 expansions[depth - 1].push((mark, expansion));
315 if !self.cx.ecfg.single_step {
316 invocations.extend(new_invocations.into_iter().rev());
320 self.cx.current_expansion = orig_expansion_data;
322 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
323 while let Some(expansions) = expansions.pop() {
324 for (mark, expansion) in expansions.into_iter().rev() {
325 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
326 placeholder_expander.add(mark.as_placeholder_id(), expansion, derives);
330 expansion.fold_with(&mut placeholder_expander)
333 fn resolve_imports(&mut self) {
335 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
336 self.cx.resolver.resolve_imports();
337 self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
341 fn collect_invocations(&mut self, expansion: Expansion, derives: &[Mark])
342 -> (Expansion, Vec<Invocation>) {
344 let mut collector = InvocationCollector {
345 cfg: StripUnconfigured {
346 should_test: self.cx.ecfg.should_test,
347 sess: self.cx.parse_sess,
348 features: self.cx.ecfg.features,
351 invocations: Vec::new(),
352 monotonic: self.monotonic,
354 (expansion.fold_with(&mut collector), collector.invocations)
358 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
359 let mark = self.cx.current_expansion.mark;
360 self.cx.resolver.visit_expansion(mark, &result.0, derives);
361 self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
367 fn expand_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
369 InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext),
370 InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext),
371 InvocationKind::Derive { .. } => self.expand_derive_invoc(invoc, ext),
375 fn expand_attr_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
376 let Invocation { expansion_kind: kind, .. } = invoc;
377 let (attr, item) = match invoc.kind {
378 InvocationKind::Attr { attr, item, .. } => (attr.unwrap(), item),
382 attr::mark_used(&attr);
383 let name = attr.name();
384 self.cx.bt_push(ExpnInfo {
385 call_site: attr.span,
386 callee: NameAndSpan {
387 format: MacroAttribute(name),
388 span: Some(attr.span),
389 allow_internal_unstable: false,
394 MultiModifier(ref mac) => {
395 let item = mac.expand(self.cx, attr.span, &attr.value, item);
396 kind.expect_from_annotatables(item)
398 MultiDecorator(ref mac) => {
399 let mut items = Vec::new();
400 mac.expand(self.cx, attr.span, &attr.value, &item,
401 &mut |item| items.push(item));
403 kind.expect_from_annotatables(items)
405 SyntaxExtension::AttrProcMacro(ref mac) => {
406 let attr_toks = stream_for_attr_args(&attr, &self.cx.parse_sess);
407 let item_toks = stream_for_item(&item, &self.cx.parse_sess);
410 expn_id: self.cx.codemap().record_expansion(ExpnInfo {
411 call_site: attr.span,
412 callee: NameAndSpan {
413 format: MacroAttribute(name),
415 allow_internal_unstable: false,
421 let tok_result = mac.expand(self.cx, attr.span, attr_toks, item_toks);
422 self.parse_expansion(tok_result, kind, name, span)
424 SyntaxExtension::ProcMacroDerive(..) | SyntaxExtension::BuiltinDerive(..) => {
425 self.cx.span_err(attr.span, &format!("`{}` is a derive mode", name));
426 kind.dummy(attr.span)
429 let msg = &format!("macro `{}` may not be used in attributes", name);
430 self.cx.span_err(attr.span, &msg);
431 kind.dummy(attr.span)
436 /// Expand a macro invocation. Returns the result of expansion.
437 fn expand_bang_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
438 let (mark, kind) = (invoc.expansion_data.mark, invoc.expansion_kind);
439 let (mac, ident, span) = match invoc.kind {
440 InvocationKind::Bang { mac, ident, span } => (mac, ident, span),
443 let path = &mac.node.path;
445 let extname = path.segments.last().unwrap().identifier.name;
446 let ident = ident.unwrap_or(keywords::Invalid.ident());
448 noop_fold_tts(mac.node.stream(), &mut Marker { mark: mark, expn_id: None });
449 let opt_expanded = match *ext {
450 NormalTT(ref expandfun, exp_span, allow_internal_unstable) => {
451 if ident.name != keywords::Invalid.name() {
453 format!("macro {}! expects no ident argument, given '{}'", extname, ident);
454 self.cx.span_err(path.span, &msg);
455 return kind.dummy(span);
458 self.cx.bt_push(ExpnInfo {
460 callee: NameAndSpan {
461 format: MacroBang(extname),
463 allow_internal_unstable: allow_internal_unstable,
467 kind.make_from(expandfun.expand(self.cx, span, marked_tts))
470 IdentTT(ref expander, tt_span, allow_internal_unstable) => {
471 if ident.name == keywords::Invalid.name() {
472 self.cx.span_err(path.span,
473 &format!("macro {}! expects an ident argument", extname));
474 return kind.dummy(span);
477 self.cx.bt_push(ExpnInfo {
479 callee: NameAndSpan {
480 format: MacroBang(extname),
482 allow_internal_unstable: allow_internal_unstable,
486 let input: Vec<_> = marked_tts.into_trees().collect();
487 kind.make_from(expander.expand(self.cx, span, ident, input))
490 MultiDecorator(..) | MultiModifier(..) | SyntaxExtension::AttrProcMacro(..) => {
491 self.cx.span_err(path.span,
492 &format!("`{}` can only be used in attributes", extname));
493 return kind.dummy(span);
496 SyntaxExtension::ProcMacroDerive(..) | SyntaxExtension::BuiltinDerive(..) => {
497 self.cx.span_err(path.span, &format!("`{}` is a derive mode", extname));
498 return kind.dummy(span);
501 SyntaxExtension::ProcMacro(ref expandfun) => {
502 if ident.name != keywords::Invalid.name() {
504 format!("macro {}! expects no ident argument, given '{}'", extname, ident);
505 self.cx.span_err(path.span, &msg);
506 return kind.dummy(span);
509 self.cx.bt_push(ExpnInfo {
511 callee: NameAndSpan {
512 format: MacroBang(extname),
513 // FIXME procedural macros do not have proper span info
514 // yet, when they do, we should use it here.
516 // FIXME probably want to follow macro_rules macros here.
517 allow_internal_unstable: false,
521 let tok_result = expandfun.expand(self.cx, span, marked_tts);
522 Some(self.parse_expansion(tok_result, kind, extname, span))
526 let expanded = if let Some(expanded) = opt_expanded {
529 let msg = format!("non-{kind} macro in {kind} position: {name}",
530 name = path.segments[0].identifier.name, kind = kind.name());
531 self.cx.span_err(path.span, &msg);
532 return kind.dummy(span);
535 expanded.fold_with(&mut Marker {
537 expn_id: Some(self.cx.backtrace()),
541 /// Expand a derive invocation. Returns the result of expansion.
542 fn expand_derive_invoc(&mut self, invoc: Invocation, ext: Rc<SyntaxExtension>) -> Expansion {
543 let Invocation { expansion_kind: kind, .. } = invoc;
544 let (name, span, item) = match invoc.kind {
545 InvocationKind::Derive { name, span, item } => (name, span, item),
549 let mitem = ast::MetaItem { name: name, span: span, node: ast::MetaItemKind::Word };
550 let pretty_name = Symbol::intern(&format!("derive({})", name));
552 self.cx.bt_push(ExpnInfo {
554 callee: NameAndSpan {
555 format: MacroAttribute(pretty_name),
557 allow_internal_unstable: false,
562 SyntaxExtension::ProcMacroDerive(ref ext, _) => {
564 expn_id: self.cx.codemap().record_expansion(ExpnInfo {
566 callee: NameAndSpan {
567 format: MacroAttribute(pretty_name),
569 allow_internal_unstable: false,
574 return kind.expect_from_annotatables(ext.expand(self.cx, span, &mitem, item));
576 SyntaxExtension::BuiltinDerive(func) => {
578 expn_id: self.cx.codemap().record_expansion(ExpnInfo {
580 callee: NameAndSpan {
581 format: MacroAttribute(pretty_name),
583 allow_internal_unstable: true,
588 let mut items = Vec::new();
589 func(self.cx, span, &mitem, &item, &mut |a| {
592 return kind.expect_from_annotatables(items);
595 let msg = &format!("macro `{}` may not be used for derive attributes", name);
596 self.cx.span_err(span, &msg);
602 fn parse_expansion(&mut self, toks: TokenStream, kind: ExpansionKind, name: Name, span: Span)
604 let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
605 let expansion = match parser.parse_expansion(kind, false) {
606 Ok(expansion) => expansion,
609 return kind.dummy(span);
612 parser.ensure_complete_parse(name, kind.name(), span);
613 // FIXME better span info
614 expansion.fold_with(&mut ChangeSpan { span: span })
618 impl<'a> Parser<'a> {
619 pub fn parse_expansion(&mut self, kind: ExpansionKind, macro_legacy_warnings: bool)
620 -> PResult<'a, Expansion> {
622 ExpansionKind::Items => {
623 let mut items = SmallVector::new();
624 while let Some(item) = self.parse_item()? {
627 Expansion::Items(items)
629 ExpansionKind::TraitItems => {
630 let mut items = SmallVector::new();
631 while self.token != token::Eof {
632 items.push(self.parse_trait_item()?);
634 Expansion::TraitItems(items)
636 ExpansionKind::ImplItems => {
637 let mut items = SmallVector::new();
638 while self.token != token::Eof {
639 items.push(self.parse_impl_item()?);
641 Expansion::ImplItems(items)
643 ExpansionKind::Stmts => {
644 let mut stmts = SmallVector::new();
645 while self.token != token::Eof &&
646 // won't make progress on a `}`
647 self.token != token::CloseDelim(token::Brace) {
648 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
652 Expansion::Stmts(stmts)
654 ExpansionKind::Expr => Expansion::Expr(self.parse_expr()?),
655 ExpansionKind::OptExpr => Expansion::OptExpr(Some(self.parse_expr()?)),
656 ExpansionKind::Ty => Expansion::Ty(self.parse_ty_no_plus()?),
657 ExpansionKind::Pat => Expansion::Pat(self.parse_pat()?),
661 pub fn ensure_complete_parse(&mut self, macro_name: ast::Name, kind_name: &str, span: Span) {
662 if self.token != token::Eof {
663 let msg = format!("macro expansion ignores token `{}` and any following",
664 self.this_token_to_string());
665 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
666 let msg = format!("caused by the macro expansion here; the usage \
667 of `{}!` is likely invalid in {} context",
668 macro_name, kind_name);
669 err.span_note(span, &msg).emit();
674 struct InvocationCollector<'a, 'b: 'a> {
675 cx: &'a mut ExtCtxt<'b>,
676 cfg: StripUnconfigured<'a>,
677 invocations: Vec<Invocation>,
681 macro_rules! fully_configure {
682 ($this:ident, $node:ident, $noop_fold:ident) => {
683 match $noop_fold($node, &mut $this.cfg).pop() {
685 None => return SmallVector::new(),
690 impl<'a, 'b> InvocationCollector<'a, 'b> {
691 fn collect(&mut self, expansion_kind: ExpansionKind, kind: InvocationKind) -> Expansion {
692 let mark = Mark::fresh();
693 self.invocations.push(Invocation {
695 expansion_kind: expansion_kind,
696 expansion_data: ExpansionData {
698 depth: self.cx.current_expansion.depth + 1,
699 ..self.cx.current_expansion.clone()
702 placeholder(expansion_kind, mark.as_placeholder_id())
705 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: ExpansionKind) -> Expansion {
706 self.collect(kind, InvocationKind::Bang { mac: mac, ident: None, span: span })
709 fn collect_attr(&mut self,
710 attr: Option<ast::Attribute>,
711 traits: Vec<(Symbol, Span)>,
715 if !traits.is_empty() &&
716 (kind == ExpansionKind::TraitItems || kind == ExpansionKind::ImplItems) {
717 self.cx.span_err(traits[0].1, "`derive` can be only be applied to items");
718 return kind.expect_from_annotatables(::std::iter::once(item));
720 self.collect(kind, InvocationKind::Attr { attr: attr, traits: traits, item: item })
723 // If `item` is an attr invocation, remove and return the macro attribute.
724 fn classify_item<T>(&mut self, mut item: T) -> (Option<ast::Attribute>, Vec<(Symbol, Span)>, T)
727 let (mut attr, mut traits) = (None, Vec::new());
729 item = item.map_attrs(|mut attrs| {
730 if let Some(legacy_attr_invoc) = self.cx.resolver.find_legacy_attr_invoc(&mut attrs) {
731 attr = Some(legacy_attr_invoc);
735 if self.cx.ecfg.proc_macro_enabled() {
736 attr = find_attr_invoc(&mut attrs);
738 traits = collect_derives(&mut self.cx, &mut attrs);
745 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
746 self.cfg.configure(node)
749 // Detect use of feature-gated or invalid attributes on macro invocations
750 // since they will not be detected after macro expansion.
751 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
752 let codemap = &self.cx.parse_sess.codemap();
753 let features = self.cx.ecfg.features.unwrap();
754 for attr in attrs.iter() {
755 feature_gate::check_attribute(&attr, &self.cx.parse_sess, codemap, features);
760 pub fn find_attr_invoc(attrs: &mut Vec<ast::Attribute>) -> Option<ast::Attribute> {
761 for i in 0 .. attrs.len() {
762 if !attr::is_known(&attrs[i]) && !is_builtin_attr(&attrs[i]) {
763 return Some(attrs.remove(i));
770 // These are pretty nasty. Ideally, we would keep the tokens around, linked from
771 // the AST. However, we don't so we need to create new ones. Since the item might
772 // have come from a macro expansion (possibly only in part), we can't use the
775 // Therefore, we must use the pretty printer (yuck) to turn the AST node into a
776 // string, which we then re-tokenise (double yuck), but first we have to patch
777 // the pretty-printed string on to the end of the existing codemap (infinity-yuck).
778 fn stream_for_item(item: &Annotatable, parse_sess: &ParseSess) -> TokenStream {
779 let text = match *item {
780 Annotatable::Item(ref i) => pprust::item_to_string(i),
781 Annotatable::TraitItem(ref ti) => pprust::trait_item_to_string(ti),
782 Annotatable::ImplItem(ref ii) => pprust::impl_item_to_string(ii),
784 string_to_stream(text, parse_sess)
787 fn stream_for_attr_args(attr: &ast::Attribute, parse_sess: &ParseSess) -> TokenStream {
788 use ast::MetaItemKind::*;
789 use print::pp::Breaks;
790 use print::pprust::PrintState;
792 let token_string = match attr.value.node {
793 // For `#[foo]`, an empty token
794 Word => return TokenStream::empty(),
795 // For `#[foo(bar, baz)]`, returns `(bar, baz)`
796 List(ref items) => pprust::to_string(|s| {
798 s.commasep(Breaks::Consistent,
800 |s, i| s.print_meta_list_item(&i))?;
803 // For `#[foo = "bar"]`, returns `= "bar"`
804 NameValue(ref lit) => pprust::to_string(|s| {
810 string_to_stream(token_string, parse_sess)
813 fn string_to_stream(text: String, parse_sess: &ParseSess) -> TokenStream {
814 let filename = String::from("<macro expansion>");
815 filemap_to_stream(parse_sess, parse_sess.codemap().new_filemap(filename, None, text))
818 impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
819 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
820 let mut expr = self.cfg.configure_expr(expr).unwrap();
821 expr.node = self.cfg.configure_expr_kind(expr.node);
823 if let ast::ExprKind::Mac(mac) = expr.node {
824 self.check_attributes(&expr.attrs);
825 self.collect_bang(mac, expr.span, ExpansionKind::Expr).make_expr()
827 P(noop_fold_expr(expr, self))
831 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
832 let mut expr = configure!(self, expr).unwrap();
833 expr.node = self.cfg.configure_expr_kind(expr.node);
835 if let ast::ExprKind::Mac(mac) = expr.node {
836 self.check_attributes(&expr.attrs);
837 self.collect_bang(mac, expr.span, ExpansionKind::OptExpr).make_opt_expr()
839 Some(P(noop_fold_expr(expr, self)))
843 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
844 let pat = self.cfg.configure_pat(pat);
846 PatKind::Mac(_) => {}
847 _ => return noop_fold_pat(pat, self),
850 pat.and_then(|pat| match pat.node {
851 PatKind::Mac(mac) => self.collect_bang(mac, pat.span, ExpansionKind::Pat).make_pat(),
856 fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
857 let stmt = match self.cfg.configure_stmt(stmt) {
859 None => return SmallVector::new(),
862 let (mac, style, attrs) = if let StmtKind::Mac(mac) = stmt.node {
865 // The placeholder expander gives ids to statements, so we avoid folding the id here.
866 let ast::Stmt { id, node, span } = stmt;
867 return noop_fold_stmt_kind(node, self).into_iter().map(|node| {
868 ast::Stmt { id: id, node: node, span: span }
872 self.check_attributes(&attrs);
873 let mut placeholder = self.collect_bang(mac, stmt.span, ExpansionKind::Stmts).make_stmts();
875 // If this is a macro invocation with a semicolon, then apply that
876 // semicolon to the final statement produced by expansion.
877 if style == MacStmtStyle::Semicolon {
878 if let Some(stmt) = placeholder.pop() {
879 placeholder.push(stmt.add_trailing_semicolon());
886 fn fold_block(&mut self, block: P<Block>) -> P<Block> {
887 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
888 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
889 let result = noop_fold_block(block, self);
890 self.cx.current_expansion.directory_ownership = old_directory_ownership;
894 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
895 let item = configure!(self, item);
897 let (attr, traits, mut item) = self.classify_item(item);
898 if attr.is_some() || !traits.is_empty() {
899 let item = Annotatable::Item(fully_configure!(self, item, noop_fold_item));
900 return self.collect_attr(attr, traits, item, ExpansionKind::Items).make_items();
904 ast::ItemKind::Mac(..) => {
905 self.check_attributes(&item.attrs);
906 item.and_then(|item| match item.node {
907 ItemKind::Mac(mac) => {
908 self.collect(ExpansionKind::Items, InvocationKind::Bang {
910 ident: Some(item.ident),
917 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
918 if item.ident == keywords::Invalid.ident() {
919 return noop_fold_item(item, self);
922 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
923 let mut module = (*self.cx.current_expansion.module).clone();
924 module.mod_path.push(item.ident);
926 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
927 // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`).
928 // Thus, if `inner` is the dummy span, we know the module is inline.
929 let inline_module = item.span.contains(inner) || inner == syntax_pos::DUMMY_SP;
932 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") {
933 self.cx.current_expansion.directory_ownership = DirectoryOwnership::Owned;
934 module.directory.push(&*path.as_str());
936 module.directory.push(&*item.ident.name.as_str());
940 PathBuf::from(self.cx.parse_sess.codemap().span_to_filename(inner));
941 let directory_ownership = match path.file_name().unwrap().to_str() {
942 Some("mod.rs") => DirectoryOwnership::Owned,
943 _ => DirectoryOwnership::UnownedViaMod(false),
946 module.directory = path;
947 self.cx.current_expansion.directory_ownership = directory_ownership;
951 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
952 let result = noop_fold_item(item, self);
953 self.cx.current_expansion.module = orig_module;
954 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
957 // Ensure that test functions are accessible from the test harness.
958 ast::ItemKind::Fn(..) if self.cx.ecfg.should_test => {
959 if item.attrs.iter().any(|attr| is_test_or_bench(attr)) {
960 item = item.map(|mut item| { item.vis = ast::Visibility::Public; item });
962 noop_fold_item(item, self)
964 _ => noop_fold_item(item, self),
968 fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
969 let item = configure!(self, item);
971 let (attr, traits, item) = self.classify_item(item);
972 if attr.is_some() || !traits.is_empty() {
974 Annotatable::TraitItem(P(fully_configure!(self, item, noop_fold_trait_item)));
975 return self.collect_attr(attr, traits, item, ExpansionKind::TraitItems)
980 ast::TraitItemKind::Macro(mac) => {
981 let ast::TraitItem { attrs, span, .. } = item;
982 self.check_attributes(&attrs);
983 self.collect_bang(mac, span, ExpansionKind::TraitItems).make_trait_items()
985 _ => fold::noop_fold_trait_item(item, self),
989 fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
990 let item = configure!(self, item);
992 let (attr, traits, item) = self.classify_item(item);
993 if attr.is_some() || !traits.is_empty() {
994 let item = Annotatable::ImplItem(P(fully_configure!(self, item, noop_fold_impl_item)));
995 return self.collect_attr(attr, traits, item, ExpansionKind::ImplItems)
1000 ast::ImplItemKind::Macro(mac) => {
1001 let ast::ImplItem { attrs, span, .. } = item;
1002 self.check_attributes(&attrs);
1003 self.collect_bang(mac, span, ExpansionKind::ImplItems).make_impl_items()
1005 _ => fold::noop_fold_impl_item(item, self),
1009 fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> {
1010 let ty = match ty.node {
1011 ast::TyKind::Mac(_) => ty.unwrap(),
1012 _ => return fold::noop_fold_ty(ty, self),
1016 ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, ExpansionKind::Ty).make_ty(),
1017 _ => unreachable!(),
1021 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
1022 noop_fold_foreign_mod(self.cfg.configure_foreign_mod(foreign_mod), self)
1025 fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
1027 ast::ItemKind::MacroDef(..) => item,
1028 _ => noop_fold_item_kind(self.cfg.configure_item_kind(item), self),
1032 fn new_id(&mut self, id: ast::NodeId) -> ast::NodeId {
1034 assert_eq!(id, ast::DUMMY_NODE_ID);
1035 self.cx.resolver.next_node_id()
1042 pub struct ExpansionConfig<'feat> {
1043 pub crate_name: String,
1044 pub features: Option<&'feat Features>,
1045 pub recursion_limit: usize,
1046 pub trace_mac: bool,
1047 pub should_test: bool, // If false, strip `#[test]` nodes
1048 pub single_step: bool,
1049 pub keep_macs: bool,
1052 macro_rules! feature_tests {
1053 ($( fn $getter:ident = $field:ident, )*) => {
1055 pub fn $getter(&self) -> bool {
1056 match self.features {
1057 Some(&Features { $field: true, .. }) => true,
1065 impl<'feat> ExpansionConfig<'feat> {
1066 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1068 crate_name: crate_name,
1070 recursion_limit: 64,
1079 fn enable_quotes = quote,
1080 fn enable_asm = asm,
1081 fn enable_log_syntax = log_syntax,
1082 fn enable_concat_idents = concat_idents,
1083 fn enable_trace_macros = trace_macros,
1084 fn enable_allow_internal_unstable = allow_internal_unstable,
1085 fn enable_custom_derive = custom_derive,
1086 fn proc_macro_enabled = proc_macro,
1090 // A Marker adds the given mark to the syntax context and
1091 // sets spans' `expn_id` to the given expn_id (unless it is `None`).
1092 struct Marker { mark: Mark, expn_id: Option<ExpnId> }
1094 impl Folder for Marker {
1095 fn fold_ident(&mut self, mut ident: Ident) -> Ident {
1096 ident.ctxt = ident.ctxt.apply_mark(self.mark);
1099 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1100 noop_fold_mac(mac, self)
1103 fn new_span(&mut self, mut span: Span) -> Span {
1104 if let Some(expn_id) = self.expn_id {
1105 span.expn_id = expn_id;