1 use crate::expand::{self, AstFragment, Invocation};
2 use crate::module::DirOwnership;
4 use rustc_ast::attr::MarkedAttrs;
6 use rustc_ast::token::{self, Nonterminal};
7 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream};
8 use rustc_ast::visit::{AssocCtxt, Visitor};
9 use rustc_ast::{self as ast, AstLike, Attribute, Item, NodeId, PatKind};
10 use rustc_attr::{self as attr, Deprecation, Stability};
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::sync::{self, Lrc};
13 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorReported};
14 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
15 use rustc_lint_defs::BuiltinLintDiagnostics;
16 use rustc_parse::{self, nt_to_tokenstream, parser, MACRO_ARGUMENTS};
17 use rustc_session::{parse::ParseSess, Limit, Session};
18 use rustc_span::def_id::{CrateNum, DefId, LocalDefId};
19 use rustc_span::edition::Edition;
20 use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId};
21 use rustc_span::source_map::SourceMap;
22 use rustc_span::symbol::{kw, sym, Ident, Symbol};
23 use rustc_span::{FileName, MultiSpan, Span, DUMMY_SP};
24 use smallvec::{smallvec, SmallVec};
26 use std::default::Default;
28 use std::path::PathBuf;
31 crate use rustc_span::hygiene::MacroKind;
33 // When adding new variants, make sure to
34 // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
35 // to use `assign_id!`
36 #[derive(Debug, Clone)]
37 pub enum Annotatable {
39 TraitItem(P<ast::AssocItem>),
40 ImplItem(P<ast::AssocItem>),
41 ForeignItem(P<ast::ForeignItem>),
45 ExprField(ast::ExprField),
46 PatField(ast::PatField),
47 GenericParam(ast::GenericParam),
49 FieldDef(ast::FieldDef),
50 Variant(ast::Variant),
55 pub fn span(&self) -> Span {
57 Annotatable::Item(ref item) => item.span,
58 Annotatable::TraitItem(ref trait_item) => trait_item.span,
59 Annotatable::ImplItem(ref impl_item) => impl_item.span,
60 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
61 Annotatable::Stmt(ref stmt) => stmt.span,
62 Annotatable::Expr(ref expr) => expr.span,
63 Annotatable::Arm(ref arm) => arm.span,
64 Annotatable::ExprField(ref field) => field.span,
65 Annotatable::PatField(ref fp) => fp.pat.span,
66 Annotatable::GenericParam(ref gp) => gp.ident.span,
67 Annotatable::Param(ref p) => p.span,
68 Annotatable::FieldDef(ref sf) => sf.span,
69 Annotatable::Variant(ref v) => v.span,
70 Annotatable::Crate(ref c) => c.span,
74 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
76 Annotatable::Item(item) => item.visit_attrs(f),
77 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
78 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
79 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
80 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
81 Annotatable::Expr(expr) => expr.visit_attrs(f),
82 Annotatable::Arm(arm) => arm.visit_attrs(f),
83 Annotatable::ExprField(field) => field.visit_attrs(f),
84 Annotatable::PatField(fp) => fp.visit_attrs(f),
85 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
86 Annotatable::Param(p) => p.visit_attrs(f),
87 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
88 Annotatable::Variant(v) => v.visit_attrs(f),
89 Annotatable::Crate(c) => c.visit_attrs(f),
93 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
95 Annotatable::Item(item) => visitor.visit_item(item),
96 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
97 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
98 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
99 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
100 Annotatable::Expr(expr) => visitor.visit_expr(expr),
101 Annotatable::Arm(arm) => visitor.visit_arm(arm),
102 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
103 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
104 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
105 Annotatable::Param(p) => visitor.visit_param(p),
106 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
107 Annotatable::Variant(v) => visitor.visit_variant(v),
108 Annotatable::Crate(c) => visitor.visit_crate(c),
112 pub fn into_nonterminal(self) -> Nonterminal {
114 Annotatable::Item(item) => token::NtItem(item),
115 Annotatable::TraitItem(item) | Annotatable::ImplItem(item) => {
116 token::NtItem(P(item.and_then(ast::AssocItem::into_item)))
118 Annotatable::ForeignItem(item) => {
119 token::NtItem(P(item.and_then(ast::ForeignItem::into_item)))
121 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
122 Annotatable::Expr(expr) => token::NtExpr(expr),
124 | Annotatable::ExprField(..)
125 | Annotatable::PatField(..)
126 | Annotatable::GenericParam(..)
127 | Annotatable::Param(..)
128 | Annotatable::FieldDef(..)
129 | Annotatable::Variant(..)
130 | Annotatable::Crate(..) => panic!("unexpected annotatable"),
134 crate fn into_tokens(self, sess: &ParseSess) -> TokenStream {
135 nt_to_tokenstream(&self.into_nonterminal(), sess, CanSynthesizeMissingTokens::No)
138 pub fn expect_item(self) -> P<ast::Item> {
140 Annotatable::Item(i) => i,
141 _ => panic!("expected Item"),
145 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
147 Annotatable::TraitItem(i) => i,
148 _ => panic!("expected Item"),
152 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
154 Annotatable::ImplItem(i) => i,
155 _ => panic!("expected Item"),
159 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
161 Annotatable::ForeignItem(i) => i,
162 _ => panic!("expected foreign item"),
166 pub fn expect_stmt(self) -> ast::Stmt {
168 Annotatable::Stmt(stmt) => stmt.into_inner(),
169 _ => panic!("expected statement"),
173 pub fn expect_expr(self) -> P<ast::Expr> {
175 Annotatable::Expr(expr) => expr,
176 _ => panic!("expected expression"),
180 pub fn expect_arm(self) -> ast::Arm {
182 Annotatable::Arm(arm) => arm,
183 _ => panic!("expected match arm"),
187 pub fn expect_expr_field(self) -> ast::ExprField {
189 Annotatable::ExprField(field) => field,
190 _ => panic!("expected field"),
194 pub fn expect_pat_field(self) -> ast::PatField {
196 Annotatable::PatField(fp) => fp,
197 _ => panic!("expected field pattern"),
201 pub fn expect_generic_param(self) -> ast::GenericParam {
203 Annotatable::GenericParam(gp) => gp,
204 _ => panic!("expected generic parameter"),
208 pub fn expect_param(self) -> ast::Param {
210 Annotatable::Param(param) => param,
211 _ => panic!("expected parameter"),
215 pub fn expect_field_def(self) -> ast::FieldDef {
217 Annotatable::FieldDef(sf) => sf,
218 _ => panic!("expected struct field"),
222 pub fn expect_variant(self) -> ast::Variant {
224 Annotatable::Variant(v) => v,
225 _ => panic!("expected variant"),
229 pub fn expect_crate(self) -> ast::Crate {
231 Annotatable::Crate(krate) => krate,
232 _ => panic!("expected krate"),
237 /// Result of an expansion that may need to be retried.
238 /// Consider using this for non-`MultiItemModifier` expanders as well.
239 pub enum ExpandResult<T, U> {
240 /// Expansion produced a result (possibly dummy).
242 /// Expansion could not produce a result and needs to be retried.
246 // `meta_item` is the attribute, and `item` is the item being modified.
247 pub trait MultiItemModifier {
250 ecx: &mut ExtCtxt<'_>,
252 meta_item: &ast::MetaItem,
254 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
257 impl<F> MultiItemModifier for F
259 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
263 ecx: &mut ExtCtxt<'_>,
265 meta_item: &ast::MetaItem,
267 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
268 ExpandResult::Ready(self(ecx, span, meta_item, item))
272 pub trait ProcMacro {
275 ecx: &'cx mut ExtCtxt<'_>,
278 ) -> Result<TokenStream, ErrorReported>;
281 impl<F> ProcMacro for F
283 F: Fn(TokenStream) -> TokenStream,
287 _ecx: &'cx mut ExtCtxt<'_>,
290 ) -> Result<TokenStream, ErrorReported> {
291 // FIXME setup implicit context in TLS before calling self.
296 pub trait AttrProcMacro {
299 ecx: &'cx mut ExtCtxt<'_>,
301 annotation: TokenStream,
302 annotated: TokenStream,
303 ) -> Result<TokenStream, ErrorReported>;
306 impl<F> AttrProcMacro for F
308 F: Fn(TokenStream, TokenStream) -> TokenStream,
312 _ecx: &'cx mut ExtCtxt<'_>,
314 annotation: TokenStream,
315 annotated: TokenStream,
316 ) -> Result<TokenStream, ErrorReported> {
317 // FIXME setup implicit context in TLS before calling self.
318 Ok(self(annotation, annotated))
322 /// Represents a thing that maps token trees to Macro Results
323 pub trait TTMacroExpander {
326 ecx: &'cx mut ExtCtxt<'_>,
329 ) -> Box<dyn MacResult + 'cx>;
332 pub type MacroExpanderFn =
333 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
335 impl<F> TTMacroExpander for F
337 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
341 ecx: &'cx mut ExtCtxt<'_>,
344 ) -> Box<dyn MacResult + 'cx> {
345 self(ecx, span, input)
349 // Use a macro because forwarding to a simple function has type system issues
350 macro_rules! make_stmts_default {
352 $me.make_expr().map(|e| {
353 smallvec![ast::Stmt {
354 id: ast::DUMMY_NODE_ID,
356 kind: ast::StmtKind::Expr(e),
362 /// The result of a macro expansion. The return values of the various
363 /// methods are spliced into the AST at the callsite of the macro.
364 pub trait MacResult {
365 /// Creates an expression.
366 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
370 /// Creates zero or more items.
371 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
375 /// Creates zero or more impl items.
376 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
380 /// Creates zero or more trait items.
381 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
385 /// Creates zero or more items in an `extern {}` block
386 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
390 /// Creates a pattern.
391 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
395 /// Creates zero or more statements.
397 /// By default this attempts to create an expression statement,
398 /// returning None if that fails.
399 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
400 make_stmts_default!(self)
403 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
407 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
411 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
415 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
419 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
423 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
427 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
431 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
435 fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
436 // Fn-like macros cannot produce a crate.
441 macro_rules! make_MacEager {
442 ( $( $fld:ident: $t:ty, )* ) => {
443 /// `MacResult` implementation for the common case where you've already
444 /// built each form of AST that you might return.
446 pub struct MacEager {
448 pub $fld: Option<$t>,
454 pub fn $fld(v: $t) -> Box<dyn MacResult> {
468 items: SmallVec<[P<ast::Item>; 1]>,
469 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
470 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
471 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
472 stmts: SmallVec<[ast::Stmt; 1]>,
476 impl MacResult for MacEager {
477 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
481 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
485 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
489 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
493 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
497 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
498 match self.stmts.as_ref().map_or(0, |s| s.len()) {
499 0 => make_stmts_default!(self),
504 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
505 if let Some(p) = self.pat {
508 if let Some(e) = self.expr {
509 if let ast::ExprKind::Lit(_) = e.kind {
510 return Some(P(ast::Pat {
511 id: ast::DUMMY_NODE_ID,
513 kind: PatKind::Lit(e),
521 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
526 /// Fill-in macro expansion result, to allow compilation to continue
527 /// after hitting errors.
528 #[derive(Copy, Clone)]
529 pub struct DummyResult {
535 /// Creates a default MacResult that can be anything.
537 /// Use this as a return value after hitting any errors and
538 /// calling `span_err`.
539 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
540 Box::new(DummyResult { is_error: true, span })
543 /// Same as `any`, but must be a valid fragment, not error.
544 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
545 Box::new(DummyResult { is_error: false, span })
548 /// A plain dummy expression.
549 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
551 id: ast::DUMMY_NODE_ID,
552 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
554 attrs: ast::AttrVec::new(),
559 /// A plain dummy pattern.
560 pub fn raw_pat(sp: Span) -> ast::Pat {
561 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
564 /// A plain dummy type.
565 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
567 id: ast::DUMMY_NODE_ID,
568 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
575 impl MacResult for DummyResult {
576 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
577 Some(DummyResult::raw_expr(self.span, self.is_error))
580 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
581 Some(P(DummyResult::raw_pat(self.span)))
584 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
585 Some(SmallVec::new())
588 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
589 Some(SmallVec::new())
592 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
593 Some(SmallVec::new())
596 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
597 Some(SmallVec::new())
600 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
601 Some(smallvec![ast::Stmt {
602 id: ast::DUMMY_NODE_ID,
603 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
608 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
609 Some(DummyResult::raw_ty(self.span, self.is_error))
612 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
613 Some(SmallVec::new())
616 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
617 Some(SmallVec::new())
620 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
621 Some(SmallVec::new())
624 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
625 Some(SmallVec::new())
628 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
629 Some(SmallVec::new())
632 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
633 Some(SmallVec::new())
636 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
637 Some(SmallVec::new())
641 /// A syntax extension kind.
642 pub enum SyntaxExtensionKind {
643 /// A token-based function-like macro.
645 /// An expander with signature TokenStream -> TokenStream.
646 Box<dyn ProcMacro + sync::Sync + sync::Send>,
649 /// An AST-based function-like macro.
651 /// An expander with signature TokenStream -> AST.
652 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
655 /// A token-based attribute macro.
657 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
658 /// The first TokenSteam is the attribute itself, the second is the annotated item.
659 /// The produced TokenSteam replaces the input TokenSteam.
660 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
663 /// An AST-based attribute macro.
665 /// An expander with signature (AST, AST) -> AST.
666 /// The first AST fragment is the attribute itself, the second is the annotated item.
667 /// The produced AST fragment replaces the input AST fragment.
668 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
671 /// A trivial attribute "macro" that does nothing,
672 /// only keeps the attribute and marks it as inert,
673 /// thus making it ineligible for further expansion.
676 /// A token-based derive macro.
678 /// An expander with signature TokenStream -> TokenStream (not yet).
679 /// The produced TokenSteam is appended to the input TokenSteam.
680 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
683 /// An AST-based derive macro.
685 /// An expander with signature AST -> AST.
686 /// The produced AST fragment is appended to the input AST fragment.
687 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
691 /// A struct representing a macro definition in "lowered" form ready for expansion.
692 pub struct SyntaxExtension {
693 /// A syntax extension kind.
694 pub kind: SyntaxExtensionKind,
695 /// Span of the macro definition.
697 /// List of unstable features that are treated as stable inside this macro.
698 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
699 /// Suppresses the `unsafe_code` lint for code produced by this macro.
700 pub allow_internal_unsafe: bool,
701 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
702 pub local_inner_macros: bool,
703 /// The macro's stability info.
704 pub stability: Option<Stability>,
705 /// The macro's deprecation info.
706 pub deprecation: Option<Deprecation>,
707 /// Names of helper attributes registered by this macro.
708 pub helper_attrs: Vec<Symbol>,
709 /// Edition of the crate in which this macro is defined.
710 pub edition: Edition,
711 /// Built-in macros have a couple of special properties like availability
712 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
713 pub builtin_name: Option<Symbol>,
716 impl SyntaxExtension {
717 /// Returns which kind of macro calls this syntax extension.
718 pub fn macro_kind(&self) -> MacroKind {
720 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
721 SyntaxExtensionKind::Attr(..)
722 | SyntaxExtensionKind::LegacyAttr(..)
723 | SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
724 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
730 /// Constructs a syntax extension with default properties.
731 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
734 allow_internal_unstable: None,
735 allow_internal_unsafe: false,
736 local_inner_macros: false,
739 helper_attrs: Vec::new(),
746 /// Constructs a syntax extension with the given properties
747 /// and other properties converted from attributes.
750 kind: SyntaxExtensionKind,
752 helper_attrs: Vec<Symbol>,
755 attrs: &[ast::Attribute],
756 ) -> SyntaxExtension {
757 let allow_internal_unstable =
758 attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
760 let mut local_inner_macros = false;
761 if let Some(macro_export) = sess.find_by_name(attrs, sym::macro_export) {
762 if let Some(l) = macro_export.meta_item_list() {
763 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
767 let (builtin_name, helper_attrs) = sess
768 .find_by_name(attrs, sym::rustc_builtin_macro)
770 // Override `helper_attrs` passed above if it's a built-in macro,
771 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
772 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
773 || (Some(name), Vec::new()),
774 |(name, helper_attrs)| (Some(name), helper_attrs),
777 .unwrap_or_else(|| (None, helper_attrs));
778 let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
779 if let Some((_, sp)) = const_stability {
782 .struct_span_err(sp, "macros cannot have const stability attributes")
783 .span_label(sp, "invalid const stability attribute")
785 sess.source_map().guess_head_span(span),
786 "const stability attribute affects this macro",
794 allow_internal_unstable: (!allow_internal_unstable.is_empty())
795 .then(|| allow_internal_unstable.into()),
796 allow_internal_unsafe: sess.contains_name(attrs, sym::allow_internal_unsafe),
798 stability: stability.map(|(s, _)| s),
799 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
806 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
808 _: &'cx mut ExtCtxt<'_>,
811 ) -> Box<dyn MacResult + 'cx> {
812 DummyResult::any(span)
814 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
817 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
823 ) -> Vec<Annotatable> {
826 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
829 pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
830 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
838 macro_def_id: Option<DefId>,
839 parent_module: Option<DefId>,
842 ExpnKind::Macro(self.macro_kind(), descr),
846 self.allow_internal_unstable.clone(),
847 self.allow_internal_unsafe,
848 self.local_inner_macros,
856 /// Error type that denotes indeterminacy.
857 pub struct Indeterminate;
859 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>)>;
861 pub trait ResolverExpand {
862 fn next_node_id(&mut self) -> NodeId;
863 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
865 fn resolve_dollar_crates(&mut self);
866 fn visit_ast_fragment_with_placeholders(
868 expn_id: LocalExpnId,
869 fragment: &AstFragment,
871 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
873 fn expansion_for_ast_pass(
878 parent_module_id: Option<NodeId>,
881 fn resolve_imports(&mut self);
883 fn resolve_macro_invocation(
886 eager_expansion_root: LocalExpnId,
888 ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
890 fn check_unused_macros(&mut self);
892 // Resolver interfaces for specific built-in macros.
893 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
894 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
895 /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
898 expn_id: LocalExpnId,
900 derive_paths: &dyn Fn() -> DeriveResolutions,
901 ) -> Result<(), Indeterminate>;
902 /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
903 /// back from resolver.
904 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
905 /// Path resolution logic for `#[cfg_accessible(path)]`.
908 expn_id: LocalExpnId,
910 ) -> Result<bool, Indeterminate>;
912 /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
913 /// No caching is performed.
914 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
916 /// The order of items in the HIR is unrelated to the order of
917 /// items in the AST. However, we generate proc macro harnesses
918 /// based on the AST order, and later refer to these harnesses
919 /// from the HIR. This field keeps track of the order in which
920 /// we generated proc macros harnesses, so that we can map
921 /// HIR proc macros items back to their harness items.
922 fn declare_proc_macro(&mut self, id: NodeId);
925 #[derive(Clone, Default)]
926 pub struct ModuleData {
927 /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
928 pub mod_path: Vec<Ident>,
929 /// Stack of paths to files loaded by out-of-line module items,
930 /// used to detect and report recursive module inclusions.
931 pub file_path_stack: Vec<PathBuf>,
932 /// Directory to search child module files in,
933 /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
934 pub dir_path: PathBuf,
938 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
940 mod_path: self.mod_path.clone(),
941 file_path_stack: self.file_path_stack.clone(),
948 pub struct ExpansionData {
951 pub module: Rc<ModuleData>,
952 pub dir_ownership: DirOwnership,
953 pub prior_type_ascription: Option<(Span, bool)>,
954 /// Some parent node that is close to this macro call
955 pub lint_node_id: NodeId,
956 pub is_trailing_mac: bool,
959 type OnExternModLoaded<'a> =
960 Option<&'a dyn Fn(Ident, Vec<Attribute>, Vec<P<Item>>, Span) -> (Vec<Attribute>, Vec<P<Item>>)>;
962 /// One of these is made during expansion and incrementally updated as we go;
963 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
964 /// -> expn_data` of their expansion context stored into their span.
965 pub struct ExtCtxt<'a> {
966 pub sess: &'a Session,
967 pub ecfg: expand::ExpansionConfig<'a>,
968 pub reduced_recursion_limit: Option<Limit>,
969 pub root_path: PathBuf,
970 pub resolver: &'a mut dyn ResolverExpand,
971 pub current_expansion: ExpansionData,
972 /// Error recovery mode entered when expansion is stuck
973 /// (or during eager expansion, but that's a hack).
974 pub force_mode: bool,
975 pub expansions: FxHashMap<Span, Vec<String>>,
976 /// Called directly after having parsed an external `mod foo;` in expansion.
978 /// `Ident` is the module name.
979 pub(super) extern_mod_loaded: OnExternModLoaded<'a>,
980 /// When we 'expand' an inert attribute, we leave it
981 /// in the AST, but insert it here so that we know
982 /// not to expand it again.
983 pub(super) expanded_inert_attrs: MarkedAttrs,
986 impl<'a> ExtCtxt<'a> {
989 ecfg: expand::ExpansionConfig<'a>,
990 resolver: &'a mut dyn ResolverExpand,
991 extern_mod_loaded: OnExternModLoaded<'a>,
996 reduced_recursion_limit: None,
999 root_path: PathBuf::new(),
1000 current_expansion: ExpansionData {
1001 id: LocalExpnId::ROOT,
1003 module: Default::default(),
1004 dir_ownership: DirOwnership::Owned { relative: None },
1005 prior_type_ascription: None,
1006 lint_node_id: ast::CRATE_NODE_ID,
1007 is_trailing_mac: false,
1010 expansions: FxHashMap::default(),
1011 expanded_inert_attrs: MarkedAttrs::new(),
1015 /// Returns a `Folder` for deeply expanding all macros in an AST node.
1016 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1017 expand::MacroExpander::new(self, false)
1020 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1021 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1022 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1023 expand::MacroExpander::new(self, true)
1025 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1026 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1028 pub fn source_map(&self) -> &'a SourceMap {
1029 self.sess.parse_sess.source_map()
1031 pub fn parse_sess(&self) -> &'a ParseSess {
1032 &self.sess.parse_sess
1034 pub fn call_site(&self) -> Span {
1035 self.current_expansion.id.expn_data().call_site
1038 /// Equivalent of `Span::def_site` from the proc macro API,
1039 /// except that the location is taken from the span passed as an argument.
1040 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1041 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1044 /// Equivalent of `Span::call_site` from the proc macro API,
1045 /// except that the location is taken from the span passed as an argument.
1046 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1047 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1050 /// Equivalent of `Span::mixed_site` from the proc macro API,
1051 /// except that the location is taken from the span passed as an argument.
1052 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1053 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1056 /// Returns span for the macro which originally caused the current expansion to happen.
1058 /// Stops backtracing at include! boundary.
1059 pub fn expansion_cause(&self) -> Option<Span> {
1060 self.current_expansion.id.expansion_cause()
1063 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
1064 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1067 /// Emit `msg` attached to `sp`, without immediately stopping
1070 /// Compilation will be stopped in the near future (at the end of
1071 /// the macro expansion phase).
1072 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1073 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1075 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1076 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1078 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1079 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1081 pub fn trace_macros_diag(&mut self) {
1082 for (sp, notes) in self.expansions.iter() {
1083 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1089 // Fixme: does this result in errors?
1090 self.expansions.clear();
1092 pub fn bug(&self, msg: &str) -> ! {
1093 self.sess.parse_sess.span_diagnostic.bug(msg);
1095 pub fn trace_macros(&self) -> bool {
1098 pub fn set_trace_macros(&mut self, x: bool) {
1099 self.ecfg.trace_mac = x
1101 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1102 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1103 iter::once(Ident::new(kw::DollarCrate, def_site))
1104 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1107 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1108 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1109 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1112 pub fn check_unused_macros(&mut self) {
1113 self.resolver.check_unused_macros();
1116 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1118 /// This unifies the logic used for resolving `include_X!`.
1120 /// FIXME: move this to `rustc_builtin_macros` and make it private.
1121 pub fn resolve_path(
1123 path: impl Into<PathBuf>,
1125 ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1126 let path = path.into();
1128 // Relative paths are resolved relative to the file in which they are found
1129 // after macro expansion (that is, they are unhygienic).
1130 if !path.is_absolute() {
1131 let callsite = span.source_callsite();
1132 let mut result = match self.source_map().span_to_filename(callsite) {
1133 FileName::Real(name) => name
1135 .expect("attempting to resolve a file path in an external file"),
1136 FileName::DocTest(path, _) => path,
1138 return Err(self.struct_span_err(
1141 "cannot resolve relative path in non-file source `{}`",
1142 self.source_map().filename_for_diagnostics(&other)
1156 /// Extracts a string literal from the macro expanded version of `expr`,
1157 /// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
1158 /// The returned bool indicates whether an applicable suggestion has already been
1159 /// added to the diagnostic to avoid emitting multiple suggestions. `Err(None)`
1160 /// indicates that an ast error was encountered.
1161 pub fn expr_to_spanned_string<'a>(
1162 cx: &'a mut ExtCtxt<'_>,
1165 ) -> Result<(Symbol, ast::StrStyle, Span), Option<(DiagnosticBuilder<'a>, bool)>> {
1166 // Perform eager expansion on the expression.
1167 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1168 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1170 Err(match expr.kind {
1171 ast::ExprKind::Lit(ref l) => match l.kind {
1172 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1173 ast::LitKind::ByteStr(_) => {
1174 let mut err = cx.struct_span_err(l.span, err_msg);
1175 err.span_suggestion(
1176 expr.span.shrink_to_lo(),
1177 "consider removing the leading `b`",
1179 Applicability::MaybeIncorrect,
1183 ast::LitKind::Err(_) => None,
1184 _ => Some((cx.struct_span_err(l.span, err_msg), false)),
1186 ast::ExprKind::Err => None,
1187 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1191 /// Extracts a string literal from the macro expanded version of `expr`,
1192 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1193 /// compilation on error, merely emits a non-fatal error and returns `None`.
1194 pub fn expr_to_string(
1195 cx: &mut ExtCtxt<'_>,
1198 ) -> Option<(Symbol, ast::StrStyle)> {
1199 expr_to_spanned_string(cx, expr, err_msg)
1201 err.map(|(mut err, _)| {
1206 .map(|(symbol, style, _)| (symbol, style))
1209 /// Non-fatally assert that `tts` is empty. Note that this function
1210 /// returns even when `tts` is non-empty, macros that *need* to stop
1211 /// compilation should call
1212 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1213 /// done as rarely as possible).
1214 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1215 if !tts.is_empty() {
1216 cx.span_err(sp, &format!("{} takes no arguments", name));
1220 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1221 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1222 match p.parse_expr() {
1223 Ok(e) => return Some(e),
1224 Err(mut err) => err.emit(),
1226 while p.token != token::Eof {
1232 /// Interpreting `tts` as a comma-separated sequence of expressions,
1233 /// expect exactly one string literal, or emit an error and return `None`.
1234 pub fn get_single_str_from_tts(
1235 cx: &mut ExtCtxt<'_>,
1239 ) -> Option<String> {
1240 let mut p = cx.new_parser_from_tts(tts);
1241 if p.token == token::Eof {
1242 cx.span_err(sp, &format!("{} takes 1 argument", name));
1245 let ret = parse_expr(&mut p)?;
1246 let _ = p.eat(&token::Comma);
1248 if p.token != token::Eof {
1249 cx.span_err(sp, &format!("{} takes 1 argument", name));
1251 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1254 /// Extracts comma-separated expressions from `tts`.
1255 /// On error, emit it, and return `None`.
1256 pub fn get_exprs_from_tts(
1257 cx: &mut ExtCtxt<'_>,
1260 ) -> Option<Vec<P<ast::Expr>>> {
1261 let mut p = cx.new_parser_from_tts(tts);
1262 let mut es = Vec::new();
1263 while p.token != token::Eof {
1264 let expr = parse_expr(&mut p)?;
1266 // Perform eager expansion on the expression.
1267 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1268 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1271 if p.eat(&token::Comma) {
1274 if p.token != token::Eof {
1275 cx.span_err(sp, "expected token: `,`");
1282 pub fn parse_macro_name_and_helper_attrs(
1283 diag: &rustc_errors::Handler,
1286 ) -> Option<(Symbol, Vec<Symbol>)> {
1287 // Once we've located the `#[proc_macro_derive]` attribute, verify
1288 // that it's of the form `#[proc_macro_derive(Foo)]` or
1289 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1290 let list = match attr.meta_item_list() {
1292 None => return None,
1294 if list.len() != 1 && list.len() != 2 {
1295 diag.span_err(attr.span, "attribute must have either one or two arguments");
1298 let trait_attr = match list[0].meta_item() {
1299 Some(meta_item) => meta_item,
1301 diag.span_err(list[0].span(), "not a meta item");
1305 let trait_ident = match trait_attr.ident() {
1306 Some(trait_ident) if trait_attr.is_word() => trait_ident,
1308 diag.span_err(trait_attr.span, "must only be one word");
1313 if !trait_ident.name.can_be_raw() {
1316 &format!("`{}` cannot be a name of {} macro", trait_ident, descr),
1320 let attributes_attr = list.get(1);
1321 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1322 if !attr.has_name(sym::attributes) {
1323 diag.span_err(attr.span(), "second argument must be `attributes`")
1325 attr.meta_item_list()
1326 .unwrap_or_else(|| {
1327 diag.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
1331 .filter_map(|attr| {
1332 let attr = match attr.meta_item() {
1333 Some(meta_item) => meta_item,
1335 diag.span_err(attr.span(), "not a meta item");
1340 let ident = match attr.ident() {
1341 Some(ident) if attr.is_word() => ident,
1343 diag.span_err(attr.span, "must only be one word");
1347 if !ident.name.can_be_raw() {
1350 &format!("`{}` cannot be a name of derive helper attribute", ident),
1361 Some((trait_ident.name, proc_attrs))
1364 /// This nonterminal looks like some specific enums from
1365 /// `proc-macro-hack` and `procedural-masquerade` crates.
1366 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1367 /// asserts in old versions of those crates and their wide use in the ecosystem.
1368 /// See issue #73345 for more details.
1369 /// FIXME(#73933): Remove this eventually.
1370 pub(crate) fn pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1371 let item = match nt {
1372 Nonterminal::NtItem(item) => item,
1373 Nonterminal::NtStmt(stmt) => match &stmt.kind {
1374 ast::StmtKind::Item(item) => item,
1380 let name = item.ident.name;
1381 if name == sym::ProceduralMasqueradeDummyType {
1382 if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1383 if let [variant] = &*enum_def.variants {
1384 if variant.ident.name == sym::Input {
1385 sess.buffer_lint_with_diagnostic(
1386 &PROC_MACRO_BACK_COMPAT,
1389 "using `procedural-masquerade` crate",
1390 BuiltinLintDiagnostics::ProcMacroBackCompat(
1391 "The `procedural-masquerade` crate has been unnecessary since Rust 1.30.0. \
1392 Versions of this crate below 0.1.7 will eventually stop compiling.".to_string())