1 #![deny(rustc::untranslatable_diagnostic)]
4 ArgumentNotAttributes, AttrNoArguments, AttributeMetaItem, AttributeSingleWord,
5 AttributesWrongForm, CannotBeNameOfMacro, ExpectedCommaInList, HelperAttributeNameInvalid,
6 MacroBodyStability, MacroConstStability, NotAMetaItem, OnlyOneArgument, OnlyOneWord,
7 ResolveRelativePath, TakesNoArguments,
9 use crate::expand::{self, AstFragment, Invocation};
10 use crate::module::DirOwnership;
12 use rustc_ast::attr::MarkedAttrs;
13 use rustc_ast::ptr::P;
14 use rustc_ast::token::{self, Nonterminal};
15 use rustc_ast::tokenstream::TokenStream;
16 use rustc_ast::visit::{AssocCtxt, Visitor};
17 use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind};
18 use rustc_attr::{self as attr, Deprecation, Stability};
19 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
20 use rustc_data_structures::sync::{self, Lrc};
22 Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult,
24 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
25 use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics};
26 use rustc_parse::{self, parser, MACRO_ARGUMENTS};
27 use rustc_session::errors::report_lit_error;
28 use rustc_session::{parse::ParseSess, Limit, Session};
29 use rustc_span::def_id::{CrateNum, DefId, LocalDefId};
30 use rustc_span::edition::Edition;
31 use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId};
32 use rustc_span::source_map::SourceMap;
33 use rustc_span::symbol::{kw, sym, Ident, Symbol};
34 use rustc_span::{BytePos, FileName, RealFileName, Span, DUMMY_SP};
35 use smallvec::{smallvec, SmallVec};
38 use std::path::PathBuf;
41 pub(crate) use rustc_span::hygiene::MacroKind;
43 // When adding new variants, make sure to
44 // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
45 // to use `assign_id!`
46 #[derive(Debug, Clone)]
47 pub enum Annotatable {
49 TraitItem(P<ast::AssocItem>),
50 ImplItem(P<ast::AssocItem>),
51 ForeignItem(P<ast::ForeignItem>),
55 ExprField(ast::ExprField),
56 PatField(ast::PatField),
57 GenericParam(ast::GenericParam),
59 FieldDef(ast::FieldDef),
60 Variant(ast::Variant),
65 pub fn span(&self) -> Span {
67 Annotatable::Item(ref item) => item.span,
68 Annotatable::TraitItem(ref trait_item) => trait_item.span,
69 Annotatable::ImplItem(ref impl_item) => impl_item.span,
70 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
71 Annotatable::Stmt(ref stmt) => stmt.span,
72 Annotatable::Expr(ref expr) => expr.span,
73 Annotatable::Arm(ref arm) => arm.span,
74 Annotatable::ExprField(ref field) => field.span,
75 Annotatable::PatField(ref fp) => fp.pat.span,
76 Annotatable::GenericParam(ref gp) => gp.ident.span,
77 Annotatable::Param(ref p) => p.span,
78 Annotatable::FieldDef(ref sf) => sf.span,
79 Annotatable::Variant(ref v) => v.span,
80 Annotatable::Crate(ref c) => c.spans.inner_span,
84 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
86 Annotatable::Item(item) => item.visit_attrs(f),
87 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
88 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
89 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
90 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
91 Annotatable::Expr(expr) => expr.visit_attrs(f),
92 Annotatable::Arm(arm) => arm.visit_attrs(f),
93 Annotatable::ExprField(field) => field.visit_attrs(f),
94 Annotatable::PatField(fp) => fp.visit_attrs(f),
95 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
96 Annotatable::Param(p) => p.visit_attrs(f),
97 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
98 Annotatable::Variant(v) => v.visit_attrs(f),
99 Annotatable::Crate(c) => c.visit_attrs(f),
103 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
105 Annotatable::Item(item) => visitor.visit_item(item),
106 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
107 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
108 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
109 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
110 Annotatable::Expr(expr) => visitor.visit_expr(expr),
111 Annotatable::Arm(arm) => visitor.visit_arm(arm),
112 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
113 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
114 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
115 Annotatable::Param(p) => visitor.visit_param(p),
116 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
117 Annotatable::Variant(v) => visitor.visit_variant(v),
118 Annotatable::Crate(c) => visitor.visit_crate(c),
122 pub fn to_tokens(&self) -> TokenStream {
124 Annotatable::Item(node) => TokenStream::from_ast(node),
125 Annotatable::TraitItem(node) | Annotatable::ImplItem(node) => {
126 TokenStream::from_ast(node)
128 Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
129 Annotatable::Stmt(node) => {
130 assert!(!matches!(node.kind, ast::StmtKind::Empty));
131 TokenStream::from_ast(node)
133 Annotatable::Expr(node) => TokenStream::from_ast(node),
135 | Annotatable::ExprField(..)
136 | Annotatable::PatField(..)
137 | Annotatable::GenericParam(..)
138 | Annotatable::Param(..)
139 | Annotatable::FieldDef(..)
140 | Annotatable::Variant(..)
141 | Annotatable::Crate(..) => panic!("unexpected annotatable"),
145 pub fn expect_item(self) -> P<ast::Item> {
147 Annotatable::Item(i) => i,
148 _ => panic!("expected Item"),
152 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
154 Annotatable::TraitItem(i) => i,
155 _ => panic!("expected Item"),
159 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
161 Annotatable::ImplItem(i) => i,
162 _ => panic!("expected Item"),
166 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
168 Annotatable::ForeignItem(i) => i,
169 _ => panic!("expected foreign item"),
173 pub fn expect_stmt(self) -> ast::Stmt {
175 Annotatable::Stmt(stmt) => stmt.into_inner(),
176 _ => panic!("expected statement"),
180 pub fn expect_expr(self) -> P<ast::Expr> {
182 Annotatable::Expr(expr) => expr,
183 _ => panic!("expected expression"),
187 pub fn expect_arm(self) -> ast::Arm {
189 Annotatable::Arm(arm) => arm,
190 _ => panic!("expected match arm"),
194 pub fn expect_expr_field(self) -> ast::ExprField {
196 Annotatable::ExprField(field) => field,
197 _ => panic!("expected field"),
201 pub fn expect_pat_field(self) -> ast::PatField {
203 Annotatable::PatField(fp) => fp,
204 _ => panic!("expected field pattern"),
208 pub fn expect_generic_param(self) -> ast::GenericParam {
210 Annotatable::GenericParam(gp) => gp,
211 _ => panic!("expected generic parameter"),
215 pub fn expect_param(self) -> ast::Param {
217 Annotatable::Param(param) => param,
218 _ => panic!("expected parameter"),
222 pub fn expect_field_def(self) -> ast::FieldDef {
224 Annotatable::FieldDef(sf) => sf,
225 _ => panic!("expected struct field"),
229 pub fn expect_variant(self) -> ast::Variant {
231 Annotatable::Variant(v) => v,
232 _ => panic!("expected variant"),
236 pub fn expect_crate(self) -> ast::Crate {
238 Annotatable::Crate(krate) => krate,
239 _ => panic!("expected krate"),
244 /// Result of an expansion that may need to be retried.
245 /// Consider using this for non-`MultiItemModifier` expanders as well.
246 pub enum ExpandResult<T, U> {
247 /// Expansion produced a result (possibly dummy).
249 /// Expansion could not produce a result and needs to be retried.
253 pub trait MultiItemModifier {
254 /// `meta_item` is the attribute, and `item` is the item being modified.
257 ecx: &mut ExtCtxt<'_>,
259 meta_item: &ast::MetaItem,
261 is_derive_const: bool,
262 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
265 impl<F> MultiItemModifier for F
267 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
271 ecx: &mut ExtCtxt<'_>,
273 meta_item: &ast::MetaItem,
275 _is_derive_const: bool,
276 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
277 ExpandResult::Ready(self(ecx, span, meta_item, item))
281 pub trait BangProcMacro {
284 ecx: &'cx mut ExtCtxt<'_>,
287 ) -> Result<TokenStream, ErrorGuaranteed>;
290 impl<F> BangProcMacro for F
292 F: Fn(TokenStream) -> TokenStream,
296 _ecx: &'cx mut ExtCtxt<'_>,
299 ) -> Result<TokenStream, ErrorGuaranteed> {
300 // FIXME setup implicit context in TLS before calling self.
305 pub trait AttrProcMacro {
308 ecx: &'cx mut ExtCtxt<'_>,
310 annotation: TokenStream,
311 annotated: TokenStream,
312 ) -> Result<TokenStream, ErrorGuaranteed>;
315 impl<F> AttrProcMacro for F
317 F: Fn(TokenStream, TokenStream) -> TokenStream,
321 _ecx: &'cx mut ExtCtxt<'_>,
323 annotation: TokenStream,
324 annotated: TokenStream,
325 ) -> Result<TokenStream, ErrorGuaranteed> {
326 // FIXME setup implicit context in TLS before calling self.
327 Ok(self(annotation, annotated))
331 /// Represents a thing that maps token trees to Macro Results
332 pub trait TTMacroExpander {
335 ecx: &'cx mut ExtCtxt<'_>,
338 ) -> Box<dyn MacResult + 'cx>;
341 pub type MacroExpanderFn =
342 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
344 impl<F> TTMacroExpander for F
346 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
350 ecx: &'cx mut ExtCtxt<'_>,
353 ) -> Box<dyn MacResult + 'cx> {
354 self(ecx, span, input)
358 // Use a macro because forwarding to a simple function has type system issues
359 macro_rules! make_stmts_default {
361 $me.make_expr().map(|e| {
362 smallvec![ast::Stmt {
363 id: ast::DUMMY_NODE_ID,
365 kind: ast::StmtKind::Expr(e),
371 /// The result of a macro expansion. The return values of the various
372 /// methods are spliced into the AST at the callsite of the macro.
373 pub trait MacResult {
374 /// Creates an expression.
375 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
379 /// Creates zero or more items.
380 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
384 /// Creates zero or more impl items.
385 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
389 /// Creates zero or more trait items.
390 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
394 /// Creates zero or more items in an `extern {}` block
395 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
399 /// Creates a pattern.
400 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
404 /// Creates zero or more statements.
406 /// By default this attempts to create an expression statement,
407 /// returning None if that fails.
408 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
409 make_stmts_default!(self)
412 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
416 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
420 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
424 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
428 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
432 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
436 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
440 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
444 fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
445 // Fn-like macros cannot produce a crate.
450 macro_rules! make_MacEager {
451 ( $( $fld:ident: $t:ty, )* ) => {
452 /// `MacResult` implementation for the common case where you've already
453 /// built each form of AST that you might return.
455 pub struct MacEager {
457 pub $fld: Option<$t>,
463 pub fn $fld(v: $t) -> Box<dyn MacResult> {
477 items: SmallVec<[P<ast::Item>; 1]>,
478 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
479 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
480 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
481 stmts: SmallVec<[ast::Stmt; 1]>,
485 impl MacResult for MacEager {
486 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
490 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
494 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
498 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
502 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
506 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
507 match self.stmts.as_ref().map_or(0, |s| s.len()) {
508 0 => make_stmts_default!(self),
513 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
514 if let Some(p) = self.pat {
517 if let Some(e) = self.expr {
518 if matches!(e.kind, ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_)) {
519 return Some(P(ast::Pat {
520 id: ast::DUMMY_NODE_ID,
522 kind: PatKind::Lit(e),
530 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
535 /// Fill-in macro expansion result, to allow compilation to continue
536 /// after hitting errors.
537 #[derive(Copy, Clone)]
538 pub struct DummyResult {
544 /// Creates a default MacResult that can be anything.
546 /// Use this as a return value after hitting any errors and
547 /// calling `span_err`.
548 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
549 Box::new(DummyResult { is_error: true, span })
552 /// Same as `any`, but must be a valid fragment, not error.
553 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
554 Box::new(DummyResult { is_error: false, span })
557 /// A plain dummy expression.
558 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
560 id: ast::DUMMY_NODE_ID,
561 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
563 attrs: ast::AttrVec::new(),
568 /// A plain dummy pattern.
569 pub fn raw_pat(sp: Span) -> ast::Pat {
570 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
573 /// A plain dummy type.
574 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
576 id: ast::DUMMY_NODE_ID,
577 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
584 impl MacResult for DummyResult {
585 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
586 Some(DummyResult::raw_expr(self.span, self.is_error))
589 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
590 Some(P(DummyResult::raw_pat(self.span)))
593 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
594 Some(SmallVec::new())
597 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
598 Some(SmallVec::new())
601 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
602 Some(SmallVec::new())
605 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
606 Some(SmallVec::new())
609 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
610 Some(smallvec![ast::Stmt {
611 id: ast::DUMMY_NODE_ID,
612 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
617 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
618 Some(DummyResult::raw_ty(self.span, self.is_error))
621 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
622 Some(SmallVec::new())
625 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
626 Some(SmallVec::new())
629 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
630 Some(SmallVec::new())
633 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
634 Some(SmallVec::new())
637 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
638 Some(SmallVec::new())
641 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
642 Some(SmallVec::new())
645 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
646 Some(SmallVec::new())
650 /// A syntax extension kind.
651 pub enum SyntaxExtensionKind {
652 /// A token-based function-like macro.
654 /// An expander with signature TokenStream -> TokenStream.
655 Box<dyn BangProcMacro + sync::Sync + sync::Send>,
658 /// An AST-based function-like macro.
660 /// An expander with signature TokenStream -> AST.
661 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
664 /// A token-based attribute macro.
666 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
667 /// The first TokenSteam is the attribute itself, the second is the annotated item.
668 /// The produced TokenSteam replaces the input TokenSteam.
669 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
672 /// An AST-based attribute macro.
674 /// An expander with signature (AST, AST) -> AST.
675 /// The first AST fragment is the attribute itself, the second is the annotated item.
676 /// The produced AST fragment replaces the input AST fragment.
677 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
680 /// A trivial attribute "macro" that does nothing,
681 /// only keeps the attribute and marks it as inert,
682 /// thus making it ineligible for further expansion.
685 /// A token-based derive macro.
687 /// An expander with signature TokenStream -> TokenStream.
688 /// The produced TokenSteam is appended to the input TokenSteam.
690 /// FIXME: The text above describes how this should work. Currently it
691 /// is handled identically to `LegacyDerive`. It should be migrated to
692 /// a token-based representation like `Bang` and `Attr`, instead of
693 /// using `MultiItemModifier`.
694 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
697 /// An AST-based derive macro.
699 /// An expander with signature AST -> AST.
700 /// The produced AST fragment is appended to the input AST fragment.
701 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
705 /// A struct representing a macro definition in "lowered" form ready for expansion.
706 pub struct SyntaxExtension {
707 /// A syntax extension kind.
708 pub kind: SyntaxExtensionKind,
709 /// Span of the macro definition.
711 /// List of unstable features that are treated as stable inside this macro.
712 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
713 /// The macro's stability info.
714 pub stability: Option<Stability>,
715 /// The macro's deprecation info.
716 pub deprecation: Option<Deprecation>,
717 /// Names of helper attributes registered by this macro.
718 pub helper_attrs: Vec<Symbol>,
719 /// Edition of the crate in which this macro is defined.
720 pub edition: Edition,
721 /// Built-in macros have a couple of special properties like availability
722 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
723 pub builtin_name: Option<Symbol>,
724 /// Suppresses the `unsafe_code` lint for code produced by this macro.
725 pub allow_internal_unsafe: bool,
726 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
727 pub local_inner_macros: bool,
728 /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
729 /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
730 pub collapse_debuginfo: bool,
733 impl SyntaxExtension {
734 /// Returns which kind of macro calls this syntax extension.
735 pub fn macro_kind(&self) -> MacroKind {
737 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
738 SyntaxExtensionKind::Attr(..)
739 | SyntaxExtensionKind::LegacyAttr(..)
740 | SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
741 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
747 /// Constructs a syntax extension with default properties.
748 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
751 allow_internal_unstable: None,
754 helper_attrs: Vec::new(),
758 allow_internal_unsafe: false,
759 local_inner_macros: false,
760 collapse_debuginfo: false,
764 /// Constructs a syntax extension with the given properties
765 /// and other properties converted from attributes.
768 kind: SyntaxExtensionKind,
770 helper_attrs: Vec<Symbol>,
773 attrs: &[ast::Attribute],
774 ) -> SyntaxExtension {
775 let allow_internal_unstable =
776 attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
778 let allow_internal_unsafe = sess.contains_name(attrs, sym::allow_internal_unsafe);
779 let local_inner_macros = sess
780 .find_by_name(attrs, sym::macro_export)
781 .and_then(|macro_export| macro_export.meta_item_list())
782 .map_or(false, |l| attr::list_contains_name(&l, sym::local_inner_macros));
783 let collapse_debuginfo = sess.contains_name(attrs, sym::collapse_debuginfo);
784 tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
786 let (builtin_name, helper_attrs) = sess
787 .find_by_name(attrs, sym::rustc_builtin_macro)
789 // Override `helper_attrs` passed above if it's a built-in macro,
790 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
791 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
792 || (Some(name), Vec::new()),
793 |(name, helper_attrs)| (Some(name), helper_attrs),
796 .unwrap_or_else(|| (None, helper_attrs));
797 let (stability, const_stability, body_stability) = attr::find_stability(&sess, attrs, span);
798 if let Some((_, sp)) = const_stability {
799 sess.emit_err(MacroConstStability {
801 head_span: sess.source_map().guess_head_span(span),
804 if let Some((_, sp)) = body_stability {
805 sess.emit_err(MacroBodyStability {
807 head_span: sess.source_map().guess_head_span(span),
814 allow_internal_unstable: (!allow_internal_unstable.is_empty())
815 .then(|| allow_internal_unstable.into()),
816 stability: stability.map(|(s, _)| s),
817 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
821 allow_internal_unsafe,
827 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
829 _: &'cx mut ExtCtxt<'_>,
832 ) -> Box<dyn MacResult + 'cx> {
833 DummyResult::any(span)
835 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
838 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
844 ) -> Vec<Annotatable> {
847 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
850 pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
851 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
859 macro_def_id: Option<DefId>,
860 parent_module: Option<DefId>,
863 ExpnKind::Macro(self.macro_kind(), descr),
867 self.allow_internal_unstable.clone(),
871 self.allow_internal_unsafe,
872 self.local_inner_macros,
873 self.collapse_debuginfo,
878 /// Error type that denotes indeterminacy.
879 pub struct Indeterminate;
881 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>, bool)>;
883 pub trait ResolverExpand {
884 fn next_node_id(&mut self) -> NodeId;
885 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
887 fn resolve_dollar_crates(&mut self);
888 fn visit_ast_fragment_with_placeholders(
890 expn_id: LocalExpnId,
891 fragment: &AstFragment,
893 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
895 fn expansion_for_ast_pass(
900 parent_module_id: Option<NodeId>,
903 fn resolve_imports(&mut self);
905 fn resolve_macro_invocation(
908 eager_expansion_root: LocalExpnId,
910 ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
912 fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
914 fn check_unused_macros(&mut self);
916 // Resolver interfaces for specific built-in macros.
917 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
918 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
919 /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
922 expn_id: LocalExpnId,
924 derive_paths: &dyn Fn() -> DeriveResolutions,
925 ) -> Result<(), Indeterminate>;
926 /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
927 /// back from resolver.
928 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
929 /// Path resolution logic for `#[cfg_accessible(path)]`.
932 expn_id: LocalExpnId,
934 ) -> Result<bool, Indeterminate>;
936 /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
937 /// No caching is performed.
938 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
940 /// The order of items in the HIR is unrelated to the order of
941 /// items in the AST. However, we generate proc macro harnesses
942 /// based on the AST order, and later refer to these harnesses
943 /// from the HIR. This field keeps track of the order in which
944 /// we generated proc macros harnesses, so that we can map
945 /// HIR proc macros items back to their harness items.
946 fn declare_proc_macro(&mut self, id: NodeId);
948 /// Tools registered with `#![register_tool]` and used by tool attributes and lints.
949 fn registered_tools(&self) -> &FxHashSet<Ident>;
952 pub trait LintStoreExpand {
953 fn pre_expansion_lint(
956 registered_tools: &FxHashSet<Ident>,
964 type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
966 #[derive(Clone, Default)]
967 pub struct ModuleData {
968 /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
969 pub mod_path: Vec<Ident>,
970 /// Stack of paths to files loaded by out-of-line module items,
971 /// used to detect and report recursive module inclusions.
972 pub file_path_stack: Vec<PathBuf>,
973 /// Directory to search child module files in,
974 /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
975 pub dir_path: PathBuf,
979 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
981 mod_path: self.mod_path.clone(),
982 file_path_stack: self.file_path_stack.clone(),
989 pub struct ExpansionData {
992 pub module: Rc<ModuleData>,
993 pub dir_ownership: DirOwnership,
994 pub prior_type_ascription: Option<(Span, bool)>,
995 /// Some parent node that is close to this macro call
996 pub lint_node_id: NodeId,
997 pub is_trailing_mac: bool,
1000 /// One of these is made during expansion and incrementally updated as we go;
1001 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
1002 /// -> expn_data` of their expansion context stored into their span.
1003 pub struct ExtCtxt<'a> {
1004 pub sess: &'a Session,
1005 pub ecfg: expand::ExpansionConfig<'a>,
1006 pub reduced_recursion_limit: Option<Limit>,
1007 pub root_path: PathBuf,
1008 pub resolver: &'a mut dyn ResolverExpand,
1009 pub current_expansion: ExpansionData,
1010 /// Error recovery mode entered when expansion is stuck
1011 /// (or during eager expansion, but that's a hack).
1012 pub force_mode: bool,
1013 pub expansions: FxIndexMap<Span, Vec<String>>,
1014 /// Used for running pre-expansion lints on freshly loaded modules.
1015 pub(super) lint_store: LintStoreExpandDyn<'a>,
1016 /// Used for storing lints generated during expansion, like `NAMED_ARGUMENTS_USED_POSITIONALLY`
1017 pub buffered_early_lint: Vec<BufferedEarlyLint>,
1018 /// When we 'expand' an inert attribute, we leave it
1019 /// in the AST, but insert it here so that we know
1020 /// not to expand it again.
1021 pub(super) expanded_inert_attrs: MarkedAttrs,
1024 impl<'a> ExtCtxt<'a> {
1027 ecfg: expand::ExpansionConfig<'a>,
1028 resolver: &'a mut dyn ResolverExpand,
1029 lint_store: LintStoreExpandDyn<'a>,
1034 reduced_recursion_limit: None,
1037 root_path: PathBuf::new(),
1038 current_expansion: ExpansionData {
1039 id: LocalExpnId::ROOT,
1041 module: Default::default(),
1042 dir_ownership: DirOwnership::Owned { relative: None },
1043 prior_type_ascription: None,
1044 lint_node_id: ast::CRATE_NODE_ID,
1045 is_trailing_mac: false,
1048 expansions: FxIndexMap::default(),
1049 expanded_inert_attrs: MarkedAttrs::new(),
1050 buffered_early_lint: vec![],
1054 /// Returns a `Folder` for deeply expanding all macros in an AST node.
1055 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1056 expand::MacroExpander::new(self, false)
1059 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1060 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1061 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1062 expand::MacroExpander::new(self, true)
1064 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1065 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1067 pub fn source_map(&self) -> &'a SourceMap {
1068 self.sess.parse_sess.source_map()
1070 pub fn parse_sess(&self) -> &'a ParseSess {
1071 &self.sess.parse_sess
1073 pub fn call_site(&self) -> Span {
1074 self.current_expansion.id.expn_data().call_site
1077 /// Returns the current expansion kind's description.
1078 pub(crate) fn expansion_descr(&self) -> String {
1079 let expn_data = self.current_expansion.id.expn_data();
1080 expn_data.kind.descr()
1083 /// Equivalent of `Span::def_site` from the proc macro API,
1084 /// except that the location is taken from the span passed as an argument.
1085 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1086 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1089 /// Equivalent of `Span::call_site` from the proc macro API,
1090 /// except that the location is taken from the span passed as an argument.
1091 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1092 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1095 /// Equivalent of `Span::mixed_site` from the proc macro API,
1096 /// except that the location is taken from the span passed as an argument.
1097 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1098 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1101 /// Returns span for the macro which originally caused the current expansion to happen.
1103 /// Stops backtracing at include! boundary.
1104 pub fn expansion_cause(&self) -> Option<Span> {
1105 self.current_expansion.id.expansion_cause()
1108 #[rustc_lint_diagnostics]
1109 pub fn struct_span_err<S: Into<MultiSpan>>(
1113 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1114 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1119 err: impl IntoDiagnostic<'a>,
1120 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1121 self.sess.create_err(err)
1124 pub fn emit_err(&self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1125 self.sess.emit_err(err)
1128 /// Emit `msg` attached to `sp`, without immediately stopping
1131 /// Compilation will be stopped in the near future (at the end of
1132 /// the macro expansion phase).
1133 #[rustc_lint_diagnostics]
1134 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1135 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1137 #[rustc_lint_diagnostics]
1138 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1139 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1141 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1142 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1144 pub fn trace_macros_diag(&mut self) {
1145 for (sp, notes) in self.expansions.iter() {
1146 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1152 // Fixme: does this result in errors?
1153 self.expansions.clear();
1155 pub fn bug(&self, msg: &str) -> ! {
1156 self.sess.parse_sess.span_diagnostic.bug(msg);
1158 pub fn trace_macros(&self) -> bool {
1161 pub fn set_trace_macros(&mut self, x: bool) {
1162 self.ecfg.trace_mac = x
1164 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1165 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1166 iter::once(Ident::new(kw::DollarCrate, def_site))
1167 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1170 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1171 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1172 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1175 pub fn check_unused_macros(&mut self) {
1176 self.resolver.check_unused_macros();
1180 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1182 /// This unifies the logic used for resolving `include_X!`.
1183 pub fn resolve_path(
1184 parse_sess: &ParseSess,
1185 path: impl Into<PathBuf>,
1187 ) -> PResult<'_, PathBuf> {
1188 let path = path.into();
1190 // Relative paths are resolved relative to the file in which they are found
1191 // after macro expansion (that is, they are unhygienic).
1192 if !path.is_absolute() {
1193 let callsite = span.source_callsite();
1194 let mut result = match parse_sess.source_map().span_to_filename(callsite) {
1195 FileName::Real(name) => name
1197 .expect("attempting to resolve a file path in an external file"),
1198 FileName::DocTest(path, _) => path,
1200 return Err(ResolveRelativePath {
1202 path: parse_sess.source_map().filename_for_diagnostics(&other).to_string(),
1204 .into_diagnostic(&parse_sess.span_diagnostic));
1215 /// Extracts a string literal from the macro expanded version of `expr`,
1216 /// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
1217 /// The returned bool indicates whether an applicable suggestion has already been
1218 /// added to the diagnostic to avoid emitting multiple suggestions. `Err(None)`
1219 /// indicates that an ast error was encountered.
1220 // FIXME(Nilstrieb) Make this function setup translatable
1221 #[allow(rustc::untranslatable_diagnostic)]
1222 pub fn expr_to_spanned_string<'a>(
1223 cx: &'a mut ExtCtxt<'_>,
1226 ) -> Result<(Symbol, ast::StrStyle, Span), Option<(DiagnosticBuilder<'a, ErrorGuaranteed>, bool)>> {
1227 // Perform eager expansion on the expression.
1228 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1229 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1231 Err(match expr.kind {
1232 ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
1233 Ok(ast::LitKind::Str(s, style)) => return Ok((s, style, expr.span)),
1234 Ok(ast::LitKind::ByteStr(_)) => {
1235 let mut err = cx.struct_span_err(expr.span, err_msg);
1236 let span = expr.span.shrink_to_lo();
1237 err.span_suggestion(
1238 span.with_hi(span.lo() + BytePos(1)),
1239 "consider removing the leading `b`",
1241 Applicability::MaybeIncorrect,
1245 Ok(ast::LitKind::Err) => None,
1247 report_lit_error(&cx.sess.parse_sess, err, token_lit, expr.span);
1250 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1252 ast::ExprKind::Err => None,
1253 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1257 /// Extracts a string literal from the macro expanded version of `expr`,
1258 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1259 /// compilation on error, merely emits a non-fatal error and returns `None`.
1260 pub fn expr_to_string(
1261 cx: &mut ExtCtxt<'_>,
1264 ) -> Option<(Symbol, ast::StrStyle)> {
1265 expr_to_spanned_string(cx, expr, err_msg)
1267 err.map(|(mut err, _)| {
1272 .map(|(symbol, style, _)| (symbol, style))
1275 /// Non-fatally assert that `tts` is empty. Note that this function
1276 /// returns even when `tts` is non-empty, macros that *need* to stop
1277 /// compilation should call
1278 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1279 /// done as rarely as possible).
1280 pub fn check_zero_tts(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream, name: &str) {
1281 if !tts.is_empty() {
1282 cx.emit_err(TakesNoArguments { span, name });
1286 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1287 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1288 match p.parse_expr() {
1289 Ok(e) => return Some(e),
1294 while p.token != token::Eof {
1300 /// Interpreting `tts` as a comma-separated sequence of expressions,
1301 /// expect exactly one string literal, or emit an error and return `None`.
1302 pub fn get_single_str_from_tts(
1303 cx: &mut ExtCtxt<'_>,
1307 ) -> Option<Symbol> {
1308 let mut p = cx.new_parser_from_tts(tts);
1309 if p.token == token::Eof {
1310 cx.emit_err(OnlyOneArgument { span, name });
1313 let ret = parse_expr(&mut p)?;
1314 let _ = p.eat(&token::Comma);
1316 if p.token != token::Eof {
1317 cx.emit_err(OnlyOneArgument { span, name });
1319 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s)
1322 /// Extracts comma-separated expressions from `tts`.
1323 /// On error, emit it, and return `None`.
1324 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>, tts: TokenStream) -> Option<Vec<P<ast::Expr>>> {
1325 let mut p = cx.new_parser_from_tts(tts);
1326 let mut es = Vec::new();
1327 while p.token != token::Eof {
1328 let expr = parse_expr(&mut p)?;
1330 // Perform eager expansion on the expression.
1331 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1332 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1335 if p.eat(&token::Comma) {
1338 if p.token != token::Eof {
1339 cx.emit_err(ExpectedCommaInList { span: p.token.span });
1346 pub fn parse_macro_name_and_helper_attrs(
1347 diag: &rustc_errors::Handler,
1350 ) -> Option<(Symbol, Vec<Symbol>)> {
1351 // Once we've located the `#[proc_macro_derive]` attribute, verify
1352 // that it's of the form `#[proc_macro_derive(Foo)]` or
1353 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1354 let list = attr.meta_item_list()?;
1355 if list.len() != 1 && list.len() != 2 {
1356 diag.emit_err(AttrNoArguments { span: attr.span });
1359 let Some(trait_attr) = list[0].meta_item() else {
1360 diag.emit_err(NotAMetaItem {span: list[0].span()});
1363 let trait_ident = match trait_attr.ident() {
1364 Some(trait_ident) if trait_attr.is_word() => trait_ident,
1366 diag.emit_err(OnlyOneWord { span: trait_attr.span });
1371 if !trait_ident.name.can_be_raw() {
1372 diag.emit_err(CannotBeNameOfMacro { span: trait_attr.span, trait_ident, macro_type });
1375 let attributes_attr = list.get(1);
1376 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1377 if !attr.has_name(sym::attributes) {
1378 diag.emit_err(ArgumentNotAttributes { span: attr.span() });
1380 attr.meta_item_list()
1381 .unwrap_or_else(|| {
1382 diag.emit_err(AttributesWrongForm { span: attr.span() });
1386 .filter_map(|attr| {
1387 let Some(attr) = attr.meta_item() else {
1388 diag.emit_err(AttributeMetaItem { span: attr.span() });
1392 let ident = match attr.ident() {
1393 Some(ident) if attr.is_word() => ident,
1395 diag.emit_err(AttributeSingleWord { span: attr.span });
1399 if !ident.name.can_be_raw() {
1400 diag.emit_err(HelperAttributeNameInvalid { span: attr.span, name: ident });
1410 Some((trait_ident.name, proc_attrs))
1413 /// This nonterminal looks like some specific enums from
1414 /// `proc-macro-hack` and `procedural-masquerade` crates.
1415 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1416 /// asserts in old versions of those crates and their wide use in the ecosystem.
1417 /// See issue #73345 for more details.
1418 /// FIXME(#73933): Remove this eventually.
1419 fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool {
1420 let name = item.ident.name;
1421 if name == sym::ProceduralMasqueradeDummyType {
1422 if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1423 if let [variant] = &*enum_def.variants {
1424 if variant.ident.name == sym::Input {
1425 let filename = sess.source_map().span_to_filename(item.ident.span);
1426 if let FileName::Real(RealFileName::LocalPath(path)) = filename {
1427 if let Some(c) = path
1429 .flat_map(|c| c.as_os_str().to_str())
1430 .find(|c| c.starts_with("rental") || c.starts_with("allsorts-rental"))
1432 let crate_matches = if c.starts_with("allsorts-rental") {
1435 let mut version = c.trim_start_matches("rental-").split('.');
1436 version.next() == Some("0")
1437 && version.next() == Some("5")
1440 .and_then(|c| c.parse::<u32>().ok())
1441 .map_or(false, |v| v < 6)
1445 sess.buffer_lint_with_diagnostic(
1446 &PROC_MACRO_BACK_COMPAT,
1449 "using an old version of `rental`",
1450 BuiltinLintDiagnostics::ProcMacroBackCompat(
1451 "older versions of the `rental` crate will stop compiling in future versions of Rust; \
1452 please update to `rental` v0.5.6, or switch to one of the `rental` alternatives".to_string()
1466 pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &ParseSess) -> bool {
1467 let item = match ann {
1468 Annotatable::Item(item) => item,
1469 Annotatable::Stmt(stmt) => match &stmt.kind {
1470 ast::StmtKind::Item(item) => item,
1475 pretty_printing_compatibility_hack(item, sess)
1478 pub(crate) fn nt_pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1479 let item = match nt {
1480 Nonterminal::NtItem(item) => item,
1481 Nonterminal::NtStmt(stmt) => match &stmt.kind {
1482 ast::StmtKind::Item(item) => item,
1487 pretty_printing_compatibility_hack(item, sess)