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, NodeId, PatKind, Path};
12 use ast::{MacStmtStyle, StmtKind, ItemKind};
13 use attr::{self, HasAttrs};
14 use codemap::{ExpnInfo, NameAndSpan, MacroBang, MacroAttribute, dummy_spanned, respan};
15 use config::{is_test_or_bench, StripUnconfigured};
16 use errors::FatalError;
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, GateIssue, is_builtin_attr, emit_feature_err};
24 use parse::{DirectoryOwnership, PResult};
25 use parse::token::{self, Token};
26 use parse::parser::Parser;
30 use syntax_pos::{Span, DUMMY_SP, FileName};
31 use syntax_pos::hygiene::ExpnFormat;
32 use tokenstream::{TokenStream, TokenTree};
33 use util::small_vector::SmallVector;
36 use std::collections::HashMap;
41 use std::path::PathBuf;
43 macro_rules! expansions {
44 ($($kind:ident: $ty:ty [$($vec:ident, $ty_elt:ty)*], $kind_name:expr, .$make:ident,
45 $(.$fold:ident)* $(lift .$fold_elt:ident)*,
46 $(.$visit:ident)* $(lift .$visit_elt:ident)*;)*) => {
47 #[derive(Copy, Clone, PartialEq, Eq)]
48 pub enum ExpansionKind { OptExpr, $( $kind, )* }
49 pub enum Expansion { OptExpr(Option<P<ast::Expr>>), $( $kind($ty), )* }
52 pub fn name(self) -> &'static str {
54 ExpansionKind::OptExpr => "expression",
55 $( ExpansionKind::$kind => $kind_name, )*
59 fn make_from<'a>(self, result: Box<MacResult + 'a>) -> Option<Expansion> {
61 ExpansionKind::OptExpr => result.make_expr().map(Some).map(Expansion::OptExpr),
62 $( ExpansionKind::$kind => result.$make().map(Expansion::$kind), )*
68 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
70 Expansion::OptExpr(expr) => expr,
71 _ => panic!("Expansion::make_* called on the wrong kind of expansion"),
74 $( pub fn $make(self) -> $ty {
76 Expansion::$kind(ast) => ast,
77 _ => panic!("Expansion::make_* called on the wrong kind of expansion"),
81 pub fn fold_with<F: Folder>(self, folder: &mut F) -> Self {
82 use self::Expansion::*;
84 OptExpr(expr) => OptExpr(expr.and_then(|expr| folder.fold_opt_expr(expr))),
85 $($( $kind(ast) => $kind(folder.$fold(ast)), )*)*
87 $kind(ast.into_iter().flat_map(|ast| folder.$fold_elt(ast)).collect())
92 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
94 Expansion::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
95 Expansion::OptExpr(None) => {}
96 $($( Expansion::$kind(ref ast) => visitor.$visit(ast), )*)*
97 $($( Expansion::$kind(ref ast) => for ast in &ast[..] {
98 visitor.$visit_elt(ast);
104 impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
105 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
106 self.expand(Expansion::OptExpr(Some(expr))).make_opt_expr()
108 $($(fn $fold(&mut self, node: $ty) -> $ty {
109 self.expand(Expansion::$kind(node)).$make()
111 $($(fn $fold_elt(&mut self, node: $ty_elt) -> $ty {
112 self.expand(Expansion::$kind(SmallVector::one(node))).$make()
116 impl<'a> MacResult for ::ext::tt::macro_rules::ParserAnyMacro<'a> {
117 $(fn $make(self: Box<::ext::tt::macro_rules::ParserAnyMacro<'a>>) -> Option<$ty> {
118 Some(self.make(ExpansionKind::$kind).$make())
125 Expr: P<ast::Expr> [], "expression", .make_expr, .fold_expr, .visit_expr;
126 Pat: P<ast::Pat> [], "pattern", .make_pat, .fold_pat, .visit_pat;
127 Ty: P<ast::Ty> [], "type", .make_ty, .fold_ty, .visit_ty;
128 Stmts: SmallVector<ast::Stmt> [SmallVector, ast::Stmt],
129 "statement", .make_stmts, lift .fold_stmt, lift .visit_stmt;
130 Items: SmallVector<P<ast::Item>> [SmallVector, P<ast::Item>],
131 "item", .make_items, lift .fold_item, lift .visit_item;
132 TraitItems: SmallVector<ast::TraitItem> [SmallVector, ast::TraitItem],
133 "trait item", .make_trait_items, lift .fold_trait_item, lift .visit_trait_item;
134 ImplItems: SmallVector<ast::ImplItem> [SmallVector, ast::ImplItem],
135 "impl item", .make_impl_items, lift .fold_impl_item, lift .visit_impl_item;
136 ForeignItems: SmallVector<ast::ForeignItem> [SmallVector, ast::ForeignItem],
137 "foreign item", .make_foreign_items, lift .fold_foreign_item, lift .visit_foreign_item;
141 fn dummy(self, span: Span) -> Option<Expansion> {
142 self.make_from(DummyResult::any(span))
145 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I) -> Expansion {
146 let items = items.into_iter();
148 ExpansionKind::Items =>
149 Expansion::Items(items.map(Annotatable::expect_item).collect()),
150 ExpansionKind::ImplItems =>
151 Expansion::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
152 ExpansionKind::TraitItems =>
153 Expansion::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
154 ExpansionKind::ForeignItems =>
155 Expansion::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
161 fn macro_bang_format(path: &ast::Path) -> ExpnFormat {
162 // We don't want to format a path using pretty-printing,
163 // `format!("{}", path)`, because that tries to insert
164 // line-breaks and is slow.
165 let mut path_str = String::with_capacity(64);
166 for (i, segment) in path.segments.iter().enumerate() {
168 path_str.push_str("::");
171 if segment.ident.name != keywords::CrateRoot.name() &&
172 segment.ident.name != keywords::DollarCrate.name()
174 path_str.push_str(&segment.ident.name.as_str())
178 MacroBang(Symbol::intern(&path_str))
181 pub struct Invocation {
182 pub kind: InvocationKind,
183 expansion_kind: ExpansionKind,
184 pub expansion_data: ExpansionData,
187 pub enum InvocationKind {
190 ident: Option<Ident>,
194 attr: Option<ast::Attribute>,
205 fn span(&self) -> Span {
207 InvocationKind::Bang { span, .. } => span,
208 InvocationKind::Attr { attr: Some(ref attr), .. } => attr.span,
209 InvocationKind::Attr { attr: None, .. } => DUMMY_SP,
210 InvocationKind::Derive { ref path, .. } => path.span,
215 pub struct MacroExpander<'a, 'b:'a> {
216 pub cx: &'a mut ExtCtxt<'b>,
217 monotonic: bool, // c.f. `cx.monotonic_expander()`
220 impl<'a, 'b> MacroExpander<'a, 'b> {
221 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
222 MacroExpander { cx: cx, monotonic: monotonic }
225 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
226 let mut module = ModuleData {
227 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
228 directory: match self.cx.codemap().span_to_unmapped_path(krate.span) {
229 FileName::Real(path) => path,
230 other => PathBuf::from(other.to_string()),
233 module.directory.pop();
234 self.cx.root_path = module.directory.clone();
235 self.cx.current_expansion.module = Rc::new(module);
236 self.cx.current_expansion.crate_span = Some(krate.span);
238 let orig_mod_span = krate.module.inner;
240 let krate_item = Expansion::Items(SmallVector::one(P(ast::Item {
243 node: ast::ItemKind::Mod(krate.module),
244 ident: keywords::Invalid.ident(),
245 id: ast::DUMMY_NODE_ID,
246 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
250 match self.expand(krate_item).make_items().pop().map(P::into_inner) {
251 Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
253 krate.module = module;
256 // Resolution failed so we return an empty expansion
257 krate.attrs = vec![];
258 krate.module = ast::Mod {
259 inner: orig_mod_span,
265 self.cx.trace_macros_diag();
269 // Fully expand all the invocations in `expansion`.
270 fn expand(&mut self, expansion: Expansion) -> Expansion {
271 let orig_expansion_data = self.cx.current_expansion.clone();
272 self.cx.current_expansion.depth = 0;
274 let (expansion, mut invocations) = self.collect_invocations(expansion, &[]);
275 self.resolve_imports();
276 invocations.reverse();
278 let mut expansions = Vec::new();
279 let mut derives = HashMap::new();
280 let mut undetermined_invocations = Vec::new();
281 let (mut progress, mut force) = (false, !self.monotonic);
283 let mut invoc = if let Some(invoc) = invocations.pop() {
286 self.resolve_imports();
287 if undetermined_invocations.is_empty() { break }
288 invocations = mem::replace(&mut undetermined_invocations, Vec::new());
289 force = !mem::replace(&mut progress, false);
294 if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark };
295 let ext = match self.cx.resolver.resolve_invoc(&mut invoc, scope, force) {
296 Ok(ext) => Some(ext),
297 Err(Determinacy::Determined) => None,
298 Err(Determinacy::Undetermined) => {
299 undetermined_invocations.push(invoc);
305 let ExpansionData { depth, mark, .. } = invoc.expansion_data;
306 self.cx.current_expansion = invoc.expansion_data.clone();
308 self.cx.current_expansion.mark = scope;
309 // FIXME(jseyfried): Refactor out the following logic
310 let (expansion, new_invocations) = if let Some(ext) = ext {
311 if let Some(ext) = ext {
312 let dummy = invoc.expansion_kind.dummy(invoc.span()).unwrap();
313 let expansion = self.expand_invoc(invoc, &*ext).unwrap_or(dummy);
314 self.collect_invocations(expansion, &[])
315 } else if let InvocationKind::Attr { attr: None, traits, item } = invoc.kind {
316 if !item.derive_allowed() {
317 let attr = attr::find_by_name(item.attrs(), "derive")
318 .expect("`derive` attribute should exist");
319 let span = attr.span;
320 let mut err = self.cx.mut_span_err(span,
321 "`derive` may only be applied to \
322 structs, enums and unions");
323 if let ast::AttrStyle::Inner = attr.style {
324 let trait_list = traits.iter()
325 .map(|t| format!("{}", t)).collect::<Vec<_>>();
326 let suggestion = format!("#[derive({})]", trait_list.join(", "));
327 err.span_suggestion(span, "try an outer attribute", suggestion);
332 let item = self.fully_configure(item)
333 .map_attrs(|mut attrs| { attrs.retain(|a| a.path != "derive"); attrs });
334 let item_with_markers =
335 add_derived_markers(&mut self.cx, item.span(), &traits, item.clone());
336 let derives = derives.entry(invoc.expansion_data.mark).or_insert_with(Vec::new);
338 for path in &traits {
339 let mark = Mark::fresh(self.cx.current_expansion.mark);
341 let item = match self.cx.resolver.resolve_macro(
342 Mark::root(), path, MacroKind::Derive, false) {
343 Ok(ext) => match *ext {
344 BuiltinDerive(..) => item_with_markers.clone(),
349 invocations.push(Invocation {
350 kind: InvocationKind::Derive { path: path.clone(), item: item },
351 expansion_kind: invoc.expansion_kind,
352 expansion_data: ExpansionData {
354 ..invoc.expansion_data.clone()
358 let expansion = invoc.expansion_kind
359 .expect_from_annotatables(::std::iter::once(item_with_markers));
360 self.collect_invocations(expansion, derives)
365 self.collect_invocations(invoc.expansion_kind.dummy(invoc.span()).unwrap(), &[])
368 if expansions.len() < depth {
369 expansions.push(Vec::new());
371 expansions[depth - 1].push((mark, expansion));
372 if !self.cx.ecfg.single_step {
373 invocations.extend(new_invocations.into_iter().rev());
377 self.cx.current_expansion = orig_expansion_data;
379 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
380 while let Some(expansions) = expansions.pop() {
381 for (mark, expansion) in expansions.into_iter().rev() {
382 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
383 placeholder_expander.add(NodeId::placeholder_from_mark(mark), expansion, derives);
387 expansion.fold_with(&mut placeholder_expander)
390 fn resolve_imports(&mut self) {
392 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
393 self.cx.resolver.resolve_imports();
394 self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
398 fn collect_invocations(&mut self, expansion: Expansion, derives: &[Mark])
399 -> (Expansion, Vec<Invocation>) {
401 let mut collector = InvocationCollector {
402 cfg: StripUnconfigured {
403 should_test: self.cx.ecfg.should_test,
404 sess: self.cx.parse_sess,
405 features: self.cx.ecfg.features,
408 invocations: Vec::new(),
409 monotonic: self.monotonic,
411 (expansion.fold_with(&mut collector), collector.invocations)
415 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
416 let mark = self.cx.current_expansion.mark;
417 self.cx.resolver.visit_expansion(mark, &result.0, derives);
418 self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
424 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
425 let mut cfg = StripUnconfigured {
426 should_test: self.cx.ecfg.should_test,
427 sess: self.cx.parse_sess,
428 features: self.cx.ecfg.features,
430 // Since the item itself has already been configured by the InvocationCollector,
431 // we know that fold result vector will contain exactly one element
433 Annotatable::Item(item) => {
434 Annotatable::Item(cfg.fold_item(item).pop().unwrap())
436 Annotatable::TraitItem(item) => {
437 Annotatable::TraitItem(item.map(|item| cfg.fold_trait_item(item).pop().unwrap()))
439 Annotatable::ImplItem(item) => {
440 Annotatable::ImplItem(item.map(|item| cfg.fold_impl_item(item).pop().unwrap()))
442 Annotatable::ForeignItem(item) => {
443 Annotatable::ForeignItem(
444 item.map(|item| cfg.fold_foreign_item(item).pop().unwrap())
447 Annotatable::Stmt(stmt) => {
448 Annotatable::Stmt(stmt.map(|stmt| cfg.fold_stmt(stmt).pop().unwrap()))
450 Annotatable::Expr(expr) => {
451 Annotatable::Expr(cfg.fold_expr(expr))
456 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtension) -> Option<Expansion> {
457 let result = match invoc.kind {
458 InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext)?,
459 InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext)?,
460 InvocationKind::Derive { .. } => self.expand_derive_invoc(invoc, ext)?,
463 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
464 let info = self.cx.current_expansion.mark.expn_info().unwrap();
465 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
466 let mut err = self.cx.struct_span_err(info.call_site,
467 &format!("recursion limit reached while expanding the macro `{}`",
468 info.callee.name()));
470 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
473 self.cx.trace_macros_diag();
480 fn expand_attr_invoc(&mut self,
482 ext: &SyntaxExtension)
483 -> Option<Expansion> {
484 let Invocation { expansion_kind: kind, .. } = invoc;
485 let (attr, item) = match invoc.kind {
486 InvocationKind::Attr { attr, item, .. } => (attr?, item),
490 attr::mark_used(&attr);
491 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
492 call_site: attr.span,
493 callee: NameAndSpan {
494 format: MacroAttribute(Symbol::intern(&format!("{}", attr.path))),
496 allow_internal_unstable: false,
497 allow_internal_unsafe: false,
502 MultiModifier(ref mac) => {
503 let meta = attr.parse_meta(self.cx.parse_sess)
504 .map_err(|mut e| { e.emit(); }).ok()?;
505 let item = mac.expand(self.cx, attr.span, &meta, item);
506 Some(kind.expect_from_annotatables(item))
508 MultiDecorator(ref mac) => {
509 let mut items = Vec::new();
510 let meta = attr.parse_meta(self.cx.parse_sess)
511 .expect("derive meta should already have been parsed");
512 mac.expand(self.cx, attr.span, &meta, &item, &mut |item| items.push(item));
514 Some(kind.expect_from_annotatables(items))
516 AttrProcMacro(ref mac) => {
517 let item_tok = TokenTree::Token(DUMMY_SP, Token::interpolated(match item {
518 Annotatable::Item(item) => token::NtItem(item),
519 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
520 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
521 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
522 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
523 Annotatable::Expr(expr) => token::NtExpr(expr),
525 let tok_result = mac.expand(self.cx, attr.span, attr.tokens, item_tok);
526 self.parse_expansion(tok_result, kind, &attr.path, attr.span)
528 ProcMacroDerive(..) | BuiltinDerive(..) => {
529 self.cx.span_err(attr.span, &format!("`{}` is a derive mode", attr.path));
530 self.cx.trace_macros_diag();
531 kind.dummy(attr.span)
534 let msg = &format!("macro `{}` may not be used in attributes", attr.path);
535 self.cx.span_err(attr.span, msg);
536 self.cx.trace_macros_diag();
537 kind.dummy(attr.span)
542 /// Expand a macro invocation. Returns the result of expansion.
543 fn expand_bang_invoc(&mut self,
545 ext: &SyntaxExtension)
546 -> Option<Expansion> {
547 let (mark, kind) = (invoc.expansion_data.mark, invoc.expansion_kind);
548 let (mac, ident, span) = match invoc.kind {
549 InvocationKind::Bang { mac, ident, span } => (mac, ident, span),
552 let path = &mac.node.path;
554 let ident = ident.unwrap_or_else(|| keywords::Invalid.ident());
555 let validate_and_set_expn_info = |this: &mut Self, // arg instead of capture
556 def_site_span: Option<Span>,
557 allow_internal_unstable,
558 allow_internal_unsafe,
559 // can't infer this type
560 unstable_feature: Option<(Symbol, u32)>| {
562 // feature-gate the macro invocation
563 if let Some((feature, issue)) = unstable_feature {
564 let crate_span = this.cx.current_expansion.crate_span.unwrap();
565 // don't stability-check macros in the same crate
566 // (the only time this is null is for syntax extensions registered as macros)
567 if def_site_span.map_or(false, |def_span| !crate_span.contains(def_span))
568 && !span.allows_unstable() && this.cx.ecfg.features.map_or(true, |feats| {
569 // macro features will count as lib features
570 !feats.declared_lib_features.iter().any(|&(feat, _)| feat == feature)
572 let explain = format!("macro {}! is unstable", path);
573 emit_feature_err(this.cx.parse_sess, &*feature.as_str(), span,
574 GateIssue::Library(Some(issue)), &explain);
575 this.cx.trace_macros_diag();
576 return Err(kind.dummy(span));
580 if ident.name != keywords::Invalid.name() {
581 let msg = format!("macro {}! expects no ident argument, given '{}'", path, ident);
582 this.cx.span_err(path.span, &msg);
583 this.cx.trace_macros_diag();
584 return Err(kind.dummy(span));
586 mark.set_expn_info(ExpnInfo {
588 callee: NameAndSpan {
589 format: macro_bang_format(path),
591 allow_internal_unstable,
592 allow_internal_unsafe,
598 let opt_expanded = match *ext {
599 DeclMacro(ref expand, def_span) => {
600 if let Err(dummy_span) = validate_and_set_expn_info(self, def_span.map(|(_, s)| s),
601 false, false, None) {
604 kind.make_from(expand.expand(self.cx, span, mac.node.stream()))
611 allow_internal_unstable,
612 allow_internal_unsafe,
615 if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s),
616 allow_internal_unstable,
617 allow_internal_unsafe,
621 kind.make_from(expander.expand(self.cx, span, mac.node.stream()))
625 IdentTT(ref expander, tt_span, allow_internal_unstable) => {
626 if ident.name == keywords::Invalid.name() {
627 self.cx.span_err(path.span,
628 &format!("macro {}! expects an ident argument", path));
629 self.cx.trace_macros_diag();
632 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
634 callee: NameAndSpan {
635 format: macro_bang_format(path),
637 allow_internal_unstable,
638 allow_internal_unsafe: false,
642 let input: Vec<_> = mac.node.stream().into_trees().collect();
643 kind.make_from(expander.expand(self.cx, span, ident, input))
647 MultiDecorator(..) | MultiModifier(..) | AttrProcMacro(..) => {
648 self.cx.span_err(path.span,
649 &format!("`{}` can only be used in attributes", path));
650 self.cx.trace_macros_diag();
654 ProcMacroDerive(..) | BuiltinDerive(..) => {
655 self.cx.span_err(path.span, &format!("`{}` is a derive mode", path));
656 self.cx.trace_macros_diag();
660 ProcMacro(ref expandfun) => {
661 if ident.name != keywords::Invalid.name() {
663 format!("macro {}! expects no ident argument, given '{}'", path, ident);
664 self.cx.span_err(path.span, &msg);
665 self.cx.trace_macros_diag();
668 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
670 callee: NameAndSpan {
671 format: macro_bang_format(path),
672 // FIXME procedural macros do not have proper span info
673 // yet, when they do, we should use it here.
675 // FIXME probably want to follow macro_rules macros here.
676 allow_internal_unstable: false,
677 allow_internal_unsafe: false,
681 let tok_result = expandfun.expand(self.cx, span, mac.node.stream());
682 self.parse_expansion(tok_result, kind, path, span)
687 if opt_expanded.is_some() {
690 let msg = format!("non-{kind} macro in {kind} position: {name}",
691 name = path.segments[0].ident.name, kind = kind.name());
692 self.cx.span_err(path.span, &msg);
693 self.cx.trace_macros_diag();
698 /// Expand a derive invocation. Returns the result of expansion.
699 fn expand_derive_invoc(&mut self,
701 ext: &SyntaxExtension)
702 -> Option<Expansion> {
703 let Invocation { expansion_kind: kind, .. } = invoc;
704 let (path, item) = match invoc.kind {
705 InvocationKind::Derive { path, item } => (path, item),
708 if !item.derive_allowed() {
712 let pretty_name = Symbol::intern(&format!("derive({})", path));
713 let span = path.span;
714 let attr = ast::Attribute {
716 tokens: TokenStream::empty(),
718 id: ast::AttrId(0), style: ast::AttrStyle::Outer, is_sugared_doc: false,
721 let mut expn_info = ExpnInfo {
723 callee: NameAndSpan {
724 format: MacroAttribute(pretty_name),
726 allow_internal_unstable: false,
727 allow_internal_unsafe: false,
732 ProcMacroDerive(ref ext, _) => {
733 invoc.expansion_data.mark.set_expn_info(expn_info);
734 let span = span.with_ctxt(self.cx.backtrace());
735 let dummy = ast::MetaItem { // FIXME(jseyfried) avoid this
736 name: keywords::Invalid.name(),
738 node: ast::MetaItemKind::Word,
740 Some(kind.expect_from_annotatables(ext.expand(self.cx, span, &dummy, item)))
742 BuiltinDerive(func) => {
743 expn_info.callee.allow_internal_unstable = true;
744 invoc.expansion_data.mark.set_expn_info(expn_info);
745 let span = span.with_ctxt(self.cx.backtrace());
746 let mut items = Vec::new();
747 func(self.cx, span, &attr.meta()?, &item, &mut |a| items.push(a));
748 Some(kind.expect_from_annotatables(items))
751 let msg = &format!("macro `{}` may not be used for derive attributes", attr.path);
752 self.cx.span_err(span, msg);
753 self.cx.trace_macros_diag();
759 fn parse_expansion(&mut self,
764 -> Option<Expansion> {
765 let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
766 match parser.parse_expansion(kind, false) {
768 parser.ensure_complete_parse(path, kind.name(), span);
774 self.cx.trace_macros_diag();
781 impl<'a> Parser<'a> {
782 pub fn parse_expansion(&mut self, kind: ExpansionKind, macro_legacy_warnings: bool)
783 -> PResult<'a, Expansion> {
785 ExpansionKind::Items => {
786 let mut items = SmallVector::new();
787 while let Some(item) = self.parse_item()? {
790 Expansion::Items(items)
792 ExpansionKind::TraitItems => {
793 let mut items = SmallVector::new();
794 while self.token != token::Eof {
795 items.push(self.parse_trait_item(&mut false)?);
797 Expansion::TraitItems(items)
799 ExpansionKind::ImplItems => {
800 let mut items = SmallVector::new();
801 while self.token != token::Eof {
802 items.push(self.parse_impl_item(&mut false)?);
804 Expansion::ImplItems(items)
806 ExpansionKind::ForeignItems => {
807 let mut items = SmallVector::new();
808 while self.token != token::Eof {
809 if let Some(item) = self.parse_foreign_item()? {
813 Expansion::ForeignItems(items)
815 ExpansionKind::Stmts => {
816 let mut stmts = SmallVector::new();
817 while self.token != token::Eof &&
818 // won't make progress on a `}`
819 self.token != token::CloseDelim(token::Brace) {
820 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
824 Expansion::Stmts(stmts)
826 ExpansionKind::Expr => Expansion::Expr(self.parse_expr()?),
827 ExpansionKind::OptExpr => {
828 if self.token != token::Eof {
829 Expansion::OptExpr(Some(self.parse_expr()?))
831 Expansion::OptExpr(None)
834 ExpansionKind::Ty => Expansion::Ty(self.parse_ty()?),
835 ExpansionKind::Pat => Expansion::Pat(self.parse_pat()?),
839 pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
840 if self.token != token::Eof {
841 let msg = format!("macro expansion ignores token `{}` and any following",
842 self.this_token_to_string());
843 // Avoid emitting backtrace info twice.
844 let def_site_span = self.span.with_ctxt(SyntaxContext::empty());
845 let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
846 let msg = format!("caused by the macro expansion here; the usage \
847 of `{}!` is likely invalid in {} context",
848 macro_path, kind_name);
849 err.span_note(span, &msg).emit();
854 struct InvocationCollector<'a, 'b: 'a> {
855 cx: &'a mut ExtCtxt<'b>,
856 cfg: StripUnconfigured<'a>,
857 invocations: Vec<Invocation>,
861 impl<'a, 'b> InvocationCollector<'a, 'b> {
862 fn collect(&mut self, expansion_kind: ExpansionKind, kind: InvocationKind) -> Expansion {
863 let mark = Mark::fresh(self.cx.current_expansion.mark);
864 self.invocations.push(Invocation {
867 expansion_data: ExpansionData {
869 depth: self.cx.current_expansion.depth + 1,
870 ..self.cx.current_expansion.clone()
873 placeholder(expansion_kind, NodeId::placeholder_from_mark(mark))
876 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: ExpansionKind) -> Expansion {
877 self.collect(kind, InvocationKind::Bang { mac: mac, ident: None, span: span })
880 fn collect_attr(&mut self,
881 attr: Option<ast::Attribute>,
886 self.collect(kind, InvocationKind::Attr { attr, traits, item })
889 // If `item` is an attr invocation, remove and return the macro attribute.
890 fn classify_item<T>(&mut self, mut item: T) -> (Option<ast::Attribute>, Vec<Path>, T)
893 let (mut attr, mut traits) = (None, Vec::new());
895 item = item.map_attrs(|mut attrs| {
896 if let Some(legacy_attr_invoc) = self.cx.resolver.find_legacy_attr_invoc(&mut attrs) {
897 attr = Some(legacy_attr_invoc);
901 if self.cx.ecfg.proc_macro_enabled() {
902 attr = find_attr_invoc(&mut attrs);
904 traits = collect_derives(&mut self.cx, &mut attrs);
911 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
912 self.cfg.configure(node)
915 // Detect use of feature-gated or invalid attributes on macro invocations
916 // since they will not be detected after macro expansion.
917 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
918 let features = self.cx.ecfg.features.unwrap();
919 for attr in attrs.iter() {
920 feature_gate::check_attribute(attr, self.cx.parse_sess, features);
924 fn check_attribute(&mut self, at: &ast::Attribute) {
925 let features = self.cx.ecfg.features.unwrap();
926 feature_gate::check_attribute(at, self.cx.parse_sess, features);
930 pub fn find_attr_invoc(attrs: &mut Vec<ast::Attribute>) -> Option<ast::Attribute> {
932 .position(|a| !attr::is_known(a) && !is_builtin_attr(a))
933 .map(|i| attrs.remove(i))
936 impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
937 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
938 let mut expr = self.cfg.configure_expr(expr).into_inner();
939 expr.node = self.cfg.configure_expr_kind(expr.node);
941 let (attr, derives, expr) = self.classify_item(expr);
943 if attr.is_some() || !derives.is_empty() {
944 // collect the invoc regardless of whether or not attributes are permitted here
945 // expansion will eat the attribute so it won't error later
946 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
948 // ExpansionKind::Expr requires the macro to emit an expression
949 return self.collect_attr(attr, derives, Annotatable::Expr(P(expr)), ExpansionKind::Expr)
953 if let ast::ExprKind::Mac(mac) = expr.node {
954 self.check_attributes(&expr.attrs);
955 self.collect_bang(mac, expr.span, ExpansionKind::Expr).make_expr()
957 P(noop_fold_expr(expr, self))
961 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
962 let mut expr = configure!(self, expr).into_inner();
963 expr.node = self.cfg.configure_expr_kind(expr.node);
965 let (attr, derives, expr) = self.classify_item(expr);
967 if attr.is_some() || !derives.is_empty() {
968 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
970 return self.collect_attr(attr, derives, Annotatable::Expr(P(expr)),
971 ExpansionKind::OptExpr)
975 if let ast::ExprKind::Mac(mac) = expr.node {
976 self.check_attributes(&expr.attrs);
977 self.collect_bang(mac, expr.span, ExpansionKind::OptExpr).make_opt_expr()
979 Some(P(noop_fold_expr(expr, self)))
983 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
984 let pat = self.cfg.configure_pat(pat);
986 PatKind::Mac(_) => {}
987 _ => return noop_fold_pat(pat, self),
990 pat.and_then(|pat| match pat.node {
991 PatKind::Mac(mac) => self.collect_bang(mac, pat.span, ExpansionKind::Pat).make_pat(),
996 fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
997 let mut stmt = match self.cfg.configure_stmt(stmt) {
999 None => return SmallVector::new(),
1002 // we'll expand attributes on expressions separately
1003 if !stmt.is_expr() {
1004 let (attr, derives, stmt_) = self.classify_item(stmt);
1006 if attr.is_some() || !derives.is_empty() {
1007 return self.collect_attr(attr, derives,
1008 Annotatable::Stmt(P(stmt_)), ExpansionKind::Stmts)
1015 if let StmtKind::Mac(mac) = stmt.node {
1016 let (mac, style, attrs) = mac.into_inner();
1017 self.check_attributes(&attrs);
1018 let mut placeholder = self.collect_bang(mac, stmt.span, ExpansionKind::Stmts)
1021 // If this is a macro invocation with a semicolon, then apply that
1022 // semicolon to the final statement produced by expansion.
1023 if style == MacStmtStyle::Semicolon {
1024 if let Some(stmt) = placeholder.pop() {
1025 placeholder.push(stmt.add_trailing_semicolon());
1032 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1033 let ast::Stmt { id, node, span } = stmt;
1034 noop_fold_stmt_kind(node, self).into_iter().map(|node| {
1035 ast::Stmt { id, node, span }
1040 fn fold_block(&mut self, block: P<Block>) -> P<Block> {
1041 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1042 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1043 let result = noop_fold_block(block, self);
1044 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1048 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
1049 let item = configure!(self, item);
1051 let (attr, traits, mut item) = self.classify_item(item);
1052 if attr.is_some() || !traits.is_empty() {
1053 let item = Annotatable::Item(item);
1054 return self.collect_attr(attr, traits, item, ExpansionKind::Items).make_items();
1058 ast::ItemKind::Mac(..) => {
1059 self.check_attributes(&item.attrs);
1060 item.and_then(|item| match item.node {
1061 ItemKind::Mac(mac) => {
1062 self.collect(ExpansionKind::Items, InvocationKind::Bang {
1064 ident: Some(item.ident),
1068 _ => unreachable!(),
1071 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1072 if item.ident == keywords::Invalid.ident() {
1073 return noop_fold_item(item, self);
1076 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1077 let mut module = (*self.cx.current_expansion.module).clone();
1078 module.mod_path.push(item.ident);
1080 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1081 // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`).
1082 // Thus, if `inner` is the dummy span, we know the module is inline.
1083 let inline_module = item.span.contains(inner) || inner == DUMMY_SP;
1086 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") {
1087 self.cx.current_expansion.directory_ownership =
1088 DirectoryOwnership::Owned { relative: None };
1089 module.directory.push(&*path.as_str());
1091 module.directory.push(&*item.ident.name.as_str());
1094 let path = self.cx.parse_sess.codemap().span_to_unmapped_path(inner);
1095 let mut path = match path {
1096 FileName::Real(path) => path,
1097 other => PathBuf::from(other.to_string()),
1099 let directory_ownership = match path.file_name().unwrap().to_str() {
1100 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1101 Some(_) => DirectoryOwnership::Owned {
1102 relative: Some(item.ident),
1104 None => DirectoryOwnership::UnownedViaMod(false),
1107 module.directory = path;
1108 self.cx.current_expansion.directory_ownership = directory_ownership;
1112 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1113 let result = noop_fold_item(item, self);
1114 self.cx.current_expansion.module = orig_module;
1115 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1118 // Ensure that test functions are accessible from the test harness.
1119 ast::ItemKind::Fn(..) if self.cx.ecfg.should_test => {
1120 if item.attrs.iter().any(|attr| is_test_or_bench(attr)) {
1121 item = item.map(|mut item| {
1122 item.vis = respan(item.vis.span, ast::VisibilityKind::Public);
1126 noop_fold_item(item, self)
1128 _ => noop_fold_item(item, self),
1132 fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
1133 let item = configure!(self, item);
1135 let (attr, traits, item) = self.classify_item(item);
1136 if attr.is_some() || !traits.is_empty() {
1137 let item = Annotatable::TraitItem(P(item));
1138 return self.collect_attr(attr, traits, item, ExpansionKind::TraitItems)
1143 ast::TraitItemKind::Macro(mac) => {
1144 let ast::TraitItem { attrs, span, .. } = item;
1145 self.check_attributes(&attrs);
1146 self.collect_bang(mac, span, ExpansionKind::TraitItems).make_trait_items()
1148 _ => fold::noop_fold_trait_item(item, self),
1152 fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
1153 let item = configure!(self, item);
1155 let (attr, traits, item) = self.classify_item(item);
1156 if attr.is_some() || !traits.is_empty() {
1157 let item = Annotatable::ImplItem(P(item));
1158 return self.collect_attr(attr, traits, item, ExpansionKind::ImplItems)
1163 ast::ImplItemKind::Macro(mac) => {
1164 let ast::ImplItem { attrs, span, .. } = item;
1165 self.check_attributes(&attrs);
1166 self.collect_bang(mac, span, ExpansionKind::ImplItems).make_impl_items()
1168 _ => fold::noop_fold_impl_item(item, self),
1172 fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> {
1173 let ty = match ty.node {
1174 ast::TyKind::Mac(_) => ty.into_inner(),
1175 _ => return fold::noop_fold_ty(ty, self),
1179 ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, ExpansionKind::Ty).make_ty(),
1180 _ => unreachable!(),
1184 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
1185 noop_fold_foreign_mod(self.cfg.configure_foreign_mod(foreign_mod), self)
1188 fn fold_foreign_item(&mut self,
1189 foreign_item: ast::ForeignItem) -> SmallVector<ast::ForeignItem> {
1190 let (attr, traits, foreign_item) = self.classify_item(foreign_item);
1192 let explain = if self.cx.ecfg.proc_macro_enabled() {
1193 feature_gate::EXPLAIN_PROC_MACROS_IN_EXTERN
1195 feature_gate::EXPLAIN_MACROS_IN_EXTERN
1198 if attr.is_some() || !traits.is_empty() {
1199 if !self.cx.ecfg.macros_in_extern_enabled() {
1200 if let Some(ref attr) = attr {
1201 emit_feature_err(&self.cx.parse_sess, "macros_in_extern", attr.span,
1202 GateIssue::Language, explain);
1206 let item = Annotatable::ForeignItem(P(foreign_item));
1207 return self.collect_attr(attr, traits, item, ExpansionKind::ForeignItems)
1208 .make_foreign_items();
1211 if let ast::ForeignItemKind::Macro(mac) = foreign_item.node {
1212 self.check_attributes(&foreign_item.attrs);
1214 if !self.cx.ecfg.macros_in_extern_enabled() {
1215 emit_feature_err(&self.cx.parse_sess, "macros_in_extern", foreign_item.span,
1216 GateIssue::Language, explain);
1219 return self.collect_bang(mac, foreign_item.span, ExpansionKind::ForeignItems)
1220 .make_foreign_items();
1223 noop_fold_foreign_item(foreign_item, self)
1226 fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
1228 ast::ItemKind::MacroDef(..) => item,
1229 _ => noop_fold_item_kind(self.cfg.configure_item_kind(item), self),
1233 fn fold_attribute(&mut self, at: ast::Attribute) -> Option<ast::Attribute> {
1234 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1235 // contents="file contents")]` attributes
1236 if !at.check_name("doc") {
1237 return noop_fold_attribute(at, self);
1240 if let Some(list) = at.meta_item_list() {
1241 if !list.iter().any(|it| it.check_name("include")) {
1242 return noop_fold_attribute(at, self);
1245 let mut items = vec![];
1248 if !it.check_name("include") {
1249 items.push(noop_fold_meta_list_item(it, self));
1253 if let Some(file) = it.value_str() {
1254 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1255 self.check_attribute(&at);
1256 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1257 // avoid loading the file if they haven't enabled the feature
1258 return noop_fold_attribute(at, self);
1261 let mut buf = vec![];
1262 let filename = self.cx.root_path.join(file.to_string());
1264 match File::open(&filename).and_then(|mut f| f.read_to_end(&mut buf)) {
1267 self.cx.span_err(at.span,
1268 &format!("couldn't read {}: {}",
1274 match String::from_utf8(buf) {
1276 // Add this input file to the code map to make it available as
1277 // dependency information
1278 self.cx.codemap().new_filemap_and_lines(&filename, &src);
1280 let include_info = vec![
1281 dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1282 attr::mk_name_value_item_str("file".into(),
1284 dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1285 attr::mk_name_value_item_str("contents".into(),
1289 items.push(dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1290 attr::mk_list_item("include".into(), include_info))));
1293 self.cx.span_err(at.span,
1294 &format!("{} wasn't a utf-8 file",
1295 filename.display()));
1299 items.push(noop_fold_meta_list_item(it, self));
1303 let meta = attr::mk_list_item("doc".into(), items);
1305 ast::AttrStyle::Inner =>
1306 Some(attr::mk_spanned_attr_inner(at.span, at.id, meta)),
1307 ast::AttrStyle::Outer =>
1308 Some(attr::mk_spanned_attr_outer(at.span, at.id, meta)),
1311 noop_fold_attribute(at, self)
1315 fn new_id(&mut self, id: ast::NodeId) -> ast::NodeId {
1317 assert_eq!(id, ast::DUMMY_NODE_ID);
1318 self.cx.resolver.next_node_id()
1325 pub struct ExpansionConfig<'feat> {
1326 pub crate_name: String,
1327 pub features: Option<&'feat Features>,
1328 pub recursion_limit: usize,
1329 pub trace_mac: bool,
1330 pub should_test: bool, // If false, strip `#[test]` nodes
1331 pub single_step: bool,
1332 pub keep_macs: bool,
1335 macro_rules! feature_tests {
1336 ($( fn $getter:ident = $field:ident, )*) => {
1338 pub fn $getter(&self) -> bool {
1339 match self.features {
1340 Some(&Features { $field: true, .. }) => true,
1348 impl<'feat> ExpansionConfig<'feat> {
1349 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1353 recursion_limit: 1024,
1362 fn enable_quotes = quote,
1363 fn enable_asm = asm,
1364 fn enable_global_asm = global_asm,
1365 fn enable_log_syntax = log_syntax,
1366 fn enable_concat_idents = concat_idents,
1367 fn enable_trace_macros = trace_macros,
1368 fn enable_allow_internal_unstable = allow_internal_unstable,
1369 fn enable_custom_derive = custom_derive,
1370 fn proc_macro_enabled = proc_macro,
1371 fn macros_in_extern_enabled = macros_in_extern,
1375 // A Marker adds the given mark to the syntax context.
1377 pub struct Marker(pub Mark);
1379 impl Folder for Marker {
1380 fn fold_ident(&mut self, mut ident: Ident) -> Ident {
1381 ident.span = ident.span.apply_mark(self.0);
1385 fn new_span(&mut self, span: Span) -> Span {
1386 span.apply_mark(self.0)
1389 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1390 noop_fold_mac(mac, self)