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::TokenStream;
8 use rustc_ast::visit::{AssocCtxt, Visitor};
9 use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind};
10 use rustc_attr::{self as attr, Deprecation, Stability};
11 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
12 use rustc_data_structures::sync::{self, Lrc};
14 Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult,
16 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
17 use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics};
18 use rustc_parse::{self, parser, MACRO_ARGUMENTS};
19 use rustc_session::{parse::ParseSess, Limit, Session};
20 use rustc_span::def_id::{CrateNum, DefId, LocalDefId};
21 use rustc_span::edition::Edition;
22 use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId};
23 use rustc_span::source_map::SourceMap;
24 use rustc_span::symbol::{kw, sym, Ident, Symbol};
25 use rustc_span::{BytePos, FileName, RealFileName, Span, DUMMY_SP};
26 use smallvec::{smallvec, SmallVec};
28 use std::default::Default;
30 use std::path::PathBuf;
33 pub(crate) use rustc_span::hygiene::MacroKind;
35 // When adding new variants, make sure to
36 // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
37 // to use `assign_id!`
38 #[derive(Debug, Clone)]
39 pub enum Annotatable {
41 TraitItem(P<ast::AssocItem>),
42 ImplItem(P<ast::AssocItem>),
43 ForeignItem(P<ast::ForeignItem>),
47 ExprField(ast::ExprField),
48 PatField(ast::PatField),
49 GenericParam(ast::GenericParam),
51 FieldDef(ast::FieldDef),
52 Variant(ast::Variant),
57 pub fn span(&self) -> Span {
59 Annotatable::Item(ref item) => item.span,
60 Annotatable::TraitItem(ref trait_item) => trait_item.span,
61 Annotatable::ImplItem(ref impl_item) => impl_item.span,
62 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
63 Annotatable::Stmt(ref stmt) => stmt.span,
64 Annotatable::Expr(ref expr) => expr.span,
65 Annotatable::Arm(ref arm) => arm.span,
66 Annotatable::ExprField(ref field) => field.span,
67 Annotatable::PatField(ref fp) => fp.pat.span,
68 Annotatable::GenericParam(ref gp) => gp.ident.span,
69 Annotatable::Param(ref p) => p.span,
70 Annotatable::FieldDef(ref sf) => sf.span,
71 Annotatable::Variant(ref v) => v.span,
72 Annotatable::Crate(ref c) => c.spans.inner_span,
76 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
78 Annotatable::Item(item) => item.visit_attrs(f),
79 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
80 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
81 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
82 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
83 Annotatable::Expr(expr) => expr.visit_attrs(f),
84 Annotatable::Arm(arm) => arm.visit_attrs(f),
85 Annotatable::ExprField(field) => field.visit_attrs(f),
86 Annotatable::PatField(fp) => fp.visit_attrs(f),
87 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
88 Annotatable::Param(p) => p.visit_attrs(f),
89 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
90 Annotatable::Variant(v) => v.visit_attrs(f),
91 Annotatable::Crate(c) => c.visit_attrs(f),
95 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
97 Annotatable::Item(item) => visitor.visit_item(item),
98 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
99 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
100 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
101 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
102 Annotatable::Expr(expr) => visitor.visit_expr(expr),
103 Annotatable::Arm(arm) => visitor.visit_arm(arm),
104 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
105 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
106 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
107 Annotatable::Param(p) => visitor.visit_param(p),
108 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
109 Annotatable::Variant(v) => visitor.visit_variant(v),
110 Annotatable::Crate(c) => visitor.visit_crate(c),
114 pub fn to_tokens(&self) -> TokenStream {
116 Annotatable::Item(node) => TokenStream::from_ast(node),
117 Annotatable::TraitItem(node) | Annotatable::ImplItem(node) => {
118 TokenStream::from_ast(node)
120 Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
121 Annotatable::Stmt(node) => {
122 assert!(!matches!(node.kind, ast::StmtKind::Empty));
123 TokenStream::from_ast(node)
125 Annotatable::Expr(node) => TokenStream::from_ast(node),
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 is_derive_const: bool,
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 _is_derive_const: bool,
268 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
269 ExpandResult::Ready(self(ecx, span, meta_item, item))
273 pub trait BangProcMacro {
276 ecx: &'cx mut ExtCtxt<'_>,
279 ) -> Result<TokenStream, ErrorGuaranteed>;
282 impl<F> BangProcMacro for F
284 F: Fn(TokenStream) -> TokenStream,
288 _ecx: &'cx mut ExtCtxt<'_>,
291 ) -> Result<TokenStream, ErrorGuaranteed> {
292 // FIXME setup implicit context in TLS before calling self.
297 pub trait AttrProcMacro {
300 ecx: &'cx mut ExtCtxt<'_>,
302 annotation: TokenStream,
303 annotated: TokenStream,
304 ) -> Result<TokenStream, ErrorGuaranteed>;
307 impl<F> AttrProcMacro for F
309 F: Fn(TokenStream, TokenStream) -> TokenStream,
313 _ecx: &'cx mut ExtCtxt<'_>,
315 annotation: TokenStream,
316 annotated: TokenStream,
317 ) -> Result<TokenStream, ErrorGuaranteed> {
318 // FIXME setup implicit context in TLS before calling self.
319 Ok(self(annotation, annotated))
323 /// Represents a thing that maps token trees to Macro Results
324 pub trait TTMacroExpander {
327 ecx: &'cx mut ExtCtxt<'_>,
330 ) -> Box<dyn MacResult + 'cx>;
333 pub type MacroExpanderFn =
334 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
336 impl<F> TTMacroExpander for F
338 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
342 ecx: &'cx mut ExtCtxt<'_>,
345 ) -> Box<dyn MacResult + 'cx> {
346 self(ecx, span, input)
350 // Use a macro because forwarding to a simple function has type system issues
351 macro_rules! make_stmts_default {
353 $me.make_expr().map(|e| {
354 smallvec![ast::Stmt {
355 id: ast::DUMMY_NODE_ID,
357 kind: ast::StmtKind::Expr(e),
363 /// The result of a macro expansion. The return values of the various
364 /// methods are spliced into the AST at the callsite of the macro.
365 pub trait MacResult {
366 /// Creates an expression.
367 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
371 /// Creates zero or more items.
372 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
376 /// Creates zero or more impl items.
377 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
381 /// Creates zero or more trait items.
382 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
386 /// Creates zero or more items in an `extern {}` block
387 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
391 /// Creates a pattern.
392 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
396 /// Creates zero or more statements.
398 /// By default this attempts to create an expression statement,
399 /// returning None if that fails.
400 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
401 make_stmts_default!(self)
404 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
408 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
412 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
416 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
420 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
424 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
428 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
432 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
436 fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
437 // Fn-like macros cannot produce a crate.
442 macro_rules! make_MacEager {
443 ( $( $fld:ident: $t:ty, )* ) => {
444 /// `MacResult` implementation for the common case where you've already
445 /// built each form of AST that you might return.
447 pub struct MacEager {
449 pub $fld: Option<$t>,
455 pub fn $fld(v: $t) -> Box<dyn MacResult> {
469 items: SmallVec<[P<ast::Item>; 1]>,
470 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
471 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
472 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
473 stmts: SmallVec<[ast::Stmt; 1]>,
477 impl MacResult for MacEager {
478 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
482 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
486 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
490 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
494 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
498 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
499 match self.stmts.as_ref().map_or(0, |s| s.len()) {
500 0 => make_stmts_default!(self),
505 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
506 if let Some(p) = self.pat {
509 if let Some(e) = self.expr {
510 if matches!(e.kind, ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_)) {
511 return Some(P(ast::Pat {
512 id: ast::DUMMY_NODE_ID,
514 kind: PatKind::Lit(e),
522 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
527 /// Fill-in macro expansion result, to allow compilation to continue
528 /// after hitting errors.
529 #[derive(Copy, Clone)]
530 pub struct DummyResult {
536 /// Creates a default MacResult that can be anything.
538 /// Use this as a return value after hitting any errors and
539 /// calling `span_err`.
540 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
541 Box::new(DummyResult { is_error: true, span })
544 /// Same as `any`, but must be a valid fragment, not error.
545 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
546 Box::new(DummyResult { is_error: false, span })
549 /// A plain dummy expression.
550 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
552 id: ast::DUMMY_NODE_ID,
553 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
555 attrs: ast::AttrVec::new(),
560 /// A plain dummy pattern.
561 pub fn raw_pat(sp: Span) -> ast::Pat {
562 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
565 /// A plain dummy type.
566 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
568 id: ast::DUMMY_NODE_ID,
569 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
576 impl MacResult for DummyResult {
577 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
578 Some(DummyResult::raw_expr(self.span, self.is_error))
581 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
582 Some(P(DummyResult::raw_pat(self.span)))
585 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
586 Some(SmallVec::new())
589 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
590 Some(SmallVec::new())
593 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
594 Some(SmallVec::new())
597 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
598 Some(SmallVec::new())
601 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
602 Some(smallvec![ast::Stmt {
603 id: ast::DUMMY_NODE_ID,
604 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
609 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
610 Some(DummyResult::raw_ty(self.span, self.is_error))
613 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
614 Some(SmallVec::new())
617 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
618 Some(SmallVec::new())
621 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
622 Some(SmallVec::new())
625 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
626 Some(SmallVec::new())
629 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
630 Some(SmallVec::new())
633 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
634 Some(SmallVec::new())
637 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
638 Some(SmallVec::new())
642 /// A syntax extension kind.
643 pub enum SyntaxExtensionKind {
644 /// A token-based function-like macro.
646 /// An expander with signature TokenStream -> TokenStream.
647 Box<dyn BangProcMacro + sync::Sync + sync::Send>,
650 /// An AST-based function-like macro.
652 /// An expander with signature TokenStream -> AST.
653 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
656 /// A token-based attribute macro.
658 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
659 /// The first TokenSteam is the attribute itself, the second is the annotated item.
660 /// The produced TokenSteam replaces the input TokenSteam.
661 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
664 /// An AST-based attribute macro.
666 /// An expander with signature (AST, AST) -> AST.
667 /// The first AST fragment is the attribute itself, the second is the annotated item.
668 /// The produced AST fragment replaces the input AST fragment.
669 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
672 /// A trivial attribute "macro" that does nothing,
673 /// only keeps the attribute and marks it as inert,
674 /// thus making it ineligible for further expansion.
677 /// A token-based derive macro.
679 /// An expander with signature TokenStream -> TokenStream.
680 /// The produced TokenSteam is appended to the input TokenSteam.
682 /// FIXME: The text above describes how this should work. Currently it
683 /// is handled identically to `LegacyDerive`. It should be migrated to
684 /// a token-based representation like `Bang` and `Attr`, instead of
685 /// using `MultiItemModifier`.
686 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
689 /// An AST-based derive macro.
691 /// An expander with signature AST -> AST.
692 /// The produced AST fragment is appended to the input AST fragment.
693 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
697 /// A struct representing a macro definition in "lowered" form ready for expansion.
698 pub struct SyntaxExtension {
699 /// A syntax extension kind.
700 pub kind: SyntaxExtensionKind,
701 /// Span of the macro definition.
703 /// List of unstable features that are treated as stable inside this macro.
704 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
705 /// The macro's stability info.
706 pub stability: Option<Stability>,
707 /// The macro's deprecation info.
708 pub deprecation: Option<Deprecation>,
709 /// Names of helper attributes registered by this macro.
710 pub helper_attrs: Vec<Symbol>,
711 /// Edition of the crate in which this macro is defined.
712 pub edition: Edition,
713 /// Built-in macros have a couple of special properties like availability
714 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
715 pub builtin_name: Option<Symbol>,
716 /// Suppresses the `unsafe_code` lint for code produced by this macro.
717 pub allow_internal_unsafe: bool,
718 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
719 pub local_inner_macros: bool,
720 /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
721 /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
722 pub collapse_debuginfo: bool,
725 impl SyntaxExtension {
726 /// Returns which kind of macro calls this syntax extension.
727 pub fn macro_kind(&self) -> MacroKind {
729 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
730 SyntaxExtensionKind::Attr(..)
731 | SyntaxExtensionKind::LegacyAttr(..)
732 | SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
733 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
739 /// Constructs a syntax extension with default properties.
740 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
743 allow_internal_unstable: None,
746 helper_attrs: Vec::new(),
750 allow_internal_unsafe: false,
751 local_inner_macros: false,
752 collapse_debuginfo: false,
756 /// Constructs a syntax extension with the given properties
757 /// and other properties converted from attributes.
760 kind: SyntaxExtensionKind,
762 helper_attrs: Vec<Symbol>,
765 attrs: &[ast::Attribute],
766 ) -> SyntaxExtension {
767 let allow_internal_unstable =
768 attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
770 let allow_internal_unsafe = sess.contains_name(attrs, sym::allow_internal_unsafe);
771 let local_inner_macros = sess
772 .find_by_name(attrs, sym::macro_export)
773 .and_then(|macro_export| macro_export.meta_item_list())
774 .map_or(false, |l| attr::list_contains_name(&l, sym::local_inner_macros));
775 let collapse_debuginfo = sess.contains_name(attrs, sym::collapse_debuginfo);
776 tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
778 let (builtin_name, helper_attrs) = sess
779 .find_by_name(attrs, sym::rustc_builtin_macro)
781 // Override `helper_attrs` passed above if it's a built-in macro,
782 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
783 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
784 || (Some(name), Vec::new()),
785 |(name, helper_attrs)| (Some(name), helper_attrs),
788 .unwrap_or_else(|| (None, helper_attrs));
789 let (stability, const_stability, body_stability) = attr::find_stability(&sess, attrs, span);
790 if let Some((_, sp)) = const_stability {
793 .struct_span_err(sp, "macros cannot have const stability attributes")
794 .span_label(sp, "invalid const stability attribute")
796 sess.source_map().guess_head_span(span),
797 "const stability attribute affects this macro",
801 if let Some((_, sp)) = body_stability {
804 .struct_span_err(sp, "macros cannot have body stability attributes")
805 .span_label(sp, "invalid body stability attribute")
807 sess.source_map().guess_head_span(span),
808 "body stability attribute affects this macro",
816 allow_internal_unstable: (!allow_internal_unstable.is_empty())
817 .then(|| allow_internal_unstable.into()),
818 stability: stability.map(|(s, _)| s),
819 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
823 allow_internal_unsafe,
829 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
831 _: &'cx mut ExtCtxt<'_>,
834 ) -> Box<dyn MacResult + 'cx> {
835 DummyResult::any(span)
837 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
840 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
846 ) -> Vec<Annotatable> {
849 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
852 pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
853 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
861 macro_def_id: Option<DefId>,
862 parent_module: Option<DefId>,
865 ExpnKind::Macro(self.macro_kind(), descr),
869 self.allow_internal_unstable.clone(),
873 self.allow_internal_unsafe,
874 self.local_inner_macros,
875 self.collapse_debuginfo,
880 /// Error type that denotes indeterminacy.
881 pub struct Indeterminate;
883 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>, bool)>;
885 pub trait ResolverExpand {
886 fn next_node_id(&mut self) -> NodeId;
887 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
889 fn resolve_dollar_crates(&mut self);
890 fn visit_ast_fragment_with_placeholders(
892 expn_id: LocalExpnId,
893 fragment: &AstFragment,
895 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
897 fn expansion_for_ast_pass(
902 parent_module_id: Option<NodeId>,
905 fn resolve_imports(&mut self);
907 fn resolve_macro_invocation(
910 eager_expansion_root: LocalExpnId,
912 ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
914 fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
916 fn check_unused_macros(&mut self);
918 // Resolver interfaces for specific built-in macros.
919 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
920 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
921 /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
924 expn_id: LocalExpnId,
926 derive_paths: &dyn Fn() -> DeriveResolutions,
927 ) -> Result<(), Indeterminate>;
928 /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
929 /// back from resolver.
930 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
931 /// Path resolution logic for `#[cfg_accessible(path)]`.
934 expn_id: LocalExpnId,
936 ) -> Result<bool, Indeterminate>;
938 /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
939 /// No caching is performed.
940 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
942 /// The order of items in the HIR is unrelated to the order of
943 /// items in the AST. However, we generate proc macro harnesses
944 /// based on the AST order, and later refer to these harnesses
945 /// from the HIR. This field keeps track of the order in which
946 /// we generated proc macros harnesses, so that we can map
947 /// HIR proc macros items back to their harness items.
948 fn declare_proc_macro(&mut self, id: NodeId);
950 /// Tools registered with `#![register_tool]` and used by tool attributes and lints.
951 fn registered_tools(&self) -> &FxHashSet<Ident>;
954 pub trait LintStoreExpand {
955 fn pre_expansion_lint(
958 registered_tools: &FxHashSet<Ident>,
966 type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
968 #[derive(Clone, Default)]
969 pub struct ModuleData {
970 /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
971 pub mod_path: Vec<Ident>,
972 /// Stack of paths to files loaded by out-of-line module items,
973 /// used to detect and report recursive module inclusions.
974 pub file_path_stack: Vec<PathBuf>,
975 /// Directory to search child module files in,
976 /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
977 pub dir_path: PathBuf,
981 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
983 mod_path: self.mod_path.clone(),
984 file_path_stack: self.file_path_stack.clone(),
991 pub struct ExpansionData {
994 pub module: Rc<ModuleData>,
995 pub dir_ownership: DirOwnership,
996 pub prior_type_ascription: Option<(Span, bool)>,
997 /// Some parent node that is close to this macro call
998 pub lint_node_id: NodeId,
999 pub is_trailing_mac: bool,
1002 /// One of these is made during expansion and incrementally updated as we go;
1003 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
1004 /// -> expn_data` of their expansion context stored into their span.
1005 pub struct ExtCtxt<'a> {
1006 pub sess: &'a Session,
1007 pub ecfg: expand::ExpansionConfig<'a>,
1008 pub reduced_recursion_limit: Option<Limit>,
1009 pub root_path: PathBuf,
1010 pub resolver: &'a mut dyn ResolverExpand,
1011 pub current_expansion: ExpansionData,
1012 /// Error recovery mode entered when expansion is stuck
1013 /// (or during eager expansion, but that's a hack).
1014 pub force_mode: bool,
1015 pub expansions: FxIndexMap<Span, Vec<String>>,
1016 /// Used for running pre-expansion lints on freshly loaded modules.
1017 pub(super) lint_store: LintStoreExpandDyn<'a>,
1018 /// Used for storing lints generated during expansion, like `NAMED_ARGUMENTS_USED_POSITIONALLY`
1019 pub buffered_early_lint: Vec<BufferedEarlyLint>,
1020 /// When we 'expand' an inert attribute, we leave it
1021 /// in the AST, but insert it here so that we know
1022 /// not to expand it again.
1023 pub(super) expanded_inert_attrs: MarkedAttrs,
1026 impl<'a> ExtCtxt<'a> {
1029 ecfg: expand::ExpansionConfig<'a>,
1030 resolver: &'a mut dyn ResolverExpand,
1031 lint_store: LintStoreExpandDyn<'a>,
1036 reduced_recursion_limit: None,
1039 root_path: PathBuf::new(),
1040 current_expansion: ExpansionData {
1041 id: LocalExpnId::ROOT,
1043 module: Default::default(),
1044 dir_ownership: DirOwnership::Owned { relative: None },
1045 prior_type_ascription: None,
1046 lint_node_id: ast::CRATE_NODE_ID,
1047 is_trailing_mac: false,
1050 expansions: FxIndexMap::default(),
1051 expanded_inert_attrs: MarkedAttrs::new(),
1052 buffered_early_lint: vec![],
1056 /// Returns a `Folder` for deeply expanding all macros in an AST node.
1057 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1058 expand::MacroExpander::new(self, false)
1061 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1062 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1063 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1064 expand::MacroExpander::new(self, true)
1066 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1067 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1069 pub fn source_map(&self) -> &'a SourceMap {
1070 self.sess.parse_sess.source_map()
1072 pub fn parse_sess(&self) -> &'a ParseSess {
1073 &self.sess.parse_sess
1075 pub fn call_site(&self) -> Span {
1076 self.current_expansion.id.expn_data().call_site
1079 /// Returns the current expansion kind's description.
1080 pub(crate) fn expansion_descr(&self) -> String {
1081 let expn_data = self.current_expansion.id.expn_data();
1082 expn_data.kind.descr()
1085 /// Equivalent of `Span::def_site` from the proc macro API,
1086 /// except that the location is taken from the span passed as an argument.
1087 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1088 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1091 /// Equivalent of `Span::call_site` from the proc macro API,
1092 /// except that the location is taken from the span passed as an argument.
1093 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1094 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1097 /// Equivalent of `Span::mixed_site` from the proc macro API,
1098 /// except that the location is taken from the span passed as an argument.
1099 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1100 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1103 /// Returns span for the macro which originally caused the current expansion to happen.
1105 /// Stops backtracing at include! boundary.
1106 pub fn expansion_cause(&self) -> Option<Span> {
1107 self.current_expansion.id.expansion_cause()
1110 #[rustc_lint_diagnostics]
1111 pub fn struct_span_err<S: Into<MultiSpan>>(
1115 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1116 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1121 err: impl IntoDiagnostic<'a>,
1122 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1123 self.sess.create_err(err)
1126 pub fn emit_err(&self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1127 self.sess.emit_err(err)
1130 /// Emit `msg` attached to `sp`, without immediately stopping
1133 /// Compilation will be stopped in the near future (at the end of
1134 /// the macro expansion phase).
1135 #[rustc_lint_diagnostics]
1136 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1137 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1139 #[rustc_lint_diagnostics]
1140 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1141 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1143 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1144 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1146 pub fn trace_macros_diag(&mut self) {
1147 for (sp, notes) in self.expansions.iter() {
1148 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1154 // Fixme: does this result in errors?
1155 self.expansions.clear();
1157 pub fn bug(&self, msg: &str) -> ! {
1158 self.sess.parse_sess.span_diagnostic.bug(msg);
1160 pub fn trace_macros(&self) -> bool {
1163 pub fn set_trace_macros(&mut self, x: bool) {
1164 self.ecfg.trace_mac = x
1166 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1167 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1168 iter::once(Ident::new(kw::DollarCrate, def_site))
1169 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1172 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1173 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1174 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1177 pub fn check_unused_macros(&mut self) {
1178 self.resolver.check_unused_macros();
1182 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1184 /// This unifies the logic used for resolving `include_X!`.
1185 pub fn resolve_path(
1186 parse_sess: &ParseSess,
1187 path: impl Into<PathBuf>,
1189 ) -> PResult<'_, PathBuf> {
1190 let path = path.into();
1192 // Relative paths are resolved relative to the file in which they are found
1193 // after macro expansion (that is, they are unhygienic).
1194 if !path.is_absolute() {
1195 let callsite = span.source_callsite();
1196 let mut result = match parse_sess.source_map().span_to_filename(callsite) {
1197 FileName::Real(name) => name
1199 .expect("attempting to resolve a file path in an external file"),
1200 FileName::DocTest(path, _) => path,
1202 return Err(parse_sess.span_diagnostic.struct_span_err(
1205 "cannot resolve relative path in non-file source `{}`",
1206 parse_sess.source_map().filename_for_diagnostics(&other)
1219 /// Extracts a string literal from the macro expanded version of `expr`,
1220 /// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
1221 /// The returned bool indicates whether an applicable suggestion has already been
1222 /// added to the diagnostic to avoid emitting multiple suggestions. `Err(None)`
1223 /// indicates that an ast error was encountered.
1224 pub fn expr_to_spanned_string<'a>(
1225 cx: &'a mut ExtCtxt<'_>,
1228 ) -> Result<(Symbol, ast::StrStyle, Span), Option<(DiagnosticBuilder<'a, ErrorGuaranteed>, bool)>> {
1229 // Perform eager expansion on the expression.
1230 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1231 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1233 Err(match expr.kind {
1234 ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
1235 Ok(ast::LitKind::Str(s, style)) => return Ok((s, style, expr.span)),
1236 Ok(ast::LitKind::ByteStr(_)) => {
1237 let mut err = cx.struct_span_err(expr.span, err_msg);
1238 let span = expr.span.shrink_to_lo();
1239 err.span_suggestion(
1240 span.with_hi(span.lo() + BytePos(1)),
1241 "consider removing the leading `b`",
1243 Applicability::MaybeIncorrect,
1247 Ok(ast::LitKind::Err) => None,
1249 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1251 ast::ExprKind::Err => None,
1252 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1256 /// Extracts a string literal from the macro expanded version of `expr`,
1257 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1258 /// compilation on error, merely emits a non-fatal error and returns `None`.
1259 pub fn expr_to_string(
1260 cx: &mut ExtCtxt<'_>,
1263 ) -> Option<(Symbol, ast::StrStyle)> {
1264 expr_to_spanned_string(cx, expr, err_msg)
1266 err.map(|(mut err, _)| {
1271 .map(|(symbol, style, _)| (symbol, style))
1274 /// Non-fatally assert that `tts` is empty. Note that this function
1275 /// returns even when `tts` is non-empty, macros that *need* to stop
1276 /// compilation should call
1277 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1278 /// done as rarely as possible).
1279 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1280 if !tts.is_empty() {
1281 cx.span_err(sp, &format!("{} takes no arguments", name));
1285 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1286 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1287 match p.parse_expr() {
1288 Ok(e) => return Some(e),
1293 while p.token != token::Eof {
1299 /// Interpreting `tts` as a comma-separated sequence of expressions,
1300 /// expect exactly one string literal, or emit an error and return `None`.
1301 pub fn get_single_str_from_tts(
1302 cx: &mut ExtCtxt<'_>,
1306 ) -> Option<Symbol> {
1307 let mut p = cx.new_parser_from_tts(tts);
1308 if p.token == token::Eof {
1309 cx.span_err(sp, &format!("{} takes 1 argument", name));
1312 let ret = parse_expr(&mut p)?;
1313 let _ = p.eat(&token::Comma);
1315 if p.token != token::Eof {
1316 cx.span_err(sp, &format!("{} takes 1 argument", name));
1318 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s)
1321 /// Extracts comma-separated expressions from `tts`.
1322 /// On error, emit it, and return `None`.
1323 pub fn get_exprs_from_tts(
1324 cx: &mut ExtCtxt<'_>,
1327 ) -> Option<Vec<P<ast::Expr>>> {
1328 let mut p = cx.new_parser_from_tts(tts);
1329 let mut es = Vec::new();
1330 while p.token != token::Eof {
1331 let expr = parse_expr(&mut p)?;
1333 // Perform eager expansion on the expression.
1334 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1335 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1338 if p.eat(&token::Comma) {
1341 if p.token != token::Eof {
1342 cx.span_err(sp, "expected token: `,`");
1349 pub fn parse_macro_name_and_helper_attrs(
1350 diag: &rustc_errors::Handler,
1353 ) -> Option<(Symbol, Vec<Symbol>)> {
1354 // Once we've located the `#[proc_macro_derive]` attribute, verify
1355 // that it's of the form `#[proc_macro_derive(Foo)]` or
1356 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1357 let list = attr.meta_item_list()?;
1358 if list.len() != 1 && list.len() != 2 {
1359 diag.span_err(attr.span, "attribute must have either one or two arguments");
1362 let Some(trait_attr) = list[0].meta_item() else {
1363 diag.span_err(list[0].span(), "not a meta item");
1366 let trait_ident = match trait_attr.ident() {
1367 Some(trait_ident) if trait_attr.is_word() => trait_ident,
1369 diag.span_err(trait_attr.span, "must only be one word");
1374 if !trait_ident.name.can_be_raw() {
1377 &format!("`{}` cannot be a name of {} macro", trait_ident, descr),
1381 let attributes_attr = list.get(1);
1382 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1383 if !attr.has_name(sym::attributes) {
1384 diag.span_err(attr.span(), "second argument must be `attributes`");
1386 attr.meta_item_list()
1387 .unwrap_or_else(|| {
1388 diag.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
1392 .filter_map(|attr| {
1393 let Some(attr) = attr.meta_item() else {
1394 diag.span_err(attr.span(), "not a meta item");
1398 let ident = match attr.ident() {
1399 Some(ident) if attr.is_word() => ident,
1401 diag.span_err(attr.span, "must only be one word");
1405 if !ident.name.can_be_raw() {
1408 &format!("`{}` cannot be a name of derive helper attribute", ident),
1419 Some((trait_ident.name, proc_attrs))
1422 /// This nonterminal looks like some specific enums from
1423 /// `proc-macro-hack` and `procedural-masquerade` crates.
1424 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1425 /// asserts in old versions of those crates and their wide use in the ecosystem.
1426 /// See issue #73345 for more details.
1427 /// FIXME(#73933): Remove this eventually.
1428 fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool {
1429 let name = item.ident.name;
1430 if name == sym::ProceduralMasqueradeDummyType {
1431 if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1432 if let [variant] = &*enum_def.variants {
1433 if variant.ident.name == sym::Input {
1434 let filename = sess.source_map().span_to_filename(item.ident.span);
1435 if let FileName::Real(RealFileName::LocalPath(path)) = filename {
1436 if let Some(c) = path
1438 .flat_map(|c| c.as_os_str().to_str())
1439 .find(|c| c.starts_with("rental") || c.starts_with("allsorts-rental"))
1441 let crate_matches = if c.starts_with("allsorts-rental") {
1444 let mut version = c.trim_start_matches("rental-").split('.');
1445 version.next() == Some("0")
1446 && version.next() == Some("5")
1449 .and_then(|c| c.parse::<u32>().ok())
1450 .map_or(false, |v| v < 6)
1454 sess.buffer_lint_with_diagnostic(
1455 &PROC_MACRO_BACK_COMPAT,
1458 "using an old version of `rental`",
1459 BuiltinLintDiagnostics::ProcMacroBackCompat(
1460 "older versions of the `rental` crate will stop compiling in future versions of Rust; \
1461 please update to `rental` v0.5.6, or switch to one of the `rental` alternatives".to_string()
1475 pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &ParseSess) -> bool {
1476 let item = match ann {
1477 Annotatable::Item(item) => item,
1478 Annotatable::Stmt(stmt) => match &stmt.kind {
1479 ast::StmtKind::Item(item) => item,
1484 pretty_printing_compatibility_hack(item, sess)
1487 pub(crate) fn nt_pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1488 let item = match nt {
1489 Nonterminal::NtItem(item) => item,
1490 Nonterminal::NtStmt(stmt) => match &stmt.kind {
1491 ast::StmtKind::Item(item) => item,
1496 pretty_printing_compatibility_hack(item, sess)