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 source_map::{ExpnInfo, MacroBang, MacroAttribute, dummy_spanned, respan};
15 use config::StripUnconfigured;
16 use errors::{Applicability, FatalError};
18 use ext::derive::{add_derived_markers, collect_derives};
19 use ext::hygiene::{self, 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, ParseSess};
25 use parse::token::{self, Token};
26 use parse::parser::Parser;
31 use syntax_pos::{Span, DUMMY_SP, FileName};
32 use syntax_pos::hygiene::ExpnFormat;
33 use tokenstream::{TokenStream, TokenTree};
34 use visit::{self, Visitor};
36 use rustc_data_structures::fx::FxHashMap;
41 use std::path::PathBuf;
43 macro_rules! ast_fragments {
45 $($Kind:ident($AstTy:ty) {
47 // FIXME: HACK: this should be `$(one ...)?` and `$(many ...)?` but `?` macro
48 // repetition was removed from 2015 edition in #51587 because of ambiguities.
49 $(one fn $fold_ast:ident; fn $visit_ast:ident;)*
50 $(many fn $fold_ast_elt:ident; fn $visit_ast_elt:ident;)*
54 /// A fragment of AST that can be produced by a single macro expansion.
55 /// Can also serve as an input and intermediate result for macro expansion operations.
56 pub enum AstFragment {
57 OptExpr(Option<P<ast::Expr>>),
61 /// "Discriminant" of an AST fragment.
62 #[derive(Copy, Clone, PartialEq, Eq)]
63 pub enum AstFragmentKind {
68 impl AstFragmentKind {
69 pub fn name(self) -> &'static str {
71 AstFragmentKind::OptExpr => "expression",
72 $(AstFragmentKind::$Kind => $kind_name,)*
76 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
78 AstFragmentKind::OptExpr =>
79 result.make_expr().map(Some).map(AstFragment::OptExpr),
80 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
86 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
88 AstFragment::OptExpr(expr) => expr,
89 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
93 $(pub fn $make_ast(self) -> $AstTy {
95 AstFragment::$Kind(ast) => ast,
96 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
100 pub fn fold_with<F: Folder>(self, folder: &mut F) -> Self {
102 AstFragment::OptExpr(expr) =>
103 AstFragment::OptExpr(expr.and_then(|expr| folder.fold_opt_expr(expr))),
104 $($(AstFragment::$Kind(ast) =>
105 AstFragment::$Kind(folder.$fold_ast(ast)),)*)*
106 $($(AstFragment::$Kind(ast) =>
107 AstFragment::$Kind(ast.into_iter()
108 .flat_map(|ast| folder.$fold_ast_elt(ast))
113 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
115 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
116 AstFragment::OptExpr(None) => {}
117 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)*)*
118 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
119 visitor.$visit_ast_elt(ast_elt);
125 impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
126 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
127 self.expand_fragment(AstFragment::OptExpr(Some(expr))).make_opt_expr()
129 $($(fn $fold_ast(&mut self, ast: $AstTy) -> $AstTy {
130 self.expand_fragment(AstFragment::$Kind(ast)).$make_ast()
132 $($(fn $fold_ast_elt(&mut self, ast_elt: <$AstTy as IntoIterator>::Item) -> $AstTy {
133 self.expand_fragment(AstFragment::$Kind(smallvec![ast_elt])).$make_ast()
137 impl<'a> MacResult for ::ext::tt::macro_rules::ParserAnyMacro<'a> {
138 $(fn $make_ast(self: Box<::ext::tt::macro_rules::ParserAnyMacro<'a>>)
140 Some(self.make(AstFragmentKind::$Kind).$make_ast())
147 Expr(P<ast::Expr>) { "expression"; one fn fold_expr; fn visit_expr; fn make_expr; }
148 Pat(P<ast::Pat>) { "pattern"; one fn fold_pat; fn visit_pat; fn make_pat; }
149 Ty(P<ast::Ty>) { "type"; one fn fold_ty; fn visit_ty; fn make_ty; }
150 Stmts(OneVector<ast::Stmt>) { "statement"; many fn fold_stmt; fn visit_stmt; fn make_stmts; }
151 Items(OneVector<P<ast::Item>>) { "item"; many fn fold_item; fn visit_item; fn make_items; }
152 TraitItems(OneVector<ast::TraitItem>) {
153 "trait item"; many fn fold_trait_item; fn visit_trait_item; fn make_trait_items;
155 ImplItems(OneVector<ast::ImplItem>) {
156 "impl item"; many fn fold_impl_item; fn visit_impl_item; fn make_impl_items;
158 ForeignItems(OneVector<ast::ForeignItem>) {
159 "foreign item"; many fn fold_foreign_item; fn visit_foreign_item; fn make_foreign_items;
163 impl AstFragmentKind {
164 fn dummy(self, span: Span) -> Option<AstFragment> {
165 self.make_from(DummyResult::any(span))
168 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
170 let mut items = items.into_iter();
172 AstFragmentKind::Items =>
173 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
174 AstFragmentKind::ImplItems =>
175 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
176 AstFragmentKind::TraitItems =>
177 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
178 AstFragmentKind::ForeignItems =>
179 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
180 AstFragmentKind::Stmts =>
181 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
182 AstFragmentKind::Expr => AstFragment::Expr(
183 items.next().expect("expected exactly one expression").expect_expr()
185 AstFragmentKind::OptExpr =>
186 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
187 AstFragmentKind::Pat | AstFragmentKind::Ty =>
188 panic!("patterns and types aren't annotatable"),
193 fn macro_bang_format(path: &ast::Path) -> ExpnFormat {
194 // We don't want to format a path using pretty-printing,
195 // `format!("{}", path)`, because that tries to insert
196 // line-breaks and is slow.
197 let mut path_str = String::with_capacity(64);
198 for (i, segment) in path.segments.iter().enumerate() {
200 path_str.push_str("::");
203 if segment.ident.name != keywords::CrateRoot.name() &&
204 segment.ident.name != keywords::DollarCrate.name()
206 path_str.push_str(&segment.ident.as_str())
210 MacroBang(Symbol::intern(&path_str))
213 pub struct Invocation {
214 pub kind: InvocationKind,
215 fragment_kind: AstFragmentKind,
216 pub expansion_data: ExpansionData,
219 // Needed for feature-gating attributes used after derives or together with test/bench
220 #[derive(Clone, Copy, PartialEq)]
221 pub enum TogetherWith {
227 pub enum InvocationKind {
230 ident: Option<Ident>,
234 attr: Option<ast::Attribute>,
237 together_with: TogetherWith,
246 pub fn span(&self) -> Span {
248 InvocationKind::Bang { span, .. } => span,
249 InvocationKind::Attr { attr: Some(ref attr), .. } => attr.span,
250 InvocationKind::Attr { attr: None, .. } => DUMMY_SP,
251 InvocationKind::Derive { ref path, .. } => path.span,
256 pub struct MacroExpander<'a, 'b:'a> {
257 pub cx: &'a mut ExtCtxt<'b>,
258 monotonic: bool, // c.f. `cx.monotonic_expander()`
261 impl<'a, 'b> MacroExpander<'a, 'b> {
262 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
263 MacroExpander { cx: cx, monotonic: monotonic }
266 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
267 let mut module = ModuleData {
268 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
269 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
270 FileName::Real(path) => path,
271 other => PathBuf::from(other.to_string()),
274 module.directory.pop();
275 self.cx.root_path = module.directory.clone();
276 self.cx.current_expansion.module = Rc::new(module);
277 self.cx.current_expansion.crate_span = Some(krate.span);
279 let orig_mod_span = krate.module.inner;
281 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
284 node: ast::ItemKind::Mod(krate.module),
285 ident: keywords::Invalid.ident(),
286 id: ast::DUMMY_NODE_ID,
287 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
291 match self.expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
292 Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
294 krate.module = module;
297 // Resolution failed so we return an empty expansion
298 krate.attrs = vec![];
299 krate.module = ast::Mod {
300 inner: orig_mod_span,
306 self.cx.trace_macros_diag();
310 // Fully expand all macro invocations in this AST fragment.
311 fn expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
312 let orig_expansion_data = self.cx.current_expansion.clone();
313 self.cx.current_expansion.depth = 0;
315 // Collect all macro invocations and replace them with placeholders.
316 let (fragment_with_placeholders, mut invocations)
317 = self.collect_invocations(input_fragment, &[]);
319 // Optimization: if we resolve all imports now,
320 // we'll be able to immediately resolve most of imported macros.
321 self.resolve_imports();
323 // Resolve paths in all invocations and produce output expanded fragments for them, but
324 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
325 // The output fragments also go through expansion recursively until no invocations are left.
326 // Unresolved macros produce dummy outputs as a recovery measure.
327 invocations.reverse();
328 let mut expanded_fragments = Vec::new();
329 let mut derives: FxHashMap<Mark, Vec<_>> = FxHashMap::default();
330 let mut undetermined_invocations = Vec::new();
331 let (mut progress, mut force) = (false, !self.monotonic);
333 let invoc = if let Some(invoc) = invocations.pop() {
336 self.resolve_imports();
337 if undetermined_invocations.is_empty() { break }
338 invocations = mem::replace(&mut undetermined_invocations, Vec::new());
339 force = !mem::replace(&mut progress, false);
344 if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark };
345 let ext = match self.cx.resolver.resolve_macro_invocation(&invoc, scope, force) {
346 Ok(ext) => Some(ext),
347 Err(Determinacy::Determined) => None,
348 Err(Determinacy::Undetermined) => {
349 undetermined_invocations.push(invoc);
355 let ExpansionData { depth, mark, .. } = invoc.expansion_data;
356 self.cx.current_expansion = invoc.expansion_data.clone();
358 self.cx.current_expansion.mark = scope;
359 // FIXME(jseyfried): Refactor out the following logic
360 let (expanded_fragment, new_invocations) = if let Some(ext) = ext {
361 if let Some(ext) = ext {
362 let dummy = invoc.fragment_kind.dummy(invoc.span()).unwrap();
363 let fragment = self.expand_invoc(invoc, &*ext).unwrap_or(dummy);
364 self.collect_invocations(fragment, &[])
365 } else if let InvocationKind::Attr { attr: None, traits, item, .. } = invoc.kind {
366 if !item.derive_allowed() {
367 let attr = attr::find_by_name(item.attrs(), "derive")
368 .expect("`derive` attribute should exist");
369 let span = attr.span;
370 let mut err = self.cx.mut_span_err(span,
371 "`derive` may only be applied to \
372 structs, enums and unions");
373 if let ast::AttrStyle::Inner = attr.style {
374 let trait_list = traits.iter()
375 .map(|t| t.to_string()).collect::<Vec<_>>();
376 let suggestion = format!("#[derive({})]", trait_list.join(", "));
377 err.span_suggestion_with_applicability(
378 span, "try an outer attribute", suggestion,
379 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
380 Applicability::MaybeIncorrect
386 let item = self.fully_configure(item)
387 .map_attrs(|mut attrs| { attrs.retain(|a| a.path != "derive"); attrs });
388 let item_with_markers =
389 add_derived_markers(&mut self.cx, item.span(), &traits, item.clone());
390 let derives = derives.entry(invoc.expansion_data.mark).or_default();
392 for path in &traits {
393 let mark = Mark::fresh(self.cx.current_expansion.mark);
395 let item = match self.cx.resolver.resolve_macro_path(
396 path, MacroKind::Derive, Mark::root(), Vec::new(), false) {
397 Ok(ext) => match *ext {
398 BuiltinDerive(..) => item_with_markers.clone(),
403 invocations.push(Invocation {
404 kind: InvocationKind::Derive { path: path.clone(), item: item },
405 fragment_kind: invoc.fragment_kind,
406 expansion_data: ExpansionData {
408 ..invoc.expansion_data.clone()
412 let fragment = invoc.fragment_kind
413 .expect_from_annotatables(::std::iter::once(item_with_markers));
414 self.collect_invocations(fragment, derives)
419 self.collect_invocations(invoc.fragment_kind.dummy(invoc.span()).unwrap(), &[])
422 if expanded_fragments.len() < depth {
423 expanded_fragments.push(Vec::new());
425 expanded_fragments[depth - 1].push((mark, expanded_fragment));
426 if !self.cx.ecfg.single_step {
427 invocations.extend(new_invocations.into_iter().rev());
431 self.cx.current_expansion = orig_expansion_data;
433 // Finally incorporate all the expanded macros into the input AST fragment.
434 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
435 while let Some(expanded_fragments) = expanded_fragments.pop() {
436 for (mark, expanded_fragment) in expanded_fragments.into_iter().rev() {
437 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
438 placeholder_expander.add(NodeId::placeholder_from_mark(mark),
439 expanded_fragment, derives);
442 fragment_with_placeholders.fold_with(&mut placeholder_expander)
445 fn resolve_imports(&mut self) {
447 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
448 self.cx.resolver.resolve_imports();
449 self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
453 /// Collect all macro invocations reachable at this time in this AST fragment, and replace
454 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
455 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
456 /// prepares data for resolving paths of macro invocations.
457 fn collect_invocations(&mut self, fragment: AstFragment, derives: &[Mark])
458 -> (AstFragment, Vec<Invocation>) {
459 let (fragment_with_placeholders, invocations) = {
460 let mut collector = InvocationCollector {
461 cfg: StripUnconfigured {
462 sess: self.cx.parse_sess,
463 features: self.cx.ecfg.features,
466 invocations: Vec::new(),
467 monotonic: self.monotonic,
469 (fragment.fold_with(&mut collector), collector.invocations)
473 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
474 let mark = self.cx.current_expansion.mark;
475 self.cx.resolver.visit_ast_fragment_with_placeholders(mark, &fragment_with_placeholders,
477 self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
480 (fragment_with_placeholders, invocations)
483 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
484 let mut cfg = StripUnconfigured {
485 sess: self.cx.parse_sess,
486 features: self.cx.ecfg.features,
488 // Since the item itself has already been configured by the InvocationCollector,
489 // we know that fold result vector will contain exactly one element
491 Annotatable::Item(item) => {
492 Annotatable::Item(cfg.fold_item(item).pop().unwrap())
494 Annotatable::TraitItem(item) => {
495 Annotatable::TraitItem(item.map(|item| cfg.fold_trait_item(item).pop().unwrap()))
497 Annotatable::ImplItem(item) => {
498 Annotatable::ImplItem(item.map(|item| cfg.fold_impl_item(item).pop().unwrap()))
500 Annotatable::ForeignItem(item) => {
501 Annotatable::ForeignItem(
502 item.map(|item| cfg.fold_foreign_item(item).pop().unwrap())
505 Annotatable::Stmt(stmt) => {
506 Annotatable::Stmt(stmt.map(|stmt| cfg.fold_stmt(stmt).pop().unwrap()))
508 Annotatable::Expr(expr) => {
509 Annotatable::Expr(cfg.fold_expr(expr))
514 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtension) -> Option<AstFragment> {
515 if invoc.fragment_kind == AstFragmentKind::ForeignItems &&
516 !self.cx.ecfg.macros_in_extern_enabled() {
517 if let SyntaxExtension::NonMacroAttr { .. } = *ext {} else {
518 emit_feature_err(&self.cx.parse_sess, "macros_in_extern",
519 invoc.span(), GateIssue::Language,
520 "macro invocations in `extern {}` blocks are experimental");
524 let result = match invoc.kind {
525 InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext)?,
526 InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext)?,
527 InvocationKind::Derive { .. } => self.expand_derive_invoc(invoc, ext)?,
530 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
531 let info = self.cx.current_expansion.mark.expn_info().unwrap();
532 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
533 let mut err = self.cx.struct_span_err(info.call_site,
534 &format!("recursion limit reached while expanding the macro `{}`",
535 info.format.name()));
537 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
540 self.cx.trace_macros_diag();
547 fn expand_attr_invoc(&mut self,
549 ext: &SyntaxExtension)
550 -> Option<AstFragment> {
551 let (attr, item) = match invoc.kind {
552 InvocationKind::Attr { attr, item, .. } => (attr?, item),
556 if let NonMacroAttr { mark_used: false } = *ext {} else {
557 // Macro attrs are always used when expanded,
558 // non-macro attrs are considered used when the field says so.
559 attr::mark_used(&attr);
561 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
562 call_site: attr.span,
564 format: MacroAttribute(Symbol::intern(&attr.path.to_string())),
565 allow_internal_unstable: false,
566 allow_internal_unsafe: false,
567 local_inner_macros: false,
568 edition: ext.edition(),
572 NonMacroAttr { .. } => {
573 attr::mark_known(&attr);
574 let item = item.map_attrs(|mut attrs| { attrs.push(attr); attrs });
575 Some(invoc.fragment_kind.expect_from_annotatables(iter::once(item)))
577 MultiModifier(ref mac) => {
578 let meta = attr.parse_meta(self.cx.parse_sess)
579 .map_err(|mut e| { e.emit(); }).ok()?;
580 let item = mac.expand(self.cx, attr.span, &meta, item);
581 Some(invoc.fragment_kind.expect_from_annotatables(item))
583 MultiDecorator(ref mac) => {
584 let mut items = Vec::new();
585 let meta = attr.parse_meta(self.cx.parse_sess)
586 .expect("derive meta should already have been parsed");
587 mac.expand(self.cx, attr.span, &meta, &item, &mut |item| items.push(item));
589 Some(invoc.fragment_kind.expect_from_annotatables(items))
591 AttrProcMacro(ref mac, ..) => {
592 self.gate_proc_macro_attr_item(attr.span, &item);
593 let item_tok = TokenTree::Token(DUMMY_SP, Token::interpolated(match item {
594 Annotatable::Item(item) => token::NtItem(item),
595 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
596 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
597 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
598 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
599 Annotatable::Expr(expr) => token::NtExpr(expr),
601 let input = self.extract_proc_macro_attr_input(attr.tokens, attr.span);
602 let tok_result = mac.expand(self.cx, attr.span, input, item_tok);
603 let res = self.parse_ast_fragment(tok_result, invoc.fragment_kind,
604 &attr.path, attr.span);
605 self.gate_proc_macro_expansion(attr.span, &res);
608 ProcMacroDerive(..) | BuiltinDerive(..) => {
609 self.cx.span_err(attr.span, &format!("`{}` is a derive mode", attr.path));
610 self.cx.trace_macros_diag();
611 invoc.fragment_kind.dummy(attr.span)
614 let msg = &format!("macro `{}` may not be used in attributes", attr.path);
615 self.cx.span_err(attr.span, msg);
616 self.cx.trace_macros_diag();
617 invoc.fragment_kind.dummy(attr.span)
622 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
623 let mut trees = tokens.trees();
625 Some(TokenTree::Delimited(_, delim)) => {
626 if trees.next().is_none() {
627 return delim.tts.into()
630 Some(TokenTree::Token(..)) => {}
631 None => return TokenStream::empty(),
633 self.cx.span_err(span, "custom attribute invocations must be \
634 of the form #[foo] or #[foo(..)], the macro name must only be \
635 followed by a delimiter token");
639 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
640 let (kind, gate) = match *item {
641 Annotatable::Item(ref item) => {
643 ItemKind::Mod(_) if self.cx.ecfg.proc_macro_mod() => return,
644 ItemKind::Mod(_) => ("modules", "proc_macro_mod"),
648 Annotatable::TraitItem(_) => return,
649 Annotatable::ImplItem(_) => return,
650 Annotatable::ForeignItem(_) => return,
651 Annotatable::Stmt(_) |
652 Annotatable::Expr(_) if self.cx.ecfg.proc_macro_expr() => return,
653 Annotatable::Stmt(_) => ("statements", "proc_macro_expr"),
654 Annotatable::Expr(_) => ("expressions", "proc_macro_expr"),
661 &format!("custom attributes cannot be applied to {}", kind),
665 fn gate_proc_macro_expansion(&self, span: Span, fragment: &Option<AstFragment>) {
666 if self.cx.ecfg.proc_macro_gen() {
669 let fragment = match fragment {
670 Some(fragment) => fragment,
674 fragment.visit_with(&mut DisallowMacros {
676 parse_sess: self.cx.parse_sess,
679 struct DisallowMacros<'a> {
681 parse_sess: &'a ParseSess,
684 impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
685 fn visit_item(&mut self, i: &'ast ast::Item) {
686 if let ast::ItemKind::MacroDef(_) = i.node {
692 &format!("procedural macros cannot expand to macro definitions"),
695 visit::walk_item(self, i);
698 fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
704 /// Expand a macro invocation. Returns the resulting expanded AST fragment.
705 fn expand_bang_invoc(&mut self,
707 ext: &SyntaxExtension)
708 -> Option<AstFragment> {
709 let (mark, kind) = (invoc.expansion_data.mark, invoc.fragment_kind);
710 let (mac, ident, span) = match invoc.kind {
711 InvocationKind::Bang { mac, ident, span } => (mac, ident, span),
714 let path = &mac.node.path;
716 let ident = ident.unwrap_or_else(|| keywords::Invalid.ident());
717 let validate_and_set_expn_info = |this: &mut Self, // arg instead of capture
718 def_site_span: Option<Span>,
719 allow_internal_unstable,
720 allow_internal_unsafe,
722 // can't infer this type
723 unstable_feature: Option<(Symbol, u32)>,
726 // feature-gate the macro invocation
727 if let Some((feature, issue)) = unstable_feature {
728 let crate_span = this.cx.current_expansion.crate_span.unwrap();
729 // don't stability-check macros in the same crate
730 // (the only time this is null is for syntax extensions registered as macros)
731 if def_site_span.map_or(false, |def_span| !crate_span.contains(def_span))
732 && !span.allows_unstable() && this.cx.ecfg.features.map_or(true, |feats| {
733 // macro features will count as lib features
734 !feats.declared_lib_features.iter().any(|&(feat, _)| feat == feature)
736 let explain = format!("macro {}! is unstable", path);
737 emit_feature_err(this.cx.parse_sess, &*feature.as_str(), span,
738 GateIssue::Library(Some(issue)), &explain);
739 this.cx.trace_macros_diag();
740 return Err(kind.dummy(span));
744 if ident.name != keywords::Invalid.name() {
745 let msg = format!("macro {}! expects no ident argument, given '{}'", path, ident);
746 this.cx.span_err(path.span, &msg);
747 this.cx.trace_macros_diag();
748 return Err(kind.dummy(span));
750 mark.set_expn_info(ExpnInfo {
752 def_site: def_site_span,
753 format: macro_bang_format(path),
754 allow_internal_unstable,
755 allow_internal_unsafe,
762 let opt_expanded = match *ext {
763 DeclMacro { ref expander, def_info, edition, .. } => {
764 if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s),
765 false, false, false, None,
769 kind.make_from(expander.expand(self.cx, span, mac.node.stream()))
776 allow_internal_unstable,
777 allow_internal_unsafe,
782 if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s),
783 allow_internal_unstable,
784 allow_internal_unsafe,
790 kind.make_from(expander.expand(self.cx, span, mac.node.stream()))
794 IdentTT(ref expander, tt_span, allow_internal_unstable) => {
795 if ident.name == keywords::Invalid.name() {
796 self.cx.span_err(path.span,
797 &format!("macro {}! expects an ident argument", path));
798 self.cx.trace_macros_diag();
801 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
804 format: macro_bang_format(path),
805 allow_internal_unstable,
806 allow_internal_unsafe: false,
807 local_inner_macros: false,
808 edition: hygiene::default_edition(),
811 let input: Vec<_> = mac.node.stream().into_trees().collect();
812 kind.make_from(expander.expand(self.cx, span, ident, input))
816 MultiDecorator(..) | MultiModifier(..) |
817 AttrProcMacro(..) | SyntaxExtension::NonMacroAttr { .. } => {
818 self.cx.span_err(path.span,
819 &format!("`{}` can only be used in attributes", path));
820 self.cx.trace_macros_diag();
824 ProcMacroDerive(..) | BuiltinDerive(..) => {
825 self.cx.span_err(path.span, &format!("`{}` is a derive mode", path));
826 self.cx.trace_macros_diag();
830 SyntaxExtension::ProcMacro { ref expander, allow_internal_unstable, edition } => {
831 if ident.name != keywords::Invalid.name() {
833 format!("macro {}! expects no ident argument, given '{}'", path, ident);
834 self.cx.span_err(path.span, &msg);
835 self.cx.trace_macros_diag();
838 self.gate_proc_macro_expansion_kind(span, kind);
839 invoc.expansion_data.mark.set_expn_info(ExpnInfo {
841 // FIXME procedural macros do not have proper span info
842 // yet, when they do, we should use it here.
844 format: macro_bang_format(path),
845 // FIXME probably want to follow macro_rules macros here.
846 allow_internal_unstable,
847 allow_internal_unsafe: false,
848 local_inner_macros: false,
852 let tok_result = expander.expand(self.cx, span, mac.node.stream());
853 let result = self.parse_ast_fragment(tok_result, kind, path, span);
854 self.gate_proc_macro_expansion(span, &result);
860 if opt_expanded.is_some() {
863 let msg = format!("non-{kind} macro in {kind} position: {name}",
864 name = path.segments[0].ident.name, kind = kind.name());
865 self.cx.span_err(path.span, &msg);
866 self.cx.trace_macros_diag();
871 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
872 let kind = match kind {
873 AstFragmentKind::Expr => "expressions",
874 AstFragmentKind::OptExpr => "expressions",
875 AstFragmentKind::Pat => "patterns",
876 AstFragmentKind::Ty => "types",
877 AstFragmentKind::Stmts => "statements",
878 AstFragmentKind::Items => return,
879 AstFragmentKind::TraitItems => return,
880 AstFragmentKind::ImplItems => return,
881 AstFragmentKind::ForeignItems => return,
883 if self.cx.ecfg.proc_macro_non_items() {
888 "proc_macro_non_items",
891 &format!("procedural macros cannot be expanded to {}", kind),
895 /// Expand a derive invocation. Returns the resulting expanded AST fragment.
896 fn expand_derive_invoc(&mut self,
898 ext: &SyntaxExtension)
899 -> Option<AstFragment> {
900 let (path, item) = match invoc.kind {
901 InvocationKind::Derive { path, item } => (path, item),
904 if !item.derive_allowed() {
908 let pretty_name = Symbol::intern(&format!("derive({})", path));
909 let span = path.span;
910 let attr = ast::Attribute {
912 tokens: TokenStream::empty(),
914 id: ast::AttrId(0), style: ast::AttrStyle::Outer, is_sugared_doc: false,
917 let mut expn_info = ExpnInfo {
920 format: MacroAttribute(pretty_name),
921 allow_internal_unstable: false,
922 allow_internal_unsafe: false,
923 local_inner_macros: false,
924 edition: ext.edition(),
928 ProcMacroDerive(ref ext, ..) => {
929 invoc.expansion_data.mark.set_expn_info(expn_info);
930 let span = span.with_ctxt(self.cx.backtrace());
931 let dummy = ast::MetaItem { // FIXME(jseyfried) avoid this
932 ident: Path::from_ident(keywords::Invalid.ident()),
934 node: ast::MetaItemKind::Word,
936 let items = ext.expand(self.cx, span, &dummy, item);
937 Some(invoc.fragment_kind.expect_from_annotatables(items))
939 BuiltinDerive(func) => {
940 expn_info.allow_internal_unstable = true;
941 invoc.expansion_data.mark.set_expn_info(expn_info);
942 let span = span.with_ctxt(self.cx.backtrace());
943 let mut items = Vec::new();
944 func(self.cx, span, &attr.meta()?, &item, &mut |a| items.push(a));
945 Some(invoc.fragment_kind.expect_from_annotatables(items))
948 let msg = &format!("macro `{}` may not be used for derive attributes", attr.path);
949 self.cx.span_err(span, msg);
950 self.cx.trace_macros_diag();
951 invoc.fragment_kind.dummy(span)
956 fn parse_ast_fragment(&mut self,
958 kind: AstFragmentKind,
961 -> Option<AstFragment> {
962 let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
963 match parser.parse_ast_fragment(kind, false) {
965 parser.ensure_complete_parse(path, kind.name(), span);
971 self.cx.trace_macros_diag();
978 impl<'a> Parser<'a> {
979 pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
980 -> PResult<'a, AstFragment> {
982 AstFragmentKind::Items => {
983 let mut items = OneVector::new();
984 while let Some(item) = self.parse_item()? {
987 AstFragment::Items(items)
989 AstFragmentKind::TraitItems => {
990 let mut items = OneVector::new();
991 while self.token != token::Eof {
992 items.push(self.parse_trait_item(&mut false)?);
994 AstFragment::TraitItems(items)
996 AstFragmentKind::ImplItems => {
997 let mut items = OneVector::new();
998 while self.token != token::Eof {
999 items.push(self.parse_impl_item(&mut false)?);
1001 AstFragment::ImplItems(items)
1003 AstFragmentKind::ForeignItems => {
1004 let mut items = OneVector::new();
1005 while self.token != token::Eof {
1006 if let Some(item) = self.parse_foreign_item()? {
1010 AstFragment::ForeignItems(items)
1012 AstFragmentKind::Stmts => {
1013 let mut stmts = OneVector::new();
1014 while self.token != token::Eof &&
1015 // won't make progress on a `}`
1016 self.token != token::CloseDelim(token::Brace) {
1017 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
1021 AstFragment::Stmts(stmts)
1023 AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
1024 AstFragmentKind::OptExpr => {
1025 if self.token != token::Eof {
1026 AstFragment::OptExpr(Some(self.parse_expr()?))
1028 AstFragment::OptExpr(None)
1031 AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
1032 AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat()?),
1036 pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
1037 if self.token != token::Eof {
1038 let msg = format!("macro expansion ignores token `{}` and any following",
1039 self.this_token_to_string());
1040 // Avoid emitting backtrace info twice.
1041 let def_site_span = self.span.with_ctxt(SyntaxContext::empty());
1042 let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
1043 let msg = format!("caused by the macro expansion here; the usage \
1044 of `{}!` is likely invalid in {} context",
1045 macro_path, kind_name);
1046 err.span_note(span, &msg).emit();
1051 struct InvocationCollector<'a, 'b: 'a> {
1052 cx: &'a mut ExtCtxt<'b>,
1053 cfg: StripUnconfigured<'a>,
1054 invocations: Vec<Invocation>,
1058 impl<'a, 'b> InvocationCollector<'a, 'b> {
1059 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
1060 let mark = Mark::fresh(self.cx.current_expansion.mark);
1061 self.invocations.push(Invocation {
1064 expansion_data: ExpansionData {
1066 depth: self.cx.current_expansion.depth + 1,
1067 ..self.cx.current_expansion.clone()
1070 placeholder(fragment_kind, NodeId::placeholder_from_mark(mark))
1073 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
1074 self.collect(kind, InvocationKind::Bang { mac: mac, ident: None, span: span })
1077 fn collect_attr(&mut self,
1078 attr: Option<ast::Attribute>,
1081 kind: AstFragmentKind,
1082 together_with: TogetherWith)
1084 self.collect(kind, InvocationKind::Attr { attr, traits, item, together_with })
1087 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, together_with: &mut TogetherWith)
1088 -> Option<ast::Attribute> {
1089 let attr = attrs.iter()
1091 if a.path == "derive" {
1092 *together_with = TogetherWith::Derive
1093 } else if a.path == "rustc_test_marker2" {
1094 *together_with = TogetherWith::TestBench
1096 !attr::is_known(a) && !is_builtin_attr(a)
1098 .map(|i| attrs.remove(i));
1099 if let Some(attr) = &attr {
1100 if !self.cx.ecfg.enable_custom_inner_attributes() &&
1101 attr.style == ast::AttrStyle::Inner && attr.path != "test" {
1102 emit_feature_err(&self.cx.parse_sess, "custom_inner_attributes",
1103 attr.span, GateIssue::Language,
1104 "non-builtin inner attributes are unstable");
1107 if together_with == &TogetherWith::None &&
1108 attrs.iter().any(|a| a.path == "rustc_test_marker2") {
1109 *together_with = TogetherWith::TestBench;
1114 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
1115 fn classify_item<T>(&mut self, mut item: T)
1116 -> (Option<ast::Attribute>, Vec<Path>, T, TogetherWith)
1119 let (mut attr, mut traits, mut together_with) = (None, Vec::new(), TogetherWith::None);
1121 item = item.map_attrs(|mut attrs| {
1122 if let Some(legacy_attr_invoc) = self.cx.resolver.find_legacy_attr_invoc(&mut attrs,
1124 attr = Some(legacy_attr_invoc);
1128 attr = self.find_attr_invoc(&mut attrs, &mut together_with);
1129 traits = collect_derives(&mut self.cx, &mut attrs);
1133 (attr, traits, item, together_with)
1136 /// Alternative of `classify_item()` that ignores `#[derive]` so invocations fallthrough
1137 /// to the unused-attributes lint (making it an error on statements and expressions
1138 /// is a breaking change)
1139 fn classify_nonitem<T: HasAttrs>(&mut self, mut item: T)
1140 -> (Option<ast::Attribute>, T, TogetherWith) {
1141 let (mut attr, mut together_with) = (None, TogetherWith::None);
1143 item = item.map_attrs(|mut attrs| {
1144 if let Some(legacy_attr_invoc) = self.cx.resolver.find_legacy_attr_invoc(&mut attrs,
1146 attr = Some(legacy_attr_invoc);
1150 attr = self.find_attr_invoc(&mut attrs, &mut together_with);
1154 (attr, item, together_with)
1157 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1158 self.cfg.configure(node)
1161 // Detect use of feature-gated or invalid attributes on macro invocations
1162 // since they will not be detected after macro expansion.
1163 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1164 let features = self.cx.ecfg.features.unwrap();
1165 for attr in attrs.iter() {
1166 self.check_attribute_inner(attr, features);
1168 // macros are expanded before any lint passes so this warning has to be hardcoded
1169 if attr.path == "derive" {
1170 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1171 .note("this may become a hard error in a future release")
1177 fn check_attribute(&mut self, at: &ast::Attribute) {
1178 let features = self.cx.ecfg.features.unwrap();
1179 self.check_attribute_inner(at, features);
1182 fn check_attribute_inner(&mut self, at: &ast::Attribute, features: &Features) {
1183 feature_gate::check_attribute(at, self.cx.parse_sess, features);
1187 impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
1188 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
1189 let mut expr = self.cfg.configure_expr(expr).into_inner();
1190 expr.node = self.cfg.configure_expr_kind(expr.node);
1192 // ignore derives so they remain unused
1193 let (attr, expr, together_with) = self.classify_nonitem(expr);
1196 // collect the invoc regardless of whether or not attributes are permitted here
1197 // expansion will eat the attribute so it won't error later
1198 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1200 // AstFragmentKind::Expr requires the macro to emit an expression
1201 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1202 AstFragmentKind::Expr, together_with).make_expr();
1205 if let ast::ExprKind::Mac(mac) = expr.node {
1206 self.check_attributes(&expr.attrs);
1207 self.collect_bang(mac, expr.span, AstFragmentKind::Expr).make_expr()
1209 P(noop_fold_expr(expr, self))
1213 fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1214 let mut expr = configure!(self, expr).into_inner();
1215 expr.node = self.cfg.configure_expr_kind(expr.node);
1217 // ignore derives so they remain unused
1218 let (attr, expr, together_with) = self.classify_nonitem(expr);
1221 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1223 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1224 AstFragmentKind::OptExpr, together_with).make_opt_expr();
1227 if let ast::ExprKind::Mac(mac) = expr.node {
1228 self.check_attributes(&expr.attrs);
1229 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr).make_opt_expr()
1231 Some(P(noop_fold_expr(expr, self)))
1235 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
1236 let pat = self.cfg.configure_pat(pat);
1238 PatKind::Mac(_) => {}
1239 _ => return noop_fold_pat(pat, self),
1242 pat.and_then(|pat| match pat.node {
1243 PatKind::Mac(mac) => self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1244 _ => unreachable!(),
1248 fn fold_stmt(&mut self, stmt: ast::Stmt) -> OneVector<ast::Stmt> {
1249 let mut stmt = match self.cfg.configure_stmt(stmt) {
1251 None => return OneVector::new(),
1254 // we'll expand attributes on expressions separately
1255 if !stmt.is_expr() {
1256 let (attr, derives, stmt_, together_with) = if stmt.is_item() {
1257 self.classify_item(stmt)
1259 // ignore derives on non-item statements so it falls through
1260 // to the unused-attributes lint
1261 let (attr, stmt, together_with) = self.classify_nonitem(stmt);
1262 (attr, vec![], stmt, together_with)
1265 if attr.is_some() || !derives.is_empty() {
1266 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt_)),
1267 AstFragmentKind::Stmts, together_with).make_stmts();
1273 if let StmtKind::Mac(mac) = stmt.node {
1274 let (mac, style, attrs) = mac.into_inner();
1275 self.check_attributes(&attrs);
1276 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1279 // If this is a macro invocation with a semicolon, then apply that
1280 // semicolon to the final statement produced by expansion.
1281 if style == MacStmtStyle::Semicolon {
1282 if let Some(stmt) = placeholder.pop() {
1283 placeholder.push(stmt.add_trailing_semicolon());
1290 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1291 let ast::Stmt { id, node, span } = stmt;
1292 noop_fold_stmt_kind(node, self).into_iter().map(|node| {
1293 ast::Stmt { id, node, span }
1298 fn fold_block(&mut self, block: P<Block>) -> P<Block> {
1299 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1300 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1301 let result = noop_fold_block(block, self);
1302 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1306 fn fold_item(&mut self, item: P<ast::Item>) -> OneVector<P<ast::Item>> {
1307 let item = configure!(self, item);
1309 let (attr, traits, item, together_with) = self.classify_item(item);
1310 if attr.is_some() || !traits.is_empty() {
1311 return self.collect_attr(attr, traits, Annotatable::Item(item),
1312 AstFragmentKind::Items, together_with).make_items();
1316 ast::ItemKind::Mac(..) => {
1317 self.check_attributes(&item.attrs);
1318 item.and_then(|item| match item.node {
1319 ItemKind::Mac(mac) => {
1320 self.collect(AstFragmentKind::Items, InvocationKind::Bang {
1322 ident: Some(item.ident),
1326 _ => unreachable!(),
1329 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1330 if item.ident == keywords::Invalid.ident() {
1331 return noop_fold_item(item, self);
1334 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1335 let mut module = (*self.cx.current_expansion.module).clone();
1336 module.mod_path.push(item.ident);
1338 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1339 // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`).
1340 // Thus, if `inner` is the dummy span, we know the module is inline.
1341 let inline_module = item.span.contains(inner) || inner.is_dummy();
1344 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") {
1345 self.cx.current_expansion.directory_ownership =
1346 DirectoryOwnership::Owned { relative: None };
1347 module.directory.push(&*path.as_str());
1349 module.directory.push(&*item.ident.as_str());
1352 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1353 let mut path = match path {
1354 FileName::Real(path) => path,
1355 other => PathBuf::from(other.to_string()),
1357 let directory_ownership = match path.file_name().unwrap().to_str() {
1358 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1359 Some(_) => DirectoryOwnership::Owned {
1360 relative: Some(item.ident),
1362 None => DirectoryOwnership::UnownedViaMod(false),
1365 module.directory = path;
1366 self.cx.current_expansion.directory_ownership = directory_ownership;
1370 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1371 let result = noop_fold_item(item, self);
1372 self.cx.current_expansion.module = orig_module;
1373 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1377 _ => noop_fold_item(item, self),
1381 fn fold_trait_item(&mut self, item: ast::TraitItem) -> OneVector<ast::TraitItem> {
1382 let item = configure!(self, item);
1384 let (attr, traits, item, together_with) = self.classify_item(item);
1385 if attr.is_some() || !traits.is_empty() {
1386 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1387 AstFragmentKind::TraitItems, together_with).make_trait_items()
1391 ast::TraitItemKind::Macro(mac) => {
1392 let ast::TraitItem { attrs, span, .. } = item;
1393 self.check_attributes(&attrs);
1394 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1396 _ => fold::noop_fold_trait_item(item, self),
1400 fn fold_impl_item(&mut self, item: ast::ImplItem) -> OneVector<ast::ImplItem> {
1401 let item = configure!(self, item);
1403 let (attr, traits, item, together_with) = self.classify_item(item);
1404 if attr.is_some() || !traits.is_empty() {
1405 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1406 AstFragmentKind::ImplItems, together_with).make_impl_items();
1410 ast::ImplItemKind::Macro(mac) => {
1411 let ast::ImplItem { attrs, span, .. } = item;
1412 self.check_attributes(&attrs);
1413 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1415 _ => fold::noop_fold_impl_item(item, self),
1419 fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> {
1420 let ty = match ty.node {
1421 ast::TyKind::Mac(_) => ty.into_inner(),
1422 _ => return fold::noop_fold_ty(ty, self),
1426 ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1427 _ => unreachable!(),
1431 fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
1432 noop_fold_foreign_mod(self.cfg.configure_foreign_mod(foreign_mod), self)
1435 fn fold_foreign_item(&mut self,
1436 foreign_item: ast::ForeignItem) -> OneVector<ast::ForeignItem> {
1437 let (attr, traits, foreign_item, together_with) = self.classify_item(foreign_item);
1439 if attr.is_some() || !traits.is_empty() {
1440 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1441 AstFragmentKind::ForeignItems, together_with)
1442 .make_foreign_items();
1445 if let ast::ForeignItemKind::Macro(mac) = foreign_item.node {
1446 self.check_attributes(&foreign_item.attrs);
1447 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1448 .make_foreign_items();
1451 noop_fold_foreign_item(foreign_item, self)
1454 fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
1456 ast::ItemKind::MacroDef(..) => item,
1457 _ => noop_fold_item_kind(self.cfg.configure_item_kind(item), self),
1461 fn fold_generic_param(&mut self, param: ast::GenericParam) -> ast::GenericParam {
1462 self.cfg.disallow_cfg_on_generic_param(¶m);
1463 noop_fold_generic_param(param, self)
1466 fn fold_attribute(&mut self, at: ast::Attribute) -> Option<ast::Attribute> {
1467 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1468 // contents="file contents")]` attributes
1469 if !at.check_name("doc") {
1470 return noop_fold_attribute(at, self);
1473 if let Some(list) = at.meta_item_list() {
1474 if !list.iter().any(|it| it.check_name("include")) {
1475 return noop_fold_attribute(at, self);
1478 let mut items = vec![];
1481 if !it.check_name("include") {
1482 items.push(noop_fold_meta_list_item(it, self));
1486 if let Some(file) = it.value_str() {
1487 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1488 self.check_attribute(&at);
1489 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1490 // avoid loading the file if they haven't enabled the feature
1491 return noop_fold_attribute(at, self);
1494 let mut buf = vec![];
1495 let filename = self.cx.root_path.join(file.to_string());
1497 match File::open(&filename).and_then(|mut f| f.read_to_end(&mut buf)) {
1500 self.cx.span_err(at.span,
1501 &format!("couldn't read {}: {}",
1507 match String::from_utf8(buf) {
1509 let src_interned = Symbol::intern(&src);
1511 // Add this input file to the code map to make it available as
1512 // dependency information
1513 self.cx.source_map().new_source_file(filename.into(), src);
1515 let include_info = vec![
1516 dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1517 attr::mk_name_value_item_str(Ident::from_str("file"),
1518 dummy_spanned(file)))),
1519 dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1520 attr::mk_name_value_item_str(Ident::from_str("contents"),
1521 dummy_spanned(src_interned)))),
1524 let include_ident = Ident::from_str("include");
1525 let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info);
1526 items.push(dummy_spanned(ast::NestedMetaItemKind::MetaItem(item)));
1529 self.cx.span_err(at.span,
1530 &format!("{} wasn't a utf-8 file",
1531 filename.display()));
1535 items.push(noop_fold_meta_list_item(it, self));
1539 let meta = attr::mk_list_item(DUMMY_SP, Ident::from_str("doc"), items);
1541 ast::AttrStyle::Inner =>
1542 Some(attr::mk_spanned_attr_inner(at.span, at.id, meta)),
1543 ast::AttrStyle::Outer =>
1544 Some(attr::mk_spanned_attr_outer(at.span, at.id, meta)),
1547 noop_fold_attribute(at, self)
1551 fn new_id(&mut self, id: ast::NodeId) -> ast::NodeId {
1553 assert_eq!(id, ast::DUMMY_NODE_ID);
1554 self.cx.resolver.next_node_id()
1561 pub struct ExpansionConfig<'feat> {
1562 pub crate_name: String,
1563 pub features: Option<&'feat Features>,
1564 pub recursion_limit: usize,
1565 pub trace_mac: bool,
1566 pub should_test: bool, // If false, strip `#[test]` nodes
1567 pub single_step: bool,
1568 pub keep_macs: bool,
1571 macro_rules! feature_tests {
1572 ($( fn $getter:ident = $field:ident, )*) => {
1574 pub fn $getter(&self) -> bool {
1575 match self.features {
1576 Some(&Features { $field: true, .. }) => true,
1584 impl<'feat> ExpansionConfig<'feat> {
1585 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1589 recursion_limit: 1024,
1598 fn enable_quotes = quote,
1599 fn enable_asm = asm,
1600 fn enable_custom_test_frameworks = custom_test_frameworks,
1601 fn enable_global_asm = global_asm,
1602 fn enable_log_syntax = log_syntax,
1603 fn enable_concat_idents = concat_idents,
1604 fn enable_trace_macros = trace_macros,
1605 fn enable_allow_internal_unstable = allow_internal_unstable,
1606 fn enable_custom_derive = custom_derive,
1607 fn enable_format_args_nl = format_args_nl,
1608 fn macros_in_extern_enabled = macros_in_extern,
1609 fn proc_macro_mod = proc_macro_mod,
1610 fn proc_macro_gen = proc_macro_gen,
1611 fn proc_macro_expr = proc_macro_expr,
1612 fn proc_macro_non_items = proc_macro_non_items,
1615 fn enable_custom_inner_attributes(&self) -> bool {
1616 self.features.map_or(false, |features| {
1617 features.custom_inner_attributes || features.custom_attribute || features.rustc_attrs
1622 // A Marker adds the given mark to the syntax context.
1624 pub struct Marker(pub Mark);
1626 impl Folder for Marker {
1627 fn new_span(&mut self, span: Span) -> Span {
1628 span.apply_mark(self.0)
1631 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1632 noop_fold_mac(mac, self)