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, Attribute, HasAttrs, Item, NodeId, PatKind};
10 use rustc_attr::{self as attr, Deprecation, Stability};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::{self, Lrc};
13 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, PResult};
14 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
15 use rustc_lint_defs::BuiltinLintDiagnostics;
16 use rustc_parse::{self, parser, to_token_stream, 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, 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.spans.inner_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 to_tokens(&self, sess: &ParseSess) -> TokenStream {
114 Annotatable::Item(node) => to_token_stream(node, sess, CanSynthesizeMissingTokens::No),
115 Annotatable::TraitItem(node) | Annotatable::ImplItem(node) => {
116 to_token_stream(node, sess, CanSynthesizeMissingTokens::No)
118 Annotatable::ForeignItem(node) => {
119 to_token_stream(node, sess, CanSynthesizeMissingTokens::No)
121 Annotatable::Stmt(node) => {
122 assert!(!matches!(node.kind, ast::StmtKind::Empty));
123 to_token_stream(node, sess, CanSynthesizeMissingTokens::No)
125 Annotatable::Expr(node) => to_token_stream(node, sess, CanSynthesizeMissingTokens::No),
127 | Annotatable::ExprField(..)
128 | Annotatable::PatField(..)
129 | Annotatable::GenericParam(..)
130 | Annotatable::Param(..)
131 | Annotatable::FieldDef(..)
132 | Annotatable::Variant(..)
133 | Annotatable::Crate(..) => panic!("unexpected annotatable"),
137 pub fn expect_item(self) -> P<ast::Item> {
139 Annotatable::Item(i) => i,
140 _ => panic!("expected Item"),
144 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
146 Annotatable::TraitItem(i) => i,
147 _ => panic!("expected Item"),
151 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
153 Annotatable::ImplItem(i) => i,
154 _ => panic!("expected Item"),
158 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
160 Annotatable::ForeignItem(i) => i,
161 _ => panic!("expected foreign item"),
165 pub fn expect_stmt(self) -> ast::Stmt {
167 Annotatable::Stmt(stmt) => stmt.into_inner(),
168 _ => panic!("expected statement"),
172 pub fn expect_expr(self) -> P<ast::Expr> {
174 Annotatable::Expr(expr) => expr,
175 _ => panic!("expected expression"),
179 pub fn expect_arm(self) -> ast::Arm {
181 Annotatable::Arm(arm) => arm,
182 _ => panic!("expected match arm"),
186 pub fn expect_expr_field(self) -> ast::ExprField {
188 Annotatable::ExprField(field) => field,
189 _ => panic!("expected field"),
193 pub fn expect_pat_field(self) -> ast::PatField {
195 Annotatable::PatField(fp) => fp,
196 _ => panic!("expected field pattern"),
200 pub fn expect_generic_param(self) -> ast::GenericParam {
202 Annotatable::GenericParam(gp) => gp,
203 _ => panic!("expected generic parameter"),
207 pub fn expect_param(self) -> ast::Param {
209 Annotatable::Param(param) => param,
210 _ => panic!("expected parameter"),
214 pub fn expect_field_def(self) -> ast::FieldDef {
216 Annotatable::FieldDef(sf) => sf,
217 _ => panic!("expected struct field"),
221 pub fn expect_variant(self) -> ast::Variant {
223 Annotatable::Variant(v) => v,
224 _ => panic!("expected variant"),
228 pub fn expect_crate(self) -> ast::Crate {
230 Annotatable::Crate(krate) => krate,
231 _ => panic!("expected krate"),
236 /// Result of an expansion that may need to be retried.
237 /// Consider using this for non-`MultiItemModifier` expanders as well.
238 pub enum ExpandResult<T, U> {
239 /// Expansion produced a result (possibly dummy).
241 /// Expansion could not produce a result and needs to be retried.
245 // `meta_item` is the attribute, and `item` is the item being modified.
246 pub trait MultiItemModifier {
249 ecx: &mut ExtCtxt<'_>,
251 meta_item: &ast::MetaItem,
253 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
256 impl<F> MultiItemModifier for F
258 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
262 ecx: &mut ExtCtxt<'_>,
264 meta_item: &ast::MetaItem,
266 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
267 ExpandResult::Ready(self(ecx, span, meta_item, item))
271 pub trait ProcMacro {
274 ecx: &'cx mut ExtCtxt<'_>,
277 ) -> Result<TokenStream, ErrorGuaranteed>;
280 impl<F> ProcMacro for F
282 F: Fn(TokenStream) -> TokenStream,
286 _ecx: &'cx mut ExtCtxt<'_>,
289 ) -> Result<TokenStream, ErrorGuaranteed> {
290 // FIXME setup implicit context in TLS before calling self.
295 pub trait AttrProcMacro {
298 ecx: &'cx mut ExtCtxt<'_>,
300 annotation: TokenStream,
301 annotated: TokenStream,
302 ) -> Result<TokenStream, ErrorGuaranteed>;
305 impl<F> AttrProcMacro for F
307 F: Fn(TokenStream, TokenStream) -> TokenStream,
311 _ecx: &'cx mut ExtCtxt<'_>,
313 annotation: TokenStream,
314 annotated: TokenStream,
315 ) -> Result<TokenStream, ErrorGuaranteed> {
316 // FIXME setup implicit context in TLS before calling self.
317 Ok(self(annotation, annotated))
321 /// Represents a thing that maps token trees to Macro Results
322 pub trait TTMacroExpander {
325 ecx: &'cx mut ExtCtxt<'_>,
328 ) -> Box<dyn MacResult + 'cx>;
331 pub type MacroExpanderFn =
332 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
334 impl<F> TTMacroExpander for F
336 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
340 ecx: &'cx mut ExtCtxt<'_>,
343 ) -> Box<dyn MacResult + 'cx> {
344 self(ecx, span, input)
348 // Use a macro because forwarding to a simple function has type system issues
349 macro_rules! make_stmts_default {
351 $me.make_expr().map(|e| {
352 smallvec![ast::Stmt {
353 id: ast::DUMMY_NODE_ID,
355 kind: ast::StmtKind::Expr(e),
361 /// The result of a macro expansion. The return values of the various
362 /// methods are spliced into the AST at the callsite of the macro.
363 pub trait MacResult {
364 /// Creates an expression.
365 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
369 /// Creates zero or more items.
370 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
374 /// Creates zero or more impl items.
375 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
379 /// Creates zero or more trait items.
380 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
384 /// Creates zero or more items in an `extern {}` block
385 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
389 /// Creates a pattern.
390 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
394 /// Creates zero or more statements.
396 /// By default this attempts to create an expression statement,
397 /// returning None if that fails.
398 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
399 make_stmts_default!(self)
402 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
406 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
410 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
414 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
418 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
422 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
426 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
430 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
434 fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
435 // Fn-like macros cannot produce a crate.
440 macro_rules! make_MacEager {
441 ( $( $fld:ident: $t:ty, )* ) => {
442 /// `MacResult` implementation for the common case where you've already
443 /// built each form of AST that you might return.
445 pub struct MacEager {
447 pub $fld: Option<$t>,
453 pub fn $fld(v: $t) -> Box<dyn MacResult> {
467 items: SmallVec<[P<ast::Item>; 1]>,
468 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
469 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
470 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
471 stmts: SmallVec<[ast::Stmt; 1]>,
475 impl MacResult for MacEager {
476 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
480 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
484 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
488 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
492 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
496 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
497 match self.stmts.as_ref().map_or(0, |s| s.len()) {
498 0 => make_stmts_default!(self),
503 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
504 if let Some(p) = self.pat {
507 if let Some(e) = self.expr {
508 if let ast::ExprKind::Lit(_) = e.kind {
509 return Some(P(ast::Pat {
510 id: ast::DUMMY_NODE_ID,
512 kind: PatKind::Lit(e),
520 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
525 /// Fill-in macro expansion result, to allow compilation to continue
526 /// after hitting errors.
527 #[derive(Copy, Clone)]
528 pub struct DummyResult {
534 /// Creates a default MacResult that can be anything.
536 /// Use this as a return value after hitting any errors and
537 /// calling `span_err`.
538 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
539 Box::new(DummyResult { is_error: true, span })
542 /// Same as `any`, but must be a valid fragment, not error.
543 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
544 Box::new(DummyResult { is_error: false, span })
547 /// A plain dummy expression.
548 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
550 id: ast::DUMMY_NODE_ID,
551 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
553 attrs: ast::AttrVec::new(),
558 /// A plain dummy pattern.
559 pub fn raw_pat(sp: Span) -> ast::Pat {
560 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
563 /// A plain dummy type.
564 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
566 id: ast::DUMMY_NODE_ID,
567 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
574 impl MacResult for DummyResult {
575 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
576 Some(DummyResult::raw_expr(self.span, self.is_error))
579 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
580 Some(P(DummyResult::raw_pat(self.span)))
583 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
584 Some(SmallVec::new())
587 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
588 Some(SmallVec::new())
591 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
592 Some(SmallVec::new())
595 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
596 Some(SmallVec::new())
599 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
600 Some(smallvec![ast::Stmt {
601 id: ast::DUMMY_NODE_ID,
602 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
607 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
608 Some(DummyResult::raw_ty(self.span, self.is_error))
611 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
612 Some(SmallVec::new())
615 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
616 Some(SmallVec::new())
619 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
620 Some(SmallVec::new())
623 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
624 Some(SmallVec::new())
627 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
628 Some(SmallVec::new())
631 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
632 Some(SmallVec::new())
635 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
636 Some(SmallVec::new())
640 /// A syntax extension kind.
641 pub enum SyntaxExtensionKind {
642 /// A token-based function-like macro.
644 /// An expander with signature TokenStream -> TokenStream.
645 Box<dyn ProcMacro + sync::Sync + sync::Send>,
648 /// An AST-based function-like macro.
650 /// An expander with signature TokenStream -> AST.
651 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
654 /// A token-based attribute macro.
656 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
657 /// The first TokenSteam is the attribute itself, the second is the annotated item.
658 /// The produced TokenSteam replaces the input TokenSteam.
659 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
662 /// An AST-based attribute macro.
664 /// An expander with signature (AST, AST) -> AST.
665 /// The first AST fragment is the attribute itself, the second is the annotated item.
666 /// The produced AST fragment replaces the input AST fragment.
667 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
670 /// A trivial attribute "macro" that does nothing,
671 /// only keeps the attribute and marks it as inert,
672 /// thus making it ineligible for further expansion.
675 /// A token-based derive macro.
677 /// An expander with signature TokenStream -> TokenStream (not yet).
678 /// The produced TokenSteam is appended to the input TokenSteam.
679 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
682 /// An AST-based derive macro.
684 /// An expander with signature AST -> AST.
685 /// The produced AST fragment is appended to the input AST fragment.
686 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
690 /// A struct representing a macro definition in "lowered" form ready for expansion.
691 pub struct SyntaxExtension {
692 /// A syntax extension kind.
693 pub kind: SyntaxExtensionKind,
694 /// Span of the macro definition.
696 /// List of unstable features that are treated as stable inside this macro.
697 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
698 /// Suppresses the `unsafe_code` lint for code produced by this macro.
699 pub allow_internal_unsafe: bool,
700 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
701 pub local_inner_macros: bool,
702 /// The macro's stability info.
703 pub stability: Option<Stability>,
704 /// The macro's deprecation info.
705 pub deprecation: Option<Deprecation>,
706 /// Names of helper attributes registered by this macro.
707 pub helper_attrs: Vec<Symbol>,
708 /// Edition of the crate in which this macro is defined.
709 pub edition: Edition,
710 /// Built-in macros have a couple of special properties like availability
711 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
712 pub builtin_name: Option<Symbol>,
715 impl SyntaxExtension {
716 /// Returns which kind of macro calls this syntax extension.
717 pub fn macro_kind(&self) -> MacroKind {
719 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
720 SyntaxExtensionKind::Attr(..)
721 | SyntaxExtensionKind::LegacyAttr(..)
722 | SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
723 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
729 /// Constructs a syntax extension with default properties.
730 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
733 allow_internal_unstable: None,
734 allow_internal_unsafe: false,
735 local_inner_macros: false,
738 helper_attrs: Vec::new(),
745 /// Constructs a syntax extension with the given properties
746 /// and other properties converted from attributes.
749 kind: SyntaxExtensionKind,
751 helper_attrs: Vec<Symbol>,
754 attrs: &[ast::Attribute],
755 ) -> SyntaxExtension {
756 let allow_internal_unstable =
757 attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
759 let mut local_inner_macros = false;
760 if let Some(macro_export) = sess.find_by_name(attrs, sym::macro_export) {
761 if let Some(l) = macro_export.meta_item_list() {
762 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
766 let (builtin_name, helper_attrs) = sess
767 .find_by_name(attrs, sym::rustc_builtin_macro)
769 // Override `helper_attrs` passed above if it's a built-in macro,
770 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
771 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
772 || (Some(name), Vec::new()),
773 |(name, helper_attrs)| (Some(name), helper_attrs),
776 .unwrap_or_else(|| (None, helper_attrs));
777 let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
778 if let Some((_, sp)) = const_stability {
781 .struct_span_err(sp, "macros cannot have const stability attributes")
782 .span_label(sp, "invalid const stability attribute")
784 sess.source_map().guess_head_span(span),
785 "const stability attribute affects this macro",
793 allow_internal_unstable: (!allow_internal_unstable.is_empty())
794 .then(|| allow_internal_unstable.into()),
795 allow_internal_unsafe: sess.contains_name(attrs, sym::allow_internal_unsafe),
797 stability: stability.map(|(s, _)| s),
798 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
805 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
807 _: &'cx mut ExtCtxt<'_>,
810 ) -> Box<dyn MacResult + 'cx> {
811 DummyResult::any(span)
813 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
816 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
822 ) -> Vec<Annotatable> {
825 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
828 pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
829 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
837 macro_def_id: Option<DefId>,
838 parent_module: Option<DefId>,
841 ExpnKind::Macro(self.macro_kind(), descr),
845 self.allow_internal_unstable.clone(),
846 self.allow_internal_unsafe,
847 self.local_inner_macros,
855 /// Error type that denotes indeterminacy.
856 pub struct Indeterminate;
858 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>)>;
860 pub trait ResolverExpand {
861 fn next_node_id(&mut self) -> NodeId;
862 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
864 fn resolve_dollar_crates(&mut self);
865 fn visit_ast_fragment_with_placeholders(
867 expn_id: LocalExpnId,
868 fragment: &AstFragment,
870 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
872 fn expansion_for_ast_pass(
877 parent_module_id: Option<NodeId>,
880 fn resolve_imports(&mut self);
882 fn resolve_macro_invocation(
885 eager_expansion_root: LocalExpnId,
887 ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
889 fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
891 fn check_unused_macros(&mut self);
893 // Resolver interfaces for specific built-in macros.
894 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
895 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
896 /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
899 expn_id: LocalExpnId,
901 derive_paths: &dyn Fn() -> DeriveResolutions,
902 ) -> Result<(), Indeterminate>;
903 /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
904 /// back from resolver.
905 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
906 /// Path resolution logic for `#[cfg_accessible(path)]`.
909 expn_id: LocalExpnId,
911 ) -> Result<bool, Indeterminate>;
913 /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
914 /// No caching is performed.
915 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
917 /// The order of items in the HIR is unrelated to the order of
918 /// items in the AST. However, we generate proc macro harnesses
919 /// based on the AST order, and later refer to these harnesses
920 /// from the HIR. This field keeps track of the order in which
921 /// we generated proc macros harnesses, so that we can map
922 /// HIR proc macros items back to their harness items.
923 fn declare_proc_macro(&mut self, id: NodeId);
925 /// Tools registered with `#![register_tool]` and used by tool attributes and lints.
926 fn registered_tools(&self) -> &FxHashSet<Ident>;
929 pub trait LintStoreExpand {
930 fn pre_expansion_lint(
933 registered_tools: &FxHashSet<Ident>,
941 type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
943 #[derive(Clone, Default)]
944 pub struct ModuleData {
945 /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
946 pub mod_path: Vec<Ident>,
947 /// Stack of paths to files loaded by out-of-line module items,
948 /// used to detect and report recursive module inclusions.
949 pub file_path_stack: Vec<PathBuf>,
950 /// Directory to search child module files in,
951 /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
952 pub dir_path: PathBuf,
956 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
958 mod_path: self.mod_path.clone(),
959 file_path_stack: self.file_path_stack.clone(),
966 pub struct ExpansionData {
969 pub module: Rc<ModuleData>,
970 pub dir_ownership: DirOwnership,
971 pub prior_type_ascription: Option<(Span, bool)>,
972 /// Some parent node that is close to this macro call
973 pub lint_node_id: NodeId,
974 pub is_trailing_mac: bool,
977 /// One of these is made during expansion and incrementally updated as we go;
978 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
979 /// -> expn_data` of their expansion context stored into their span.
980 pub struct ExtCtxt<'a> {
981 pub sess: &'a Session,
982 pub ecfg: expand::ExpansionConfig<'a>,
983 pub reduced_recursion_limit: Option<Limit>,
984 pub root_path: PathBuf,
985 pub resolver: &'a mut dyn ResolverExpand,
986 pub current_expansion: ExpansionData,
987 /// Error recovery mode entered when expansion is stuck
988 /// (or during eager expansion, but that's a hack).
989 pub force_mode: bool,
990 pub expansions: FxHashMap<Span, Vec<String>>,
991 /// Used for running pre-expansion lints on freshly loaded modules.
992 pub(super) lint_store: LintStoreExpandDyn<'a>,
993 /// When we 'expand' an inert attribute, we leave it
994 /// in the AST, but insert it here so that we know
995 /// not to expand it again.
996 pub(super) expanded_inert_attrs: MarkedAttrs,
999 impl<'a> ExtCtxt<'a> {
1002 ecfg: expand::ExpansionConfig<'a>,
1003 resolver: &'a mut dyn ResolverExpand,
1004 lint_store: LintStoreExpandDyn<'a>,
1009 reduced_recursion_limit: None,
1012 root_path: PathBuf::new(),
1013 current_expansion: ExpansionData {
1014 id: LocalExpnId::ROOT,
1016 module: Default::default(),
1017 dir_ownership: DirOwnership::Owned { relative: None },
1018 prior_type_ascription: None,
1019 lint_node_id: ast::CRATE_NODE_ID,
1020 is_trailing_mac: false,
1023 expansions: FxHashMap::default(),
1024 expanded_inert_attrs: MarkedAttrs::new(),
1028 /// Returns a `Folder` for deeply expanding all macros in an AST node.
1029 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1030 expand::MacroExpander::new(self, false)
1033 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1034 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1035 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1036 expand::MacroExpander::new(self, true)
1038 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1039 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1041 pub fn source_map(&self) -> &'a SourceMap {
1042 self.sess.parse_sess.source_map()
1044 pub fn parse_sess(&self) -> &'a ParseSess {
1045 &self.sess.parse_sess
1047 pub fn call_site(&self) -> Span {
1048 self.current_expansion.id.expn_data().call_site
1051 /// Returns the current expansion kind's description.
1052 pub(crate) fn expansion_descr(&self) -> String {
1053 let expn_data = self.current_expansion.id.expn_data();
1054 expn_data.kind.descr()
1057 /// Equivalent of `Span::def_site` from the proc macro API,
1058 /// except that the location is taken from the span passed as an argument.
1059 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1060 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1063 /// Equivalent of `Span::call_site` from the proc macro API,
1064 /// except that the location is taken from the span passed as an argument.
1065 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1066 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1069 /// Equivalent of `Span::mixed_site` from the proc macro API,
1070 /// except that the location is taken from the span passed as an argument.
1071 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1072 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1075 /// Returns span for the macro which originally caused the current expansion to happen.
1077 /// Stops backtracing at include! boundary.
1078 pub fn expansion_cause(&self) -> Option<Span> {
1079 self.current_expansion.id.expansion_cause()
1082 pub fn struct_span_err<S: Into<MultiSpan>>(
1086 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1087 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1090 /// Emit `msg` attached to `sp`, without immediately stopping
1093 /// Compilation will be stopped in the near future (at the end of
1094 /// the macro expansion phase).
1095 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1096 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1098 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1099 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1101 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1102 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1104 pub fn trace_macros_diag(&mut self) {
1105 for (sp, notes) in self.expansions.iter() {
1106 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1112 // Fixme: does this result in errors?
1113 self.expansions.clear();
1115 pub fn bug(&self, msg: &str) -> ! {
1116 self.sess.parse_sess.span_diagnostic.bug(msg);
1118 pub fn trace_macros(&self) -> bool {
1121 pub fn set_trace_macros(&mut self, x: bool) {
1122 self.ecfg.trace_mac = x
1124 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1125 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1126 iter::once(Ident::new(kw::DollarCrate, def_site))
1127 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1130 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1131 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1132 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1135 pub fn check_unused_macros(&mut self) {
1136 self.resolver.check_unused_macros();
1140 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1142 /// This unifies the logic used for resolving `include_X!`.
1143 pub fn resolve_path(
1144 parse_sess: &ParseSess,
1145 path: impl Into<PathBuf>,
1147 ) -> PResult<'_, PathBuf> {
1148 let path = path.into();
1150 // Relative paths are resolved relative to the file in which they are found
1151 // after macro expansion (that is, they are unhygienic).
1152 if !path.is_absolute() {
1153 let callsite = span.source_callsite();
1154 let mut result = match parse_sess.source_map().span_to_filename(callsite) {
1155 FileName::Real(name) => name
1157 .expect("attempting to resolve a file path in an external file"),
1158 FileName::DocTest(path, _) => path,
1160 return Err(parse_sess.span_diagnostic.struct_span_err(
1163 "cannot resolve relative path in non-file source `{}`",
1164 parse_sess.source_map().filename_for_diagnostics(&other)
1177 /// Extracts a string literal from the macro expanded version of `expr`,
1178 /// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
1179 /// The returned bool indicates whether an applicable suggestion has already been
1180 /// added to the diagnostic to avoid emitting multiple suggestions. `Err(None)`
1181 /// indicates that an ast error was encountered.
1182 pub fn expr_to_spanned_string<'a>(
1183 cx: &'a mut ExtCtxt<'_>,
1186 ) -> Result<(Symbol, ast::StrStyle, Span), Option<(DiagnosticBuilder<'a, ErrorGuaranteed>, bool)>> {
1187 // Perform eager expansion on the expression.
1188 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1189 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1191 Err(match expr.kind {
1192 ast::ExprKind::Lit(ref l) => match l.kind {
1193 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1194 ast::LitKind::ByteStr(_) => {
1195 let mut err = cx.struct_span_err(l.span, err_msg);
1196 err.span_suggestion(
1197 expr.span.shrink_to_lo(),
1198 "consider removing the leading `b`",
1200 Applicability::MaybeIncorrect,
1204 ast::LitKind::Err(_) => None,
1205 _ => Some((cx.struct_span_err(l.span, err_msg), false)),
1207 ast::ExprKind::Err => None,
1208 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1212 /// Extracts a string literal from the macro expanded version of `expr`,
1213 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1214 /// compilation on error, merely emits a non-fatal error and returns `None`.
1215 pub fn expr_to_string(
1216 cx: &mut ExtCtxt<'_>,
1219 ) -> Option<(Symbol, ast::StrStyle)> {
1220 expr_to_spanned_string(cx, expr, err_msg)
1222 err.map(|(mut err, _)| {
1227 .map(|(symbol, style, _)| (symbol, style))
1230 /// Non-fatally assert that `tts` is empty. Note that this function
1231 /// returns even when `tts` is non-empty, macros that *need* to stop
1232 /// compilation should call
1233 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1234 /// done as rarely as possible).
1235 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1236 if !tts.is_empty() {
1237 cx.span_err(sp, &format!("{} takes no arguments", name));
1241 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1242 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1243 match p.parse_expr() {
1244 Ok(e) => return Some(e),
1249 while p.token != token::Eof {
1255 /// Interpreting `tts` as a comma-separated sequence of expressions,
1256 /// expect exactly one string literal, or emit an error and return `None`.
1257 pub fn get_single_str_from_tts(
1258 cx: &mut ExtCtxt<'_>,
1262 ) -> Option<Symbol> {
1263 let mut p = cx.new_parser_from_tts(tts);
1264 if p.token == token::Eof {
1265 cx.span_err(sp, &format!("{} takes 1 argument", name));
1268 let ret = parse_expr(&mut p)?;
1269 let _ = p.eat(&token::Comma);
1271 if p.token != token::Eof {
1272 cx.span_err(sp, &format!("{} takes 1 argument", name));
1274 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s)
1277 /// Extracts comma-separated expressions from `tts`.
1278 /// On error, emit it, and return `None`.
1279 pub fn get_exprs_from_tts(
1280 cx: &mut ExtCtxt<'_>,
1283 ) -> Option<Vec<P<ast::Expr>>> {
1284 let mut p = cx.new_parser_from_tts(tts);
1285 let mut es = Vec::new();
1286 while p.token != token::Eof {
1287 let expr = parse_expr(&mut p)?;
1289 // Perform eager expansion on the expression.
1290 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1291 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1294 if p.eat(&token::Comma) {
1297 if p.token != token::Eof {
1298 cx.span_err(sp, "expected token: `,`");
1305 pub fn parse_macro_name_and_helper_attrs(
1306 diag: &rustc_errors::Handler,
1309 ) -> Option<(Symbol, Vec<Symbol>)> {
1310 // Once we've located the `#[proc_macro_derive]` attribute, verify
1311 // that it's of the form `#[proc_macro_derive(Foo)]` or
1312 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1313 let list = attr.meta_item_list()?;
1314 if list.len() != 1 && list.len() != 2 {
1315 diag.span_err(attr.span, "attribute must have either one or two arguments");
1318 let Some(trait_attr) = list[0].meta_item() else {
1319 diag.span_err(list[0].span(), "not a meta item");
1322 let trait_ident = match trait_attr.ident() {
1323 Some(trait_ident) if trait_attr.is_word() => trait_ident,
1325 diag.span_err(trait_attr.span, "must only be one word");
1330 if !trait_ident.name.can_be_raw() {
1333 &format!("`{}` cannot be a name of {} macro", trait_ident, descr),
1337 let attributes_attr = list.get(1);
1338 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1339 if !attr.has_name(sym::attributes) {
1340 diag.span_err(attr.span(), "second argument must be `attributes`");
1342 attr.meta_item_list()
1343 .unwrap_or_else(|| {
1344 diag.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
1348 .filter_map(|attr| {
1349 let Some(attr) = attr.meta_item() else {
1350 diag.span_err(attr.span(), "not a meta item");
1354 let ident = match attr.ident() {
1355 Some(ident) if attr.is_word() => ident,
1357 diag.span_err(attr.span, "must only be one word");
1361 if !ident.name.can_be_raw() {
1364 &format!("`{}` cannot be a name of derive helper attribute", ident),
1375 Some((trait_ident.name, proc_attrs))
1378 /// This nonterminal looks like some specific enums from
1379 /// `proc-macro-hack` and `procedural-masquerade` crates.
1380 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1381 /// asserts in old versions of those crates and their wide use in the ecosystem.
1382 /// See issue #73345 for more details.
1383 /// FIXME(#73933): Remove this eventually.
1384 fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool {
1385 let name = item.ident.name;
1386 if name == sym::ProceduralMasqueradeDummyType {
1387 if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1388 if let [variant] = &*enum_def.variants {
1389 if variant.ident.name == sym::Input {
1390 sess.buffer_lint_with_diagnostic(
1391 &PROC_MACRO_BACK_COMPAT,
1394 "using `procedural-masquerade` crate",
1395 BuiltinLintDiagnostics::ProcMacroBackCompat(
1396 "The `procedural-masquerade` crate has been unnecessary since Rust 1.30.0. \
1397 Versions of this crate below 0.1.7 will eventually stop compiling.".to_string())
1407 pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &ParseSess) -> bool {
1408 let item = match ann {
1409 Annotatable::Item(item) => item,
1410 Annotatable::Stmt(stmt) => match &stmt.kind {
1411 ast::StmtKind::Item(item) => item,
1416 pretty_printing_compatibility_hack(item, sess)
1419 pub(crate) fn nt_pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1420 let item = match nt {
1421 Nonterminal::NtItem(item) => item,
1422 Nonterminal::NtStmt(stmt) => match &stmt.kind {
1423 ast::StmtKind::Item(item) => item,
1428 pretty_printing_compatibility_hack(item, sess)