1 use crate::ast::{self, Block, Ident, LitKind, NodeId, PatKind, Path};
2 use crate::ast::{MacStmtStyle, StmtKind, ItemKind};
3 use crate::attr::{self, HasAttrs};
4 use crate::source_map::{dummy_spanned, respan};
5 use crate::config::StripUnconfigured;
6 use crate::ext::base::*;
7 use crate::ext::derive::{add_derived_markers, collect_derives};
8 use crate::ext::hygiene::{ExpnId, SyntaxContext, ExpnInfo, ExpnKind};
9 use crate::ext::placeholders::{placeholder, PlaceholderExpander};
10 use crate::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
11 use crate::mut_visit::*;
12 use crate::parse::{DirectoryOwnership, PResult, ParseSess};
13 use crate::parse::token;
14 use crate::parse::parser::Parser;
16 use crate::symbol::{sym, Symbol};
17 use crate::tokenstream::{TokenStream, TokenTree};
18 use crate::visit::{self, Visitor};
19 use crate::util::map_in_place::MapInPlace;
21 use errors::{Applicability, FatalError};
22 use smallvec::{smallvec, SmallVec};
23 use syntax_pos::{Span, DUMMY_SP, FileName};
25 use rustc_data_structures::fx::FxHashMap;
26 use rustc_data_structures::sync::Lrc;
28 use std::io::ErrorKind;
30 use std::ops::DerefMut;
32 use std::path::PathBuf;
34 macro_rules! ast_fragments {
36 $($Kind:ident($AstTy:ty) {
38 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
39 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
43 /// A fragment of AST that can be produced by a single macro expansion.
44 /// Can also serve as an input and intermediate result for macro expansion operations.
45 pub enum AstFragment {
46 OptExpr(Option<P<ast::Expr>>),
50 /// "Discriminant" of an AST fragment.
51 #[derive(Copy, Clone, PartialEq, Eq)]
52 pub enum AstFragmentKind {
57 impl AstFragmentKind {
58 pub fn name(self) -> &'static str {
60 AstFragmentKind::OptExpr => "expression",
61 $(AstFragmentKind::$Kind => $kind_name,)*
65 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
67 AstFragmentKind::OptExpr =>
68 result.make_expr().map(Some).map(AstFragment::OptExpr),
69 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
75 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
77 AstFragment::OptExpr(expr) => expr,
78 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
82 $(pub fn $make_ast(self) -> $AstTy {
84 AstFragment::$Kind(ast) => ast,
85 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
89 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
91 AstFragment::OptExpr(opt_expr) => {
92 visit_clobber(opt_expr, |opt_expr| {
93 if let Some(expr) = opt_expr {
94 vis.filter_map_expr(expr)
100 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
101 $($(AstFragment::$Kind(ast) =>
102 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
106 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
108 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
109 AstFragment::OptExpr(None) => {}
110 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
111 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
112 visitor.$visit_ast_elt(ast_elt);
118 impl<'a, 'b> MutVisitor for MacroExpander<'a, 'b> {
119 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
120 self.expand_fragment(AstFragment::OptExpr(Some(expr))).make_opt_expr()
122 $($(fn $mut_visit_ast(&mut self, ast: &mut $AstTy) {
123 visit_clobber(ast, |ast| self.expand_fragment(AstFragment::$Kind(ast)).$make_ast());
125 $($(fn $flat_map_ast_elt(&mut self, ast_elt: <$AstTy as IntoIterator>::Item) -> $AstTy {
126 self.expand_fragment(AstFragment::$Kind(smallvec![ast_elt])).$make_ast()
130 impl<'a> MacResult for crate::ext::tt::macro_rules::ParserAnyMacro<'a> {
131 $(fn $make_ast(self: Box<crate::ext::tt::macro_rules::ParserAnyMacro<'a>>)
133 Some(self.make(AstFragmentKind::$Kind).$make_ast())
140 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
141 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
142 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
143 Stmts(SmallVec<[ast::Stmt; 1]>) {
144 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
146 Items(SmallVec<[P<ast::Item>; 1]>) {
147 "item"; many fn flat_map_item; fn visit_item; fn make_items;
149 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
150 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
152 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
153 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
155 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
156 "foreign item"; many fn flat_map_foreign_item; fn visit_foreign_item; fn make_foreign_items;
160 impl AstFragmentKind {
161 fn dummy(self, span: Span) -> AstFragment {
162 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
165 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
167 let mut items = items.into_iter();
169 AstFragmentKind::Items =>
170 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
171 AstFragmentKind::ImplItems =>
172 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
173 AstFragmentKind::TraitItems =>
174 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
175 AstFragmentKind::ForeignItems =>
176 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
177 AstFragmentKind::Stmts =>
178 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
179 AstFragmentKind::Expr => AstFragment::Expr(
180 items.next().expect("expected exactly one expression").expect_expr()
182 AstFragmentKind::OptExpr =>
183 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
184 AstFragmentKind::Pat | AstFragmentKind::Ty =>
185 panic!("patterns and types aren't annotatable"),
190 pub struct Invocation {
191 pub kind: InvocationKind,
192 fragment_kind: AstFragmentKind,
193 pub expansion_data: ExpansionData,
196 pub enum InvocationKind {
202 attr: ast::Attribute,
204 // Required for resolving derive helper attributes.
206 // We temporarily report errors for attribute macros placed after derives
212 item_with_markers: Annotatable,
214 /// "Invocation" that contains all derives from an item,
215 /// broken into multiple `Derive` invocations when expanded.
216 /// FIXME: Find a way to remove it.
224 pub fn span(&self) -> Span {
226 InvocationKind::Bang { span, .. } => *span,
227 InvocationKind::Attr { attr, .. } => attr.span,
228 InvocationKind::Derive { path, .. } => path.span,
229 InvocationKind::DeriveContainer { item, .. } => item.span(),
234 pub struct MacroExpander<'a, 'b> {
235 pub cx: &'a mut ExtCtxt<'b>,
236 monotonic: bool, // cf. `cx.monotonic_expander()`
239 impl<'a, 'b> MacroExpander<'a, 'b> {
240 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
241 MacroExpander { cx, monotonic }
244 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
245 let mut module = ModuleData {
246 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
247 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
248 FileName::Real(path) => path,
249 other => PathBuf::from(other.to_string()),
252 module.directory.pop();
253 self.cx.root_path = module.directory.clone();
254 self.cx.current_expansion.module = Rc::new(module);
256 let orig_mod_span = krate.module.inner;
258 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
261 node: ast::ItemKind::Mod(krate.module),
262 ident: Ident::invalid(),
263 id: ast::DUMMY_NODE_ID,
264 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
268 match self.expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
269 Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
271 krate.module = module;
274 // Resolution failed so we return an empty expansion
275 krate.attrs = vec![];
276 krate.module = ast::Mod {
277 inner: orig_mod_span,
284 self.cx.trace_macros_diag();
288 // Fully expand all macro invocations in this AST fragment.
289 fn expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
290 let orig_expansion_data = self.cx.current_expansion.clone();
291 self.cx.current_expansion.depth = 0;
293 // Collect all macro invocations and replace them with placeholders.
294 let (mut fragment_with_placeholders, mut invocations)
295 = self.collect_invocations(input_fragment, &[]);
297 // Optimization: if we resolve all imports now,
298 // we'll be able to immediately resolve most of imported macros.
299 self.resolve_imports();
301 // Resolve paths in all invocations and produce output expanded fragments for them, but
302 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
303 // The output fragments also go through expansion recursively until no invocations are left.
304 // Unresolved macros produce dummy outputs as a recovery measure.
305 invocations.reverse();
306 let mut expanded_fragments = Vec::new();
307 let mut derives: FxHashMap<ExpnId, Vec<_>> = FxHashMap::default();
308 let mut undetermined_invocations = Vec::new();
309 let (mut progress, mut force) = (false, !self.monotonic);
311 let invoc = if let Some(invoc) = invocations.pop() {
314 self.resolve_imports();
315 if undetermined_invocations.is_empty() { break }
316 invocations = mem::take(&mut undetermined_invocations);
317 force = !mem::replace(&mut progress, false);
322 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
323 let ext = match self.cx.resolver.resolve_macro_invocation(&invoc, scope, force) {
325 Err(Indeterminate) => {
326 undetermined_invocations.push(invoc);
332 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
333 self.cx.current_expansion = invoc.expansion_data.clone();
334 self.cx.current_expansion.id = scope;
336 // FIXME(jseyfried): Refactor out the following logic
337 let (expanded_fragment, new_invocations) = if let Some(ext) = ext {
338 let fragment = self.expand_invoc(invoc, &ext.kind);
339 self.collect_invocations(fragment, &[])
340 } else if let InvocationKind::DeriveContainer { derives: traits, item } = invoc.kind {
341 if !item.derive_allowed() {
342 let attr = attr::find_by_name(item.attrs(), sym::derive)
343 .expect("`derive` attribute should exist");
344 let span = attr.span;
345 let mut err = self.cx.mut_span_err(span,
346 "`derive` may only be applied to \
347 structs, enums and unions");
348 if let ast::AttrStyle::Inner = attr.style {
349 let trait_list = traits.iter()
350 .map(|t| t.to_string()).collect::<Vec<_>>();
351 let suggestion = format!("#[derive({})]", trait_list.join(", "));
353 span, "try an outer attribute", suggestion,
354 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
355 Applicability::MaybeIncorrect
361 let mut item = self.fully_configure(item);
362 item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
363 let mut item_with_markers = item.clone();
364 add_derived_markers(&mut self.cx, item.span(), &traits, &mut item_with_markers);
365 let derives = derives.entry(invoc.expansion_data.id).or_default();
367 derives.reserve(traits.len());
368 invocations.reserve(traits.len());
370 let expn_id = ExpnId::fresh(self.cx.current_expansion.id, None);
371 derives.push(expn_id);
372 invocations.push(Invocation {
373 kind: InvocationKind::Derive {
376 item_with_markers: item_with_markers.clone(),
378 fragment_kind: invoc.fragment_kind,
379 expansion_data: ExpansionData {
381 ..invoc.expansion_data.clone()
385 let fragment = invoc.fragment_kind
386 .expect_from_annotatables(::std::iter::once(item_with_markers));
387 self.collect_invocations(fragment, derives)
392 if expanded_fragments.len() < depth {
393 expanded_fragments.push(Vec::new());
395 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
396 if !self.cx.ecfg.single_step {
397 invocations.extend(new_invocations.into_iter().rev());
401 self.cx.current_expansion = orig_expansion_data;
403 // Finally incorporate all the expanded macros into the input AST fragment.
404 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
405 while let Some(expanded_fragments) = expanded_fragments.pop() {
406 for (mark, expanded_fragment) in expanded_fragments.into_iter().rev() {
407 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
408 placeholder_expander.add(NodeId::placeholder_from_expn_id(mark),
409 expanded_fragment, derives);
412 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
413 fragment_with_placeholders
416 fn resolve_imports(&mut self) {
418 self.cx.resolver.resolve_imports();
422 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
423 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
424 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
425 /// prepares data for resolving paths of macro invocations.
426 fn collect_invocations(&mut self, mut fragment: AstFragment, derives: &[ExpnId])
427 -> (AstFragment, Vec<Invocation>) {
428 // Resolve `$crate`s in the fragment for pretty-printing.
429 self.cx.resolver.resolve_dollar_crates();
432 let mut collector = InvocationCollector {
433 cfg: StripUnconfigured {
434 sess: self.cx.parse_sess,
435 features: self.cx.ecfg.features,
438 invocations: Vec::new(),
439 monotonic: self.monotonic,
441 fragment.mut_visit_with(&mut collector);
442 collector.invocations
446 self.cx.resolver.visit_ast_fragment_with_placeholders(
447 self.cx.current_expansion.id, &fragment, derives);
450 (fragment, invocations)
453 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
454 let mut cfg = StripUnconfigured {
455 sess: self.cx.parse_sess,
456 features: self.cx.ecfg.features,
458 // Since the item itself has already been configured by the InvocationCollector,
459 // we know that fold result vector will contain exactly one element
461 Annotatable::Item(item) => {
462 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
464 Annotatable::TraitItem(item) => {
465 Annotatable::TraitItem(
466 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
468 Annotatable::ImplItem(item) => {
469 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
471 Annotatable::ForeignItem(item) => {
472 Annotatable::ForeignItem(
473 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
476 Annotatable::Stmt(stmt) => {
477 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
479 Annotatable::Expr(mut expr) => {
480 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
485 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
486 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
487 if fragment_kind == AstFragmentKind::ForeignItems && !self.cx.ecfg.macros_in_extern() {
488 if let SyntaxExtensionKind::NonMacroAttr { .. } = ext {} else {
489 emit_feature_err(&self.cx.parse_sess, sym::macros_in_extern,
490 span, GateIssue::Language,
491 "macro invocations in `extern {}` blocks are experimental");
495 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
496 let info = self.cx.current_expansion.id.expn_info().unwrap();
497 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
498 let mut err = self.cx.struct_span_err(info.call_site,
499 &format!("recursion limit reached while expanding the macro `{}`",
502 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
505 self.cx.trace_macros_diag();
510 InvocationKind::Bang { mac, .. } => match ext {
511 SyntaxExtensionKind::Bang(expander) => {
512 self.gate_proc_macro_expansion_kind(span, fragment_kind);
513 let tok_result = expander.expand(self.cx, span, mac.node.stream());
515 self.parse_ast_fragment(tok_result, fragment_kind, &mac.node.path, span);
516 self.gate_proc_macro_expansion(span, &result);
519 SyntaxExtensionKind::LegacyBang(expander) => {
520 let tok_result = expander.expand(self.cx, span, mac.node.stream());
521 if let Some(result) = fragment_kind.make_from(tok_result) {
524 let msg = format!("non-{kind} macro in {kind} position: {path}",
525 kind = fragment_kind.name(), path = mac.node.path);
526 self.cx.span_err(span, &msg);
527 self.cx.trace_macros_diag();
528 fragment_kind.dummy(span)
533 InvocationKind::Attr { attr, mut item, .. } => match ext {
534 SyntaxExtensionKind::Attr(expander) => {
535 self.gate_proc_macro_attr_item(span, &item);
536 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
537 Annotatable::Item(item) => token::NtItem(item),
538 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
539 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
540 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
541 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
542 Annotatable::Expr(expr) => token::NtExpr(expr),
543 })), DUMMY_SP).into();
544 let input = self.extract_proc_macro_attr_input(attr.tokens, span);
545 let tok_result = expander.expand(self.cx, span, input, item_tok);
546 let res = self.parse_ast_fragment(tok_result, fragment_kind, &attr.path, span);
547 self.gate_proc_macro_expansion(span, &res);
550 SyntaxExtensionKind::LegacyAttr(expander) => {
551 match attr.parse_meta(self.cx.parse_sess) {
553 let item = expander.expand(self.cx, span, &meta, item);
554 fragment_kind.expect_from_annotatables(item)
558 fragment_kind.dummy(span)
562 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
563 attr::mark_known(&attr);
565 attr::mark_used(&attr);
567 item.visit_attrs(|attrs| attrs.push(attr));
568 fragment_kind.expect_from_annotatables(iter::once(item))
572 InvocationKind::Derive { path, item, item_with_markers } => match ext {
573 SyntaxExtensionKind::Derive(expander) |
574 SyntaxExtensionKind::LegacyDerive(expander) => {
575 let (path, item) = match ext {
576 SyntaxExtensionKind::LegacyDerive(..) => (path, item_with_markers),
579 if !item.derive_allowed() {
580 return fragment_kind.dummy(span);
582 let meta = ast::MetaItem { node: ast::MetaItemKind::Word, span, path };
583 let span = span.with_ctxt(self.cx.backtrace());
584 let items = expander.expand(self.cx, span, &meta, item);
585 fragment_kind.expect_from_annotatables(items)
589 InvocationKind::DeriveContainer { .. } => unreachable!()
593 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
594 let mut trees = tokens.trees();
596 Some(TokenTree::Delimited(_, _, tts)) => {
597 if trees.next().is_none() {
601 Some(TokenTree::Token(..)) => {}
602 None => return TokenStream::empty(),
604 self.cx.span_err(span, "custom attribute invocations must be \
605 of the form `#[foo]` or `#[foo(..)]`, the macro name must only be \
606 followed by a delimiter token");
610 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
611 let (kind, gate) = match *item {
612 Annotatable::Item(ref item) => {
614 ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
615 ItemKind::Mod(_) => ("modules", sym::proc_macro_hygiene),
619 Annotatable::TraitItem(_) => return,
620 Annotatable::ImplItem(_) => return,
621 Annotatable::ForeignItem(_) => return,
622 Annotatable::Stmt(_) |
623 Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
624 Annotatable::Stmt(_) => ("statements", sym::proc_macro_hygiene),
625 Annotatable::Expr(_) => ("expressions", sym::proc_macro_hygiene),
632 &format!("custom attributes cannot be applied to {}", kind),
636 fn gate_proc_macro_expansion(&self, span: Span, fragment: &AstFragment) {
637 if self.cx.ecfg.proc_macro_hygiene() {
641 fragment.visit_with(&mut DisallowMacros {
643 parse_sess: self.cx.parse_sess,
646 struct DisallowMacros<'a> {
648 parse_sess: &'a ParseSess,
651 impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
652 fn visit_item(&mut self, i: &'ast ast::Item) {
653 if let ast::ItemKind::MacroDef(_) = i.node {
656 sym::proc_macro_hygiene,
659 "procedural macros cannot expand to macro definitions",
662 visit::walk_item(self, i);
665 fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
671 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
672 let kind = match kind {
673 AstFragmentKind::Expr => "expressions",
674 AstFragmentKind::OptExpr => "expressions",
675 AstFragmentKind::Pat => "patterns",
676 AstFragmentKind::Ty => "types",
677 AstFragmentKind::Stmts => "statements",
678 AstFragmentKind::Items => return,
679 AstFragmentKind::TraitItems => return,
680 AstFragmentKind::ImplItems => return,
681 AstFragmentKind::ForeignItems => return,
683 if self.cx.ecfg.proc_macro_hygiene() {
688 sym::proc_macro_hygiene,
691 &format!("procedural macros cannot be expanded to {}", kind),
695 fn parse_ast_fragment(&mut self,
697 kind: AstFragmentKind,
701 let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
702 match parser.parse_ast_fragment(kind, false) {
704 parser.ensure_complete_parse(path, kind.name(), span);
710 self.cx.trace_macros_diag();
717 impl<'a> Parser<'a> {
718 pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
719 -> PResult<'a, AstFragment> {
721 AstFragmentKind::Items => {
722 let mut items = SmallVec::new();
723 while let Some(item) = self.parse_item()? {
726 AstFragment::Items(items)
728 AstFragmentKind::TraitItems => {
729 let mut items = SmallVec::new();
730 while self.token != token::Eof {
731 items.push(self.parse_trait_item(&mut false)?);
733 AstFragment::TraitItems(items)
735 AstFragmentKind::ImplItems => {
736 let mut items = SmallVec::new();
737 while self.token != token::Eof {
738 items.push(self.parse_impl_item(&mut false)?);
740 AstFragment::ImplItems(items)
742 AstFragmentKind::ForeignItems => {
743 let mut items = SmallVec::new();
744 while self.token != token::Eof {
745 items.push(self.parse_foreign_item(DUMMY_SP)?);
747 AstFragment::ForeignItems(items)
749 AstFragmentKind::Stmts => {
750 let mut stmts = SmallVec::new();
751 while self.token != token::Eof &&
752 // won't make progress on a `}`
753 self.token != token::CloseDelim(token::Brace) {
754 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
758 AstFragment::Stmts(stmts)
760 AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
761 AstFragmentKind::OptExpr => {
762 if self.token != token::Eof {
763 AstFragment::OptExpr(Some(self.parse_expr()?))
765 AstFragment::OptExpr(None)
768 AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
769 AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat(None)?),
773 pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
774 if self.token != token::Eof {
775 let msg = format!("macro expansion ignores token `{}` and any following",
776 self.this_token_to_string());
777 // Avoid emitting backtrace info twice.
778 let def_site_span = self.token.span.with_ctxt(SyntaxContext::empty());
779 let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
780 err.span_label(span, "caused by the macro expansion here");
782 "the usage of `{}!` is likely invalid in {} context",
787 let semi_span = self.sess.source_map().next_point(span);
789 let semi_full_span = semi_span.to(self.sess.source_map().next_point(semi_span));
790 match self.sess.source_map().span_to_snippet(semi_full_span) {
791 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
794 "you might be missing a semicolon here",
796 Applicability::MaybeIncorrect,
806 struct InvocationCollector<'a, 'b> {
807 cx: &'a mut ExtCtxt<'b>,
808 cfg: StripUnconfigured<'a>,
809 invocations: Vec<Invocation>,
813 impl<'a, 'b> InvocationCollector<'a, 'b> {
814 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
815 // Expansion info for all the collected invocations is set upon their resolution,
816 // with exception of the derive container case which is not resolved and can get
817 // its expansion info immediately.
818 let expn_info = match &kind {
819 InvocationKind::DeriveContainer { item, .. } => Some(ExpnInfo::default(
820 ExpnKind::Macro(MacroKind::Attr, sym::derive),
821 item.span(), self.cx.parse_sess.edition,
825 let expn_id = ExpnId::fresh(self.cx.current_expansion.id, expn_info);
826 self.invocations.push(Invocation {
829 expansion_data: ExpansionData {
831 depth: self.cx.current_expansion.depth + 1,
832 ..self.cx.current_expansion.clone()
835 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
838 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
839 self.collect(kind, InvocationKind::Bang { mac, span })
842 fn collect_attr(&mut self,
843 attr: Option<ast::Attribute>,
846 kind: AstFragmentKind,
849 self.collect(kind, match attr {
850 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
851 None => InvocationKind::DeriveContainer { derives, item },
855 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
856 -> Option<ast::Attribute> {
857 let attr = attrs.iter()
859 if a.path == sym::derive {
860 *after_derive = true;
862 !attr::is_known(a) && !is_builtin_attr(a)
864 .map(|i| attrs.remove(i));
865 if let Some(attr) = &attr {
866 if !self.cx.ecfg.custom_inner_attributes() &&
867 attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
868 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
869 attr.span, GateIssue::Language,
870 "non-builtin inner attributes are unstable");
876 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
877 fn classify_item<T>(&mut self, item: &mut T)
878 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
881 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
883 item.visit_attrs(|mut attrs| {
884 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
885 traits = collect_derives(&mut self.cx, &mut attrs);
888 (attr, traits, after_derive)
891 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
892 /// to the unused-attributes lint (making it an error on statements and expressions
893 /// is a breaking change)
894 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
895 -> (Option<ast::Attribute>, /* after_derive */ bool) {
896 let (mut attr, mut after_derive) = (None, false);
898 nonitem.visit_attrs(|mut attrs| {
899 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
905 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
906 self.cfg.configure(node)
909 // Detect use of feature-gated or invalid attributes on macro invocations
910 // since they will not be detected after macro expansion.
911 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
912 let features = self.cx.ecfg.features.unwrap();
913 for attr in attrs.iter() {
914 self.check_attribute_inner(attr, features);
916 // macros are expanded before any lint passes so this warning has to be hardcoded
917 if attr.path == sym::derive {
918 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
919 .note("this may become a hard error in a future release")
925 fn check_attribute(&mut self, at: &ast::Attribute) {
926 let features = self.cx.ecfg.features.unwrap();
927 self.check_attribute_inner(at, features);
930 fn check_attribute_inner(&mut self, at: &ast::Attribute, features: &Features) {
931 feature_gate::check_attribute(at, self.cx.parse_sess, features);
935 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
936 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
937 self.cfg.configure_expr(expr);
938 visit_clobber(expr.deref_mut(), |mut expr| {
939 self.cfg.configure_expr_kind(&mut expr.node);
941 // ignore derives so they remain unused
942 let (attr, after_derive) = self.classify_nonitem(&mut expr);
945 // Collect the invoc regardless of whether or not attributes are permitted here
946 // expansion will eat the attribute so it won't error later.
947 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
949 // AstFragmentKind::Expr requires the macro to emit an expression.
950 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
951 AstFragmentKind::Expr, after_derive)
956 if let ast::ExprKind::Mac(mac) = expr.node {
957 self.check_attributes(&expr.attrs);
958 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
962 noop_visit_expr(&mut expr, self);
968 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
969 let expr = configure!(self, expr);
970 expr.filter_map(|mut expr| {
971 self.cfg.configure_expr_kind(&mut expr.node);
973 // Ignore derives so they remain unused.
974 let (attr, after_derive) = self.classify_nonitem(&mut expr);
977 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
979 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
980 AstFragmentKind::OptExpr, after_derive)
982 .map(|expr| expr.into_inner())
985 if let ast::ExprKind::Mac(mac) = expr.node {
986 self.check_attributes(&expr.attrs);
987 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
989 .map(|expr| expr.into_inner())
991 Some({ noop_visit_expr(&mut expr, self); expr })
996 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
997 self.cfg.configure_pat(pat);
999 PatKind::Mac(_) => {}
1000 _ => return noop_visit_pat(pat, self),
1003 visit_clobber(pat, |mut pat| {
1004 match mem::replace(&mut pat.node, PatKind::Wild) {
1005 PatKind::Mac(mac) =>
1006 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1007 _ => unreachable!(),
1012 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1013 let mut stmt = configure!(self, stmt);
1015 // we'll expand attributes on expressions separately
1016 if !stmt.is_expr() {
1017 let (attr, derives, after_derive) = if stmt.is_item() {
1018 self.classify_item(&mut stmt)
1020 // ignore derives on non-item statements so it falls through
1021 // to the unused-attributes lint
1022 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1023 (attr, vec![], after_derive)
1026 if attr.is_some() || !derives.is_empty() {
1027 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1028 AstFragmentKind::Stmts, after_derive).make_stmts();
1032 if let StmtKind::Mac(mac) = stmt.node {
1033 let (mac, style, attrs) = mac.into_inner();
1034 self.check_attributes(&attrs);
1035 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1038 // If this is a macro invocation with a semicolon, then apply that
1039 // semicolon to the final statement produced by expansion.
1040 if style == MacStmtStyle::Semicolon {
1041 if let Some(stmt) = placeholder.pop() {
1042 placeholder.push(stmt.add_trailing_semicolon());
1049 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1050 let ast::Stmt { id, node, span } = stmt;
1051 noop_flat_map_stmt_kind(node, self).into_iter().map(|node| {
1052 ast::Stmt { id, node, span }
1057 fn visit_block(&mut self, block: &mut P<Block>) {
1058 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1059 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1060 noop_visit_block(block, self);
1061 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1064 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1065 let mut item = configure!(self, item);
1067 let (attr, traits, after_derive) = self.classify_item(&mut item);
1068 if attr.is_some() || !traits.is_empty() {
1069 return self.collect_attr(attr, traits, Annotatable::Item(item),
1070 AstFragmentKind::Items, after_derive).make_items();
1074 ast::ItemKind::Mac(..) => {
1075 self.check_attributes(&item.attrs);
1076 item.and_then(|item| match item.node {
1077 ItemKind::Mac(mac) => self.collect(
1078 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1080 _ => unreachable!(),
1083 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1084 if item.ident == Ident::invalid() {
1085 return noop_flat_map_item(item, self);
1088 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1089 let mut module = (*self.cx.current_expansion.module).clone();
1090 module.mod_path.push(item.ident);
1092 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1093 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1094 // Thus, if `inner` is the dummy span, we know the module is inline.
1095 let inline_module = item.span.contains(inner) || inner.is_dummy();
1098 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1099 self.cx.current_expansion.directory_ownership =
1100 DirectoryOwnership::Owned { relative: None };
1101 module.directory.push(&*path.as_str());
1103 module.directory.push(&*item.ident.as_str());
1106 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1107 let mut path = match path {
1108 FileName::Real(path) => path,
1109 other => PathBuf::from(other.to_string()),
1111 let directory_ownership = match path.file_name().unwrap().to_str() {
1112 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1113 Some(_) => DirectoryOwnership::Owned {
1114 relative: Some(item.ident),
1116 None => DirectoryOwnership::UnownedViaMod(false),
1119 module.directory = path;
1120 self.cx.current_expansion.directory_ownership = directory_ownership;
1124 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1125 let result = noop_flat_map_item(item, self);
1126 self.cx.current_expansion.module = orig_module;
1127 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1131 _ => noop_flat_map_item(item, self),
1135 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1136 let mut item = configure!(self, item);
1138 let (attr, traits, after_derive) = self.classify_item(&mut item);
1139 if attr.is_some() || !traits.is_empty() {
1140 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1141 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1145 ast::TraitItemKind::Macro(mac) => {
1146 let ast::TraitItem { attrs, span, .. } = item;
1147 self.check_attributes(&attrs);
1148 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1150 _ => noop_flat_map_trait_item(item, self),
1154 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1155 let mut item = configure!(self, item);
1157 let (attr, traits, after_derive) = self.classify_item(&mut item);
1158 if attr.is_some() || !traits.is_empty() {
1159 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1160 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1164 ast::ImplItemKind::Macro(mac) => {
1165 let ast::ImplItem { attrs, span, .. } = item;
1166 self.check_attributes(&attrs);
1167 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1169 _ => noop_flat_map_impl_item(item, self),
1173 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1175 ast::TyKind::Mac(_) => {}
1176 _ => return noop_visit_ty(ty, self),
1179 visit_clobber(ty, |mut ty| {
1180 match mem::replace(&mut ty.node, ast::TyKind::Err) {
1181 ast::TyKind::Mac(mac) =>
1182 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1183 _ => unreachable!(),
1188 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1189 self.cfg.configure_foreign_mod(foreign_mod);
1190 noop_visit_foreign_mod(foreign_mod, self);
1193 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1194 -> SmallVec<[ast::ForeignItem; 1]>
1196 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1198 if attr.is_some() || !traits.is_empty() {
1199 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1200 AstFragmentKind::ForeignItems, after_derive)
1201 .make_foreign_items();
1204 if let ast::ForeignItemKind::Macro(mac) = foreign_item.node {
1205 self.check_attributes(&foreign_item.attrs);
1206 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1207 .make_foreign_items();
1210 noop_flat_map_foreign_item(foreign_item, self)
1213 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1215 ast::ItemKind::MacroDef(..) => {}
1217 self.cfg.configure_item_kind(item);
1218 noop_visit_item_kind(item, self);
1223 fn visit_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
1224 self.cfg.configure_generic_params(params);
1225 noop_visit_generic_params(params, self);
1228 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1229 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1230 // contents="file contents")]` attributes
1231 if !at.check_name(sym::doc) {
1232 return noop_visit_attribute(at, self);
1235 if let Some(list) = at.meta_item_list() {
1236 if !list.iter().any(|it| it.check_name(sym::include)) {
1237 return noop_visit_attribute(at, self);
1240 let mut items = vec![];
1242 for mut it in list {
1243 if !it.check_name(sym::include) {
1244 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1248 if let Some(file) = it.value_str() {
1249 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1250 self.check_attribute(&at);
1251 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1252 // avoid loading the file if they haven't enabled the feature
1253 return noop_visit_attribute(at, self);
1256 let filename = self.cx.resolve_path(&*file.as_str(), it.span());
1257 match fs::read_to_string(&filename) {
1259 let src_interned = Symbol::intern(&src);
1261 // Add this input file to the code map to make it available as
1262 // dependency information
1263 self.cx.source_map().new_source_file(filename.into(), src);
1265 let include_info = vec![
1266 ast::NestedMetaItem::MetaItem(
1267 attr::mk_name_value_item_str(
1268 Ident::with_empty_ctxt(sym::file),
1269 dummy_spanned(file),
1272 ast::NestedMetaItem::MetaItem(
1273 attr::mk_name_value_item_str(
1274 Ident::with_empty_ctxt(sym::contents),
1275 dummy_spanned(src_interned),
1280 let include_ident = Ident::with_empty_ctxt(sym::include);
1281 let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info);
1282 items.push(ast::NestedMetaItem::MetaItem(item));
1287 .and_then(|item| item.name_value_literal())
1290 if e.kind() == ErrorKind::InvalidData {
1294 &format!("{} wasn't a utf-8 file", filename.display()),
1296 .span_label(lit.span, "contains invalid utf-8")
1299 let mut err = self.cx.struct_span_err(
1301 &format!("couldn't read {}: {}", filename.display(), e),
1303 err.span_label(lit.span, "couldn't read file");
1310 let mut err = self.cx.struct_span_err(
1312 &format!("expected path to external documentation"),
1315 // Check if the user erroneously used `doc(include(...))` syntax.
1316 let literal = it.meta_item_list().and_then(|list| {
1317 if list.len() == 1 {
1318 list[0].literal().map(|literal| &literal.node)
1324 let (path, applicability) = match &literal {
1325 Some(LitKind::Str(path, ..)) => {
1326 (path.to_string(), Applicability::MachineApplicable)
1328 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1331 err.span_suggestion(
1333 "provide a file path with `=`",
1334 format!("include = \"{}\"", path),
1342 let meta = attr::mk_list_item(DUMMY_SP, Ident::with_empty_ctxt(sym::doc), items);
1344 ast::AttrStyle::Inner => *at = attr::mk_spanned_attr_inner(at.span, at.id, meta),
1345 ast::AttrStyle::Outer => *at = attr::mk_spanned_attr_outer(at.span, at.id, meta),
1348 noop_visit_attribute(at, self)
1352 fn visit_id(&mut self, id: &mut ast::NodeId) {
1354 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1355 *id = self.cx.resolver.next_node_id()
1359 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1360 self.cfg.configure_fn_decl(&mut fn_decl);
1361 noop_visit_fn_decl(fn_decl, self);
1365 pub struct ExpansionConfig<'feat> {
1366 pub crate_name: String,
1367 pub features: Option<&'feat Features>,
1368 pub recursion_limit: usize,
1369 pub trace_mac: bool,
1370 pub should_test: bool, // If false, strip `#[test]` nodes
1371 pub single_step: bool,
1372 pub keep_macs: bool,
1375 impl<'feat> ExpansionConfig<'feat> {
1376 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1380 recursion_limit: 1024,
1388 fn macros_in_extern(&self) -> bool {
1389 self.features.map_or(false, |features| features.macros_in_extern)
1391 fn proc_macro_hygiene(&self) -> bool {
1392 self.features.map_or(false, |features| features.proc_macro_hygiene)
1394 fn custom_inner_attributes(&self) -> bool {
1395 self.features.map_or(false, |features| features.custom_inner_attributes)
1399 // A Marker adds the given mark to the syntax context.
1401 pub struct Marker(pub ExpnId);
1403 impl MutVisitor for Marker {
1404 fn visit_span(&mut self, span: &mut Span) {
1405 *span = span.apply_mark(self.0)
1408 fn visit_mac(&mut self, mac: &mut ast::Mac) {
1409 noop_visit_mac(mac, self)