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;
20 use crate::util::path;
22 use errors::{Applicability, FatalError};
23 use smallvec::{smallvec, SmallVec};
24 use syntax_pos::{Span, DUMMY_SP, FileName};
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_data_structures::sync::Lrc;
29 use std::io::ErrorKind;
31 use std::ops::DerefMut;
33 use std::path::PathBuf;
35 macro_rules! ast_fragments {
37 $($Kind:ident($AstTy:ty) {
39 $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)?
40 $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident;)?
44 /// A fragment of AST that can be produced by a single macro expansion.
45 /// Can also serve as an input and intermediate result for macro expansion operations.
46 pub enum AstFragment {
47 OptExpr(Option<P<ast::Expr>>),
51 /// "Discriminant" of an AST fragment.
52 #[derive(Copy, Clone, PartialEq, Eq)]
53 pub enum AstFragmentKind {
58 impl AstFragmentKind {
59 pub fn name(self) -> &'static str {
61 AstFragmentKind::OptExpr => "expression",
62 $(AstFragmentKind::$Kind => $kind_name,)*
66 fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
68 AstFragmentKind::OptExpr =>
69 result.make_expr().map(Some).map(AstFragment::OptExpr),
70 $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
76 pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
78 AstFragment::OptExpr(expr) => expr,
79 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
83 $(pub fn $make_ast(self) -> $AstTy {
85 AstFragment::$Kind(ast) => ast,
86 _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
90 pub fn mut_visit_with<F: MutVisitor>(&mut self, vis: &mut F) {
92 AstFragment::OptExpr(opt_expr) => {
93 visit_clobber(opt_expr, |opt_expr| {
94 if let Some(expr) = opt_expr {
95 vis.filter_map_expr(expr)
101 $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)*
102 $($(AstFragment::$Kind(ast) =>
103 ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)*
107 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
109 AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
110 AstFragment::OptExpr(None) => {}
111 $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)*
112 $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
113 visitor.$visit_ast_elt(ast_elt);
119 impl<'a, 'b> MutVisitor for MacroExpander<'a, 'b> {
120 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
121 self.expand_fragment(AstFragment::OptExpr(Some(expr))).make_opt_expr()
123 $($(fn $mut_visit_ast(&mut self, ast: &mut $AstTy) {
124 visit_clobber(ast, |ast| self.expand_fragment(AstFragment::$Kind(ast)).$make_ast());
126 $($(fn $flat_map_ast_elt(&mut self, ast_elt: <$AstTy as IntoIterator>::Item) -> $AstTy {
127 self.expand_fragment(AstFragment::$Kind(smallvec![ast_elt])).$make_ast()
131 impl<'a> MacResult for crate::ext::tt::macro_rules::ParserAnyMacro<'a> {
132 $(fn $make_ast(self: Box<crate::ext::tt::macro_rules::ParserAnyMacro<'a>>)
134 Some(self.make(AstFragmentKind::$Kind).$make_ast())
141 Expr(P<ast::Expr>) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; }
142 Pat(P<ast::Pat>) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; }
143 Ty(P<ast::Ty>) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; }
144 Stmts(SmallVec<[ast::Stmt; 1]>) {
145 "statement"; many fn flat_map_stmt; fn visit_stmt; fn make_stmts;
147 Items(SmallVec<[P<ast::Item>; 1]>) {
148 "item"; many fn flat_map_item; fn visit_item; fn make_items;
150 TraitItems(SmallVec<[ast::TraitItem; 1]>) {
151 "trait item"; many fn flat_map_trait_item; fn visit_trait_item; fn make_trait_items;
153 ImplItems(SmallVec<[ast::ImplItem; 1]>) {
154 "impl item"; many fn flat_map_impl_item; fn visit_impl_item; fn make_impl_items;
156 ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
157 "foreign item"; many fn flat_map_foreign_item; fn visit_foreign_item; fn make_foreign_items;
161 impl AstFragmentKind {
162 fn dummy(self, span: Span) -> AstFragment {
163 self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
166 fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
168 let mut items = items.into_iter();
170 AstFragmentKind::Items =>
171 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
172 AstFragmentKind::ImplItems =>
173 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
174 AstFragmentKind::TraitItems =>
175 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
176 AstFragmentKind::ForeignItems =>
177 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
178 AstFragmentKind::Stmts =>
179 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
180 AstFragmentKind::Expr => AstFragment::Expr(
181 items.next().expect("expected exactly one expression").expect_expr()
183 AstFragmentKind::OptExpr =>
184 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
185 AstFragmentKind::Pat | AstFragmentKind::Ty =>
186 panic!("patterns and types aren't annotatable"),
191 pub struct Invocation {
192 pub kind: InvocationKind,
193 fragment_kind: AstFragmentKind,
194 pub expansion_data: ExpansionData,
197 pub enum InvocationKind {
203 attr: ast::Attribute,
205 // Required for resolving derive helper attributes.
207 // We temporarily report errors for attribute macros placed after derives
213 item_with_markers: Annotatable,
215 /// "Invocation" that contains all derives from an item,
216 /// broken into multiple `Derive` invocations when expanded.
217 /// FIXME: Find a way to remove it.
225 pub fn span(&self) -> Span {
227 InvocationKind::Bang { span, .. } => *span,
228 InvocationKind::Attr { attr, .. } => attr.span,
229 InvocationKind::Derive { path, .. } => path.span,
230 InvocationKind::DeriveContainer { item, .. } => item.span(),
235 pub struct MacroExpander<'a, 'b> {
236 pub cx: &'a mut ExtCtxt<'b>,
237 monotonic: bool, // cf. `cx.monotonic_expander()`
240 impl<'a, 'b> MacroExpander<'a, 'b> {
241 pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
242 MacroExpander { cx, monotonic }
245 pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
246 let mut module = ModuleData {
247 mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
248 directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
249 FileName::Real(path) => path,
250 other => PathBuf::from(other.to_string()),
253 module.directory.pop();
254 self.cx.root_path = module.directory.clone();
255 self.cx.current_expansion.module = Rc::new(module);
257 let orig_mod_span = krate.module.inner;
259 let krate_item = AstFragment::Items(smallvec![P(ast::Item {
262 node: ast::ItemKind::Mod(krate.module),
263 ident: Ident::invalid(),
264 id: ast::DUMMY_NODE_ID,
265 vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
269 match self.expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
270 Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
272 krate.module = module;
275 // Resolution failed so we return an empty expansion
276 krate.attrs = vec![];
277 krate.module = ast::Mod {
278 inner: orig_mod_span,
285 self.cx.trace_macros_diag();
289 // Fully expand all macro invocations in this AST fragment.
290 fn expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
291 let orig_expansion_data = self.cx.current_expansion.clone();
292 self.cx.current_expansion.depth = 0;
294 // Collect all macro invocations and replace them with placeholders.
295 let (mut fragment_with_placeholders, mut invocations)
296 = self.collect_invocations(input_fragment, &[]);
298 // Optimization: if we resolve all imports now,
299 // we'll be able to immediately resolve most of imported macros.
300 self.resolve_imports();
302 // Resolve paths in all invocations and produce output expanded fragments for them, but
303 // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
304 // The output fragments also go through expansion recursively until no invocations are left.
305 // Unresolved macros produce dummy outputs as a recovery measure.
306 invocations.reverse();
307 let mut expanded_fragments = Vec::new();
308 let mut derives: FxHashMap<ExpnId, Vec<_>> = FxHashMap::default();
309 let mut undetermined_invocations = Vec::new();
310 let (mut progress, mut force) = (false, !self.monotonic);
312 let invoc = if let Some(invoc) = invocations.pop() {
315 self.resolve_imports();
316 if undetermined_invocations.is_empty() { break }
317 invocations = mem::take(&mut undetermined_invocations);
318 force = !mem::replace(&mut progress, false);
323 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
324 let ext = match self.cx.resolver.resolve_macro_invocation(&invoc, scope, force) {
326 Err(Indeterminate) => {
327 undetermined_invocations.push(invoc);
333 let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
334 self.cx.current_expansion = invoc.expansion_data.clone();
335 self.cx.current_expansion.id = scope;
337 // FIXME(jseyfried): Refactor out the following logic
338 let (expanded_fragment, new_invocations) = if let Some(ext) = ext {
339 let fragment = self.expand_invoc(invoc, &ext.kind);
340 self.collect_invocations(fragment, &[])
341 } else if let InvocationKind::DeriveContainer { derives: traits, item } = invoc.kind {
342 if !item.derive_allowed() {
343 let attr = attr::find_by_name(item.attrs(), sym::derive)
344 .expect("`derive` attribute should exist");
345 let span = attr.span;
346 let mut err = self.cx.mut_span_err(span,
347 "`derive` may only be applied to \
348 structs, enums and unions");
349 if let ast::AttrStyle::Inner = attr.style {
350 let trait_list = traits.iter()
351 .map(|t| t.to_string()).collect::<Vec<_>>();
352 let suggestion = format!("#[derive({})]", trait_list.join(", "));
354 span, "try an outer attribute", suggestion,
355 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
356 Applicability::MaybeIncorrect
362 let mut item = self.fully_configure(item);
363 item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
364 let mut item_with_markers = item.clone();
365 add_derived_markers(&mut self.cx, item.span(), &traits, &mut item_with_markers);
366 let derives = derives.entry(invoc.expansion_data.id).or_default();
368 derives.reserve(traits.len());
369 invocations.reserve(traits.len());
371 let expn_id = ExpnId::fresh(self.cx.current_expansion.id, None);
372 derives.push(expn_id);
373 invocations.push(Invocation {
374 kind: InvocationKind::Derive {
377 item_with_markers: item_with_markers.clone(),
379 fragment_kind: invoc.fragment_kind,
380 expansion_data: ExpansionData {
382 ..invoc.expansion_data.clone()
386 let fragment = invoc.fragment_kind
387 .expect_from_annotatables(::std::iter::once(item_with_markers));
388 self.collect_invocations(fragment, derives)
393 if expanded_fragments.len() < depth {
394 expanded_fragments.push(Vec::new());
396 expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
397 if !self.cx.ecfg.single_step {
398 invocations.extend(new_invocations.into_iter().rev());
402 self.cx.current_expansion = orig_expansion_data;
404 // Finally incorporate all the expanded macros into the input AST fragment.
405 let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
406 while let Some(expanded_fragments) = expanded_fragments.pop() {
407 for (mark, expanded_fragment) in expanded_fragments.into_iter().rev() {
408 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
409 placeholder_expander.add(NodeId::placeholder_from_expn_id(mark),
410 expanded_fragment, derives);
413 fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
414 fragment_with_placeholders
417 fn resolve_imports(&mut self) {
419 self.cx.resolver.resolve_imports();
423 /// Collects all macro invocations reachable at this time in this AST fragment, and replace
424 /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
425 /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
426 /// prepares data for resolving paths of macro invocations.
427 fn collect_invocations(&mut self, mut fragment: AstFragment, derives: &[ExpnId])
428 -> (AstFragment, Vec<Invocation>) {
429 // Resolve `$crate`s in the fragment for pretty-printing.
430 self.cx.resolver.resolve_dollar_crates();
433 let mut collector = InvocationCollector {
434 cfg: StripUnconfigured {
435 sess: self.cx.parse_sess,
436 features: self.cx.ecfg.features,
439 invocations: Vec::new(),
440 monotonic: self.monotonic,
442 fragment.mut_visit_with(&mut collector);
443 collector.invocations
447 self.cx.resolver.visit_ast_fragment_with_placeholders(
448 self.cx.current_expansion.id, &fragment, derives);
451 (fragment, invocations)
454 fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
455 let mut cfg = StripUnconfigured {
456 sess: self.cx.parse_sess,
457 features: self.cx.ecfg.features,
459 // Since the item itself has already been configured by the InvocationCollector,
460 // we know that fold result vector will contain exactly one element
462 Annotatable::Item(item) => {
463 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
465 Annotatable::TraitItem(item) => {
466 Annotatable::TraitItem(
467 item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
469 Annotatable::ImplItem(item) => {
470 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
472 Annotatable::ForeignItem(item) => {
473 Annotatable::ForeignItem(
474 item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
477 Annotatable::Stmt(stmt) => {
478 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
480 Annotatable::Expr(mut expr) => {
481 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
486 fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
487 let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
488 if fragment_kind == AstFragmentKind::ForeignItems && !self.cx.ecfg.macros_in_extern() {
489 if let SyntaxExtensionKind::NonMacroAttr { .. } = ext {} else {
490 emit_feature_err(&self.cx.parse_sess, sym::macros_in_extern,
491 span, GateIssue::Language,
492 "macro invocations in `extern {}` blocks are experimental");
496 if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
497 let info = self.cx.current_expansion.id.expn_info().unwrap();
498 let suggested_limit = self.cx.ecfg.recursion_limit * 2;
499 let mut err = self.cx.struct_span_err(info.call_site,
500 &format!("recursion limit reached while expanding the macro `{}`",
503 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
506 self.cx.trace_macros_diag();
511 InvocationKind::Bang { mac, .. } => match ext {
512 SyntaxExtensionKind::Bang(expander) => {
513 self.gate_proc_macro_expansion_kind(span, fragment_kind);
514 let tok_result = expander.expand(self.cx, span, mac.node.stream());
516 self.parse_ast_fragment(tok_result, fragment_kind, &mac.node.path, span);
517 self.gate_proc_macro_expansion(span, &result);
520 SyntaxExtensionKind::LegacyBang(expander) => {
521 let tok_result = expander.expand(self.cx, span, mac.node.stream());
522 if let Some(result) = fragment_kind.make_from(tok_result) {
525 let msg = format!("non-{kind} macro in {kind} position: {path}",
526 kind = fragment_kind.name(), path = mac.node.path);
527 self.cx.span_err(span, &msg);
528 self.cx.trace_macros_diag();
529 fragment_kind.dummy(span)
534 InvocationKind::Attr { attr, mut item, .. } => match ext {
535 SyntaxExtensionKind::Attr(expander) => {
536 self.gate_proc_macro_attr_item(span, &item);
537 let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
538 Annotatable::Item(item) => token::NtItem(item),
539 Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
540 Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
541 Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
542 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
543 Annotatable::Expr(expr) => token::NtExpr(expr),
544 })), DUMMY_SP).into();
545 let input = self.extract_proc_macro_attr_input(attr.tokens, span);
546 let tok_result = expander.expand(self.cx, span, input, item_tok);
547 let res = self.parse_ast_fragment(tok_result, fragment_kind, &attr.path, span);
548 self.gate_proc_macro_expansion(span, &res);
551 SyntaxExtensionKind::LegacyAttr(expander) => {
552 match attr.parse_meta(self.cx.parse_sess) {
554 let item = expander.expand(self.cx, span, &meta, item);
555 fragment_kind.expect_from_annotatables(item)
559 fragment_kind.dummy(span)
563 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
564 attr::mark_known(&attr);
566 attr::mark_used(&attr);
568 item.visit_attrs(|attrs| attrs.push(attr));
569 fragment_kind.expect_from_annotatables(iter::once(item))
573 InvocationKind::Derive { path, item, item_with_markers } => match ext {
574 SyntaxExtensionKind::Derive(expander) |
575 SyntaxExtensionKind::LegacyDerive(expander) => {
576 let (path, item) = match ext {
577 SyntaxExtensionKind::LegacyDerive(..) => (path, item_with_markers),
580 if !item.derive_allowed() {
581 return fragment_kind.dummy(span);
583 let meta = ast::MetaItem { node: ast::MetaItemKind::Word, span, path };
584 let span = span.with_ctxt(self.cx.backtrace());
585 let items = expander.expand(self.cx, span, &meta, item);
586 fragment_kind.expect_from_annotatables(items)
590 InvocationKind::DeriveContainer { .. } => unreachable!()
594 fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
595 let mut trees = tokens.trees();
597 Some(TokenTree::Delimited(_, _, tts)) => {
598 if trees.next().is_none() {
602 Some(TokenTree::Token(..)) => {}
603 None => return TokenStream::empty(),
605 self.cx.span_err(span, "custom attribute invocations must be \
606 of the form #[foo] or #[foo(..)], the macro name must only be \
607 followed by a delimiter token");
611 fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
612 let (kind, gate) = match *item {
613 Annotatable::Item(ref item) => {
615 ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
616 ItemKind::Mod(_) => ("modules", sym::proc_macro_hygiene),
620 Annotatable::TraitItem(_) => return,
621 Annotatable::ImplItem(_) => return,
622 Annotatable::ForeignItem(_) => return,
623 Annotatable::Stmt(_) |
624 Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
625 Annotatable::Stmt(_) => ("statements", sym::proc_macro_hygiene),
626 Annotatable::Expr(_) => ("expressions", sym::proc_macro_hygiene),
633 &format!("custom attributes cannot be applied to {}", kind),
637 fn gate_proc_macro_expansion(&self, span: Span, fragment: &AstFragment) {
638 if self.cx.ecfg.proc_macro_hygiene() {
642 fragment.visit_with(&mut DisallowMacros {
644 parse_sess: self.cx.parse_sess,
647 struct DisallowMacros<'a> {
649 parse_sess: &'a ParseSess,
652 impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
653 fn visit_item(&mut self, i: &'ast ast::Item) {
654 if let ast::ItemKind::MacroDef(_) = i.node {
657 sym::proc_macro_hygiene,
660 "procedural macros cannot expand to macro definitions",
663 visit::walk_item(self, i);
666 fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
672 fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
673 let kind = match kind {
674 AstFragmentKind::Expr => "expressions",
675 AstFragmentKind::OptExpr => "expressions",
676 AstFragmentKind::Pat => "patterns",
677 AstFragmentKind::Ty => "types",
678 AstFragmentKind::Stmts => "statements",
679 AstFragmentKind::Items => return,
680 AstFragmentKind::TraitItems => return,
681 AstFragmentKind::ImplItems => return,
682 AstFragmentKind::ForeignItems => return,
684 if self.cx.ecfg.proc_macro_hygiene() {
689 sym::proc_macro_hygiene,
692 &format!("procedural macros cannot be expanded to {}", kind),
696 fn parse_ast_fragment(&mut self,
698 kind: AstFragmentKind,
702 let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
703 match parser.parse_ast_fragment(kind, false) {
705 parser.ensure_complete_parse(path, kind.name(), span);
711 self.cx.trace_macros_diag();
718 impl<'a> Parser<'a> {
719 pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
720 -> PResult<'a, AstFragment> {
722 AstFragmentKind::Items => {
723 let mut items = SmallVec::new();
724 while let Some(item) = self.parse_item()? {
727 AstFragment::Items(items)
729 AstFragmentKind::TraitItems => {
730 let mut items = SmallVec::new();
731 while self.token != token::Eof {
732 items.push(self.parse_trait_item(&mut false)?);
734 AstFragment::TraitItems(items)
736 AstFragmentKind::ImplItems => {
737 let mut items = SmallVec::new();
738 while self.token != token::Eof {
739 items.push(self.parse_impl_item(&mut false)?);
741 AstFragment::ImplItems(items)
743 AstFragmentKind::ForeignItems => {
744 let mut items = SmallVec::new();
745 while self.token != token::Eof {
746 items.push(self.parse_foreign_item(DUMMY_SP)?);
748 AstFragment::ForeignItems(items)
750 AstFragmentKind::Stmts => {
751 let mut stmts = SmallVec::new();
752 while self.token != token::Eof &&
753 // won't make progress on a `}`
754 self.token != token::CloseDelim(token::Brace) {
755 if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
759 AstFragment::Stmts(stmts)
761 AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
762 AstFragmentKind::OptExpr => {
763 if self.token != token::Eof {
764 AstFragment::OptExpr(Some(self.parse_expr()?))
766 AstFragment::OptExpr(None)
769 AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
770 AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat(None)?),
774 pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
775 if self.token != token::Eof {
776 let msg = format!("macro expansion ignores token `{}` and any following",
777 self.this_token_to_string());
778 // Avoid emitting backtrace info twice.
779 let def_site_span = self.token.span.with_ctxt(SyntaxContext::empty());
780 let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
781 err.span_label(span, "caused by the macro expansion here");
783 "the usage of `{}!` is likely invalid in {} context",
788 let semi_span = self.sess.source_map().next_point(span);
790 let semi_full_span = semi_span.to(self.sess.source_map().next_point(semi_span));
791 match self.sess.source_map().span_to_snippet(semi_full_span) {
792 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
795 "you might be missing a semicolon here",
797 Applicability::MaybeIncorrect,
807 struct InvocationCollector<'a, 'b> {
808 cx: &'a mut ExtCtxt<'b>,
809 cfg: StripUnconfigured<'a>,
810 invocations: Vec<Invocation>,
814 impl<'a, 'b> InvocationCollector<'a, 'b> {
815 fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
816 // Expansion info for all the collected invocations is set upon their resolution,
817 // with exception of the derive container case which is not resolved and can get
818 // its expansion info immediately.
819 let expn_info = match &kind {
820 InvocationKind::DeriveContainer { item, .. } => Some(ExpnInfo::default(
821 ExpnKind::Macro(MacroKind::Attr, sym::derive),
822 item.span(), self.cx.parse_sess.edition,
826 let expn_id = ExpnId::fresh(self.cx.current_expansion.id, expn_info);
827 self.invocations.push(Invocation {
830 expansion_data: ExpansionData {
832 depth: self.cx.current_expansion.depth + 1,
833 ..self.cx.current_expansion.clone()
836 placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
839 fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
840 self.collect(kind, InvocationKind::Bang { mac, span })
843 fn collect_attr(&mut self,
844 attr: Option<ast::Attribute>,
847 kind: AstFragmentKind,
850 self.collect(kind, match attr {
851 Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
852 None => InvocationKind::DeriveContainer { derives, item },
856 fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
857 -> Option<ast::Attribute> {
858 let attr = attrs.iter()
860 if a.path == sym::derive {
861 *after_derive = true;
863 !attr::is_known(a) && !is_builtin_attr(a)
865 .map(|i| attrs.remove(i));
866 if let Some(attr) = &attr {
867 if !self.cx.ecfg.custom_inner_attributes() &&
868 attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
869 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
870 attr.span, GateIssue::Language,
871 "non-builtin inner attributes are unstable");
877 /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
878 fn classify_item<T>(&mut self, item: &mut T)
879 -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
882 let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
884 item.visit_attrs(|mut attrs| {
885 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
886 traits = collect_derives(&mut self.cx, &mut attrs);
889 (attr, traits, after_derive)
892 /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
893 /// to the unused-attributes lint (making it an error on statements and expressions
894 /// is a breaking change)
895 fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
896 -> (Option<ast::Attribute>, /* after_derive */ bool) {
897 let (mut attr, mut after_derive) = (None, false);
899 nonitem.visit_attrs(|mut attrs| {
900 attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
906 fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
907 self.cfg.configure(node)
910 // Detect use of feature-gated or invalid attributes on macro invocations
911 // since they will not be detected after macro expansion.
912 fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
913 let features = self.cx.ecfg.features.unwrap();
914 for attr in attrs.iter() {
915 self.check_attribute_inner(attr, features);
917 // macros are expanded before any lint passes so this warning has to be hardcoded
918 if attr.path == sym::derive {
919 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
920 .note("this may become a hard error in a future release")
926 fn check_attribute(&mut self, at: &ast::Attribute) {
927 let features = self.cx.ecfg.features.unwrap();
928 self.check_attribute_inner(at, features);
931 fn check_attribute_inner(&mut self, at: &ast::Attribute, features: &Features) {
932 feature_gate::check_attribute(at, self.cx.parse_sess, features);
936 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
937 fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
938 self.cfg.configure_expr(expr);
939 visit_clobber(expr.deref_mut(), |mut expr| {
940 self.cfg.configure_expr_kind(&mut expr.node);
942 // ignore derives so they remain unused
943 let (attr, after_derive) = self.classify_nonitem(&mut expr);
946 // Collect the invoc regardless of whether or not attributes are permitted here
947 // expansion will eat the attribute so it won't error later.
948 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
950 // AstFragmentKind::Expr requires the macro to emit an expression.
951 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
952 AstFragmentKind::Expr, after_derive)
957 if let ast::ExprKind::Mac(mac) = expr.node {
958 self.check_attributes(&expr.attrs);
959 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
963 noop_visit_expr(&mut expr, self);
969 fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
970 let expr = configure!(self, expr);
971 expr.filter_map(|mut expr| {
972 self.cfg.configure_expr_kind(&mut expr.node);
974 // Ignore derives so they remain unused.
975 let (attr, after_derive) = self.classify_nonitem(&mut expr);
978 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
980 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
981 AstFragmentKind::OptExpr, after_derive)
983 .map(|expr| expr.into_inner())
986 if let ast::ExprKind::Mac(mac) = expr.node {
987 self.check_attributes(&expr.attrs);
988 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
990 .map(|expr| expr.into_inner())
992 Some({ noop_visit_expr(&mut expr, self); expr })
997 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
998 self.cfg.configure_pat(pat);
1000 PatKind::Mac(_) => {}
1001 _ => return noop_visit_pat(pat, self),
1004 visit_clobber(pat, |mut pat| {
1005 match mem::replace(&mut pat.node, PatKind::Wild) {
1006 PatKind::Mac(mac) =>
1007 self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1008 _ => unreachable!(),
1013 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1014 let mut stmt = configure!(self, stmt);
1016 // we'll expand attributes on expressions separately
1017 if !stmt.is_expr() {
1018 let (attr, derives, after_derive) = if stmt.is_item() {
1019 self.classify_item(&mut stmt)
1021 // ignore derives on non-item statements so it falls through
1022 // to the unused-attributes lint
1023 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1024 (attr, vec![], after_derive)
1027 if attr.is_some() || !derives.is_empty() {
1028 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1029 AstFragmentKind::Stmts, after_derive).make_stmts();
1033 if let StmtKind::Mac(mac) = stmt.node {
1034 let (mac, style, attrs) = mac.into_inner();
1035 self.check_attributes(&attrs);
1036 let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1039 // If this is a macro invocation with a semicolon, then apply that
1040 // semicolon to the final statement produced by expansion.
1041 if style == MacStmtStyle::Semicolon {
1042 if let Some(stmt) = placeholder.pop() {
1043 placeholder.push(stmt.add_trailing_semicolon());
1050 // The placeholder expander gives ids to statements, so we avoid folding the id here.
1051 let ast::Stmt { id, node, span } = stmt;
1052 noop_flat_map_stmt_kind(node, self).into_iter().map(|node| {
1053 ast::Stmt { id, node, span }
1058 fn visit_block(&mut self, block: &mut P<Block>) {
1059 let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1060 self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1061 noop_visit_block(block, self);
1062 self.cx.current_expansion.directory_ownership = old_directory_ownership;
1065 fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1066 let mut item = configure!(self, item);
1068 let (attr, traits, after_derive) = self.classify_item(&mut item);
1069 if attr.is_some() || !traits.is_empty() {
1070 return self.collect_attr(attr, traits, Annotatable::Item(item),
1071 AstFragmentKind::Items, after_derive).make_items();
1075 ast::ItemKind::Mac(..) => {
1076 self.check_attributes(&item.attrs);
1077 item.and_then(|item| match item.node {
1078 ItemKind::Mac(mac) => self.collect(
1079 AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1081 _ => unreachable!(),
1084 ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1085 if item.ident == Ident::invalid() {
1086 return noop_flat_map_item(item, self);
1089 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1090 let mut module = (*self.cx.current_expansion.module).clone();
1091 module.mod_path.push(item.ident);
1093 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1094 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1095 // Thus, if `inner` is the dummy span, we know the module is inline.
1096 let inline_module = item.span.contains(inner) || inner.is_dummy();
1099 if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1100 self.cx.current_expansion.directory_ownership =
1101 DirectoryOwnership::Owned { relative: None };
1102 module.directory.push(&*path.as_str());
1104 module.directory.push(&*item.ident.as_str());
1107 let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1108 let mut path = match path {
1109 FileName::Real(path) => path,
1110 other => PathBuf::from(other.to_string()),
1112 let directory_ownership = match path.file_name().unwrap().to_str() {
1113 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1114 Some(_) => DirectoryOwnership::Owned {
1115 relative: Some(item.ident),
1117 None => DirectoryOwnership::UnownedViaMod(false),
1120 module.directory = path;
1121 self.cx.current_expansion.directory_ownership = directory_ownership;
1125 mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1126 let result = noop_flat_map_item(item, self);
1127 self.cx.current_expansion.module = orig_module;
1128 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1132 _ => noop_flat_map_item(item, self),
1136 fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1137 let mut item = configure!(self, item);
1139 let (attr, traits, after_derive) = self.classify_item(&mut item);
1140 if attr.is_some() || !traits.is_empty() {
1141 return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1142 AstFragmentKind::TraitItems, after_derive).make_trait_items()
1146 ast::TraitItemKind::Macro(mac) => {
1147 let ast::TraitItem { attrs, span, .. } = item;
1148 self.check_attributes(&attrs);
1149 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1151 _ => noop_flat_map_trait_item(item, self),
1155 fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1156 let mut item = configure!(self, item);
1158 let (attr, traits, after_derive) = self.classify_item(&mut item);
1159 if attr.is_some() || !traits.is_empty() {
1160 return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1161 AstFragmentKind::ImplItems, after_derive).make_impl_items();
1165 ast::ImplItemKind::Macro(mac) => {
1166 let ast::ImplItem { attrs, span, .. } = item;
1167 self.check_attributes(&attrs);
1168 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1170 _ => noop_flat_map_impl_item(item, self),
1174 fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1176 ast::TyKind::Mac(_) => {}
1177 _ => return noop_visit_ty(ty, self),
1180 visit_clobber(ty, |mut ty| {
1181 match mem::replace(&mut ty.node, ast::TyKind::Err) {
1182 ast::TyKind::Mac(mac) =>
1183 self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1184 _ => unreachable!(),
1189 fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1190 self.cfg.configure_foreign_mod(foreign_mod);
1191 noop_visit_foreign_mod(foreign_mod, self);
1194 fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1195 -> SmallVec<[ast::ForeignItem; 1]>
1197 let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1199 if attr.is_some() || !traits.is_empty() {
1200 return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1201 AstFragmentKind::ForeignItems, after_derive)
1202 .make_foreign_items();
1205 if let ast::ForeignItemKind::Macro(mac) = foreign_item.node {
1206 self.check_attributes(&foreign_item.attrs);
1207 return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1208 .make_foreign_items();
1211 noop_flat_map_foreign_item(foreign_item, self)
1214 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1216 ast::ItemKind::MacroDef(..) => {}
1218 self.cfg.configure_item_kind(item);
1219 noop_visit_item_kind(item, self);
1224 fn visit_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
1225 self.cfg.configure_generic_params(params);
1226 noop_visit_generic_params(params, self);
1229 fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1230 // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1231 // contents="file contents")]` attributes
1232 if !at.check_name(sym::doc) {
1233 return noop_visit_attribute(at, self);
1236 if let Some(list) = at.meta_item_list() {
1237 if !list.iter().any(|it| it.check_name(sym::include)) {
1238 return noop_visit_attribute(at, self);
1241 let mut items = vec![];
1243 for mut it in list {
1244 if !it.check_name(sym::include) {
1245 items.push({ noop_visit_meta_list_item(&mut it, self); it });
1249 if let Some(file) = it.value_str() {
1250 let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1251 self.check_attribute(&at);
1252 if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1253 // avoid loading the file if they haven't enabled the feature
1254 return noop_visit_attribute(at, self);
1257 let filename = path::resolve(&*file.as_str(), it.span(), self.cx.source_map());
1258 match fs::read_to_string(&filename) {
1260 let src_interned = Symbol::intern(&src);
1262 // Add this input file to the code map to make it available as
1263 // dependency information
1264 self.cx.source_map().new_source_file(filename.into(), src);
1266 let include_info = vec![
1267 ast::NestedMetaItem::MetaItem(
1268 attr::mk_name_value_item_str(
1269 Ident::with_empty_ctxt(sym::file),
1270 dummy_spanned(file),
1273 ast::NestedMetaItem::MetaItem(
1274 attr::mk_name_value_item_str(
1275 Ident::with_empty_ctxt(sym::contents),
1276 dummy_spanned(src_interned),
1281 let include_ident = Ident::with_empty_ctxt(sym::include);
1282 let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info);
1283 items.push(ast::NestedMetaItem::MetaItem(item));
1288 .and_then(|item| item.name_value_literal())
1291 if e.kind() == ErrorKind::InvalidData {
1295 &format!("{} wasn't a utf-8 file", filename.display()),
1297 .span_label(lit.span, "contains invalid utf-8")
1300 let mut err = self.cx.struct_span_err(
1302 &format!("couldn't read {}: {}", filename.display(), e),
1304 err.span_label(lit.span, "couldn't read file");
1311 let mut err = self.cx.struct_span_err(
1313 &format!("expected path to external documentation"),
1316 // Check if the user erroneously used `doc(include(...))` syntax.
1317 let literal = it.meta_item_list().and_then(|list| {
1318 if list.len() == 1 {
1319 list[0].literal().map(|literal| &literal.node)
1325 let (path, applicability) = match &literal {
1326 Some(LitKind::Str(path, ..)) => {
1327 (path.to_string(), Applicability::MachineApplicable)
1329 _ => (String::from("<path>"), Applicability::HasPlaceholders),
1332 err.span_suggestion(
1334 "provide a file path with `=`",
1335 format!("include = \"{}\"", path),
1343 let meta = attr::mk_list_item(DUMMY_SP, Ident::with_empty_ctxt(sym::doc), items);
1345 ast::AttrStyle::Inner => *at = attr::mk_spanned_attr_inner(at.span, at.id, meta),
1346 ast::AttrStyle::Outer => *at = attr::mk_spanned_attr_outer(at.span, at.id, meta),
1349 noop_visit_attribute(at, self)
1353 fn visit_id(&mut self, id: &mut ast::NodeId) {
1355 debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1356 *id = self.cx.resolver.next_node_id()
1360 fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1361 self.cfg.configure_fn_decl(&mut fn_decl);
1362 noop_visit_fn_decl(fn_decl, self);
1366 pub struct ExpansionConfig<'feat> {
1367 pub crate_name: String,
1368 pub features: Option<&'feat Features>,
1369 pub recursion_limit: usize,
1370 pub trace_mac: bool,
1371 pub should_test: bool, // If false, strip `#[test]` nodes
1372 pub single_step: bool,
1373 pub keep_macs: bool,
1376 impl<'feat> ExpansionConfig<'feat> {
1377 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1381 recursion_limit: 1024,
1389 fn macros_in_extern(&self) -> bool {
1390 self.features.map_or(false, |features| features.macros_in_extern)
1392 fn proc_macro_hygiene(&self) -> bool {
1393 self.features.map_or(false, |features| features.proc_macro_hygiene)
1395 fn custom_inner_attributes(&self) -> bool {
1396 self.features.map_or(false, |features| features.custom_inner_attributes)
1400 // A Marker adds the given mark to the syntax context.
1402 pub struct Marker(pub ExpnId);
1404 impl MutVisitor for Marker {
1405 fn visit_span(&mut self, span: &mut Span) {
1406 *span = span.apply_mark(self.0)
1409 fn visit_mac(&mut self, mac: &mut ast::Mac) {
1410 noop_visit_mac(mac, self)