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};
37 use std::default::Default;
39 use std::path::PathBuf;
42 pub(crate) use rustc_span::hygiene::MacroKind;
44 // When adding new variants, make sure to
45 // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
46 // to use `assign_id!`
47 #[derive(Debug, Clone)]
48 pub enum Annotatable {
50 TraitItem(P<ast::AssocItem>),
51 ImplItem(P<ast::AssocItem>),
52 ForeignItem(P<ast::ForeignItem>),
56 ExprField(ast::ExprField),
57 PatField(ast::PatField),
58 GenericParam(ast::GenericParam),
60 FieldDef(ast::FieldDef),
61 Variant(ast::Variant),
66 pub fn span(&self) -> Span {
68 Annotatable::Item(ref item) => item.span,
69 Annotatable::TraitItem(ref trait_item) => trait_item.span,
70 Annotatable::ImplItem(ref impl_item) => impl_item.span,
71 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
72 Annotatable::Stmt(ref stmt) => stmt.span,
73 Annotatable::Expr(ref expr) => expr.span,
74 Annotatable::Arm(ref arm) => arm.span,
75 Annotatable::ExprField(ref field) => field.span,
76 Annotatable::PatField(ref fp) => fp.pat.span,
77 Annotatable::GenericParam(ref gp) => gp.ident.span,
78 Annotatable::Param(ref p) => p.span,
79 Annotatable::FieldDef(ref sf) => sf.span,
80 Annotatable::Variant(ref v) => v.span,
81 Annotatable::Crate(ref c) => c.spans.inner_span,
85 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
87 Annotatable::Item(item) => item.visit_attrs(f),
88 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
89 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
90 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
91 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
92 Annotatable::Expr(expr) => expr.visit_attrs(f),
93 Annotatable::Arm(arm) => arm.visit_attrs(f),
94 Annotatable::ExprField(field) => field.visit_attrs(f),
95 Annotatable::PatField(fp) => fp.visit_attrs(f),
96 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
97 Annotatable::Param(p) => p.visit_attrs(f),
98 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
99 Annotatable::Variant(v) => v.visit_attrs(f),
100 Annotatable::Crate(c) => c.visit_attrs(f),
104 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
106 Annotatable::Item(item) => visitor.visit_item(item),
107 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
108 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
109 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
110 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
111 Annotatable::Expr(expr) => visitor.visit_expr(expr),
112 Annotatable::Arm(arm) => visitor.visit_arm(arm),
113 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
114 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
115 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
116 Annotatable::Param(p) => visitor.visit_param(p),
117 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
118 Annotatable::Variant(v) => visitor.visit_variant(v),
119 Annotatable::Crate(c) => visitor.visit_crate(c),
123 pub fn to_tokens(&self) -> TokenStream {
125 Annotatable::Item(node) => TokenStream::from_ast(node),
126 Annotatable::TraitItem(node) | Annotatable::ImplItem(node) => {
127 TokenStream::from_ast(node)
129 Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
130 Annotatable::Stmt(node) => {
131 assert!(!matches!(node.kind, ast::StmtKind::Empty));
132 TokenStream::from_ast(node)
134 Annotatable::Expr(node) => TokenStream::from_ast(node),
136 | Annotatable::ExprField(..)
137 | Annotatable::PatField(..)
138 | Annotatable::GenericParam(..)
139 | Annotatable::Param(..)
140 | Annotatable::FieldDef(..)
141 | Annotatable::Variant(..)
142 | Annotatable::Crate(..) => panic!("unexpected annotatable"),
146 pub fn expect_item(self) -> P<ast::Item> {
148 Annotatable::Item(i) => i,
149 _ => panic!("expected Item"),
153 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
155 Annotatable::TraitItem(i) => i,
156 _ => panic!("expected Item"),
160 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
162 Annotatable::ImplItem(i) => i,
163 _ => panic!("expected Item"),
167 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
169 Annotatable::ForeignItem(i) => i,
170 _ => panic!("expected foreign item"),
174 pub fn expect_stmt(self) -> ast::Stmt {
176 Annotatable::Stmt(stmt) => stmt.into_inner(),
177 _ => panic!("expected statement"),
181 pub fn expect_expr(self) -> P<ast::Expr> {
183 Annotatable::Expr(expr) => expr,
184 _ => panic!("expected expression"),
188 pub fn expect_arm(self) -> ast::Arm {
190 Annotatable::Arm(arm) => arm,
191 _ => panic!("expected match arm"),
195 pub fn expect_expr_field(self) -> ast::ExprField {
197 Annotatable::ExprField(field) => field,
198 _ => panic!("expected field"),
202 pub fn expect_pat_field(self) -> ast::PatField {
204 Annotatable::PatField(fp) => fp,
205 _ => panic!("expected field pattern"),
209 pub fn expect_generic_param(self) -> ast::GenericParam {
211 Annotatable::GenericParam(gp) => gp,
212 _ => panic!("expected generic parameter"),
216 pub fn expect_param(self) -> ast::Param {
218 Annotatable::Param(param) => param,
219 _ => panic!("expected parameter"),
223 pub fn expect_field_def(self) -> ast::FieldDef {
225 Annotatable::FieldDef(sf) => sf,
226 _ => panic!("expected struct field"),
230 pub fn expect_variant(self) -> ast::Variant {
232 Annotatable::Variant(v) => v,
233 _ => panic!("expected variant"),
237 pub fn expect_crate(self) -> ast::Crate {
239 Annotatable::Crate(krate) => krate,
240 _ => panic!("expected krate"),
245 /// Result of an expansion that may need to be retried.
246 /// Consider using this for non-`MultiItemModifier` expanders as well.
247 pub enum ExpandResult<T, U> {
248 /// Expansion produced a result (possibly dummy).
250 /// Expansion could not produce a result and needs to be retried.
254 pub trait MultiItemModifier {
255 /// `meta_item` is the attribute, and `item` is the item being modified.
258 ecx: &mut ExtCtxt<'_>,
260 meta_item: &ast::MetaItem,
262 is_derive_const: bool,
263 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
266 impl<F> MultiItemModifier for F
268 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
272 ecx: &mut ExtCtxt<'_>,
274 meta_item: &ast::MetaItem,
276 _is_derive_const: bool,
277 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
278 ExpandResult::Ready(self(ecx, span, meta_item, item))
282 pub trait BangProcMacro {
285 ecx: &'cx mut ExtCtxt<'_>,
288 ) -> Result<TokenStream, ErrorGuaranteed>;
291 impl<F> BangProcMacro for F
293 F: Fn(TokenStream) -> TokenStream,
297 _ecx: &'cx mut ExtCtxt<'_>,
300 ) -> Result<TokenStream, ErrorGuaranteed> {
301 // FIXME setup implicit context in TLS before calling self.
306 pub trait AttrProcMacro {
309 ecx: &'cx mut ExtCtxt<'_>,
311 annotation: TokenStream,
312 annotated: TokenStream,
313 ) -> Result<TokenStream, ErrorGuaranteed>;
316 impl<F> AttrProcMacro for F
318 F: Fn(TokenStream, TokenStream) -> TokenStream,
322 _ecx: &'cx mut ExtCtxt<'_>,
324 annotation: TokenStream,
325 annotated: TokenStream,
326 ) -> Result<TokenStream, ErrorGuaranteed> {
327 // FIXME setup implicit context in TLS before calling self.
328 Ok(self(annotation, annotated))
332 /// Represents a thing that maps token trees to Macro Results
333 pub trait TTMacroExpander {
336 ecx: &'cx mut ExtCtxt<'_>,
339 ) -> Box<dyn MacResult + 'cx>;
342 pub type MacroExpanderFn =
343 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
345 impl<F> TTMacroExpander for F
347 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
351 ecx: &'cx mut ExtCtxt<'_>,
354 ) -> Box<dyn MacResult + 'cx> {
355 self(ecx, span, input)
359 // Use a macro because forwarding to a simple function has type system issues
360 macro_rules! make_stmts_default {
362 $me.make_expr().map(|e| {
363 smallvec![ast::Stmt {
364 id: ast::DUMMY_NODE_ID,
366 kind: ast::StmtKind::Expr(e),
372 /// The result of a macro expansion. The return values of the various
373 /// methods are spliced into the AST at the callsite of the macro.
374 pub trait MacResult {
375 /// Creates an expression.
376 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
380 /// Creates zero or more items.
381 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
385 /// Creates zero or more impl items.
386 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
390 /// Creates zero or more trait items.
391 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
395 /// Creates zero or more items in an `extern {}` block
396 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
400 /// Creates a pattern.
401 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
405 /// Creates zero or more statements.
407 /// By default this attempts to create an expression statement,
408 /// returning None if that fails.
409 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
410 make_stmts_default!(self)
413 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
417 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
421 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
425 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
429 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
433 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
437 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
441 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
445 fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
446 // Fn-like macros cannot produce a crate.
451 macro_rules! make_MacEager {
452 ( $( $fld:ident: $t:ty, )* ) => {
453 /// `MacResult` implementation for the common case where you've already
454 /// built each form of AST that you might return.
456 pub struct MacEager {
458 pub $fld: Option<$t>,
464 pub fn $fld(v: $t) -> Box<dyn MacResult> {
478 items: SmallVec<[P<ast::Item>; 1]>,
479 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
480 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
481 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
482 stmts: SmallVec<[ast::Stmt; 1]>,
486 impl MacResult for MacEager {
487 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
491 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
495 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
499 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
503 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
507 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
508 match self.stmts.as_ref().map_or(0, |s| s.len()) {
509 0 => make_stmts_default!(self),
514 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
515 if let Some(p) = self.pat {
518 if let Some(e) = self.expr {
519 if matches!(e.kind, ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_)) {
520 return Some(P(ast::Pat {
521 id: ast::DUMMY_NODE_ID,
523 kind: PatKind::Lit(e),
531 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
536 /// Fill-in macro expansion result, to allow compilation to continue
537 /// after hitting errors.
538 #[derive(Copy, Clone)]
539 pub struct DummyResult {
545 /// Creates a default MacResult that can be anything.
547 /// Use this as a return value after hitting any errors and
548 /// calling `span_err`.
549 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
550 Box::new(DummyResult { is_error: true, span })
553 /// Same as `any`, but must be a valid fragment, not error.
554 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
555 Box::new(DummyResult { is_error: false, span })
558 /// A plain dummy expression.
559 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
561 id: ast::DUMMY_NODE_ID,
562 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
564 attrs: ast::AttrVec::new(),
569 /// A plain dummy pattern.
570 pub fn raw_pat(sp: Span) -> ast::Pat {
571 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
574 /// A plain dummy type.
575 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
577 id: ast::DUMMY_NODE_ID,
578 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
585 impl MacResult for DummyResult {
586 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
587 Some(DummyResult::raw_expr(self.span, self.is_error))
590 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
591 Some(P(DummyResult::raw_pat(self.span)))
594 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
595 Some(SmallVec::new())
598 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
599 Some(SmallVec::new())
602 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
603 Some(SmallVec::new())
606 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
607 Some(SmallVec::new())
610 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
611 Some(smallvec![ast::Stmt {
612 id: ast::DUMMY_NODE_ID,
613 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
618 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
619 Some(DummyResult::raw_ty(self.span, self.is_error))
622 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
623 Some(SmallVec::new())
626 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
627 Some(SmallVec::new())
630 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
631 Some(SmallVec::new())
634 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
635 Some(SmallVec::new())
638 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
639 Some(SmallVec::new())
642 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
643 Some(SmallVec::new())
646 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
647 Some(SmallVec::new())
651 /// A syntax extension kind.
652 pub enum SyntaxExtensionKind {
653 /// A token-based function-like macro.
655 /// An expander with signature TokenStream -> TokenStream.
656 Box<dyn BangProcMacro + sync::Sync + sync::Send>,
659 /// An AST-based function-like macro.
661 /// An expander with signature TokenStream -> AST.
662 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
665 /// A token-based attribute macro.
667 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
668 /// The first TokenSteam is the attribute itself, the second is the annotated item.
669 /// The produced TokenSteam replaces the input TokenSteam.
670 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
673 /// An AST-based attribute macro.
675 /// An expander with signature (AST, AST) -> AST.
676 /// The first AST fragment is the attribute itself, the second is the annotated item.
677 /// The produced AST fragment replaces the input AST fragment.
678 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
681 /// A trivial attribute "macro" that does nothing,
682 /// only keeps the attribute and marks it as inert,
683 /// thus making it ineligible for further expansion.
686 /// A token-based derive macro.
688 /// An expander with signature TokenStream -> TokenStream.
689 /// The produced TokenSteam is appended to the input TokenSteam.
691 /// FIXME: The text above describes how this should work. Currently it
692 /// is handled identically to `LegacyDerive`. It should be migrated to
693 /// a token-based representation like `Bang` and `Attr`, instead of
694 /// using `MultiItemModifier`.
695 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
698 /// An AST-based derive macro.
700 /// An expander with signature AST -> AST.
701 /// The produced AST fragment is appended to the input AST fragment.
702 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
706 /// A struct representing a macro definition in "lowered" form ready for expansion.
707 pub struct SyntaxExtension {
708 /// A syntax extension kind.
709 pub kind: SyntaxExtensionKind,
710 /// Span of the macro definition.
712 /// List of unstable features that are treated as stable inside this macro.
713 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
714 /// The macro's stability info.
715 pub stability: Option<Stability>,
716 /// The macro's deprecation info.
717 pub deprecation: Option<Deprecation>,
718 /// Names of helper attributes registered by this macro.
719 pub helper_attrs: Vec<Symbol>,
720 /// Edition of the crate in which this macro is defined.
721 pub edition: Edition,
722 /// Built-in macros have a couple of special properties like availability
723 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
724 pub builtin_name: Option<Symbol>,
725 /// Suppresses the `unsafe_code` lint for code produced by this macro.
726 pub allow_internal_unsafe: bool,
727 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
728 pub local_inner_macros: bool,
729 /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
730 /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
731 pub collapse_debuginfo: bool,
734 impl SyntaxExtension {
735 /// Returns which kind of macro calls this syntax extension.
736 pub fn macro_kind(&self) -> MacroKind {
738 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
739 SyntaxExtensionKind::Attr(..)
740 | SyntaxExtensionKind::LegacyAttr(..)
741 | SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
742 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
748 /// Constructs a syntax extension with default properties.
749 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
752 allow_internal_unstable: None,
755 helper_attrs: Vec::new(),
759 allow_internal_unsafe: false,
760 local_inner_macros: false,
761 collapse_debuginfo: false,
765 /// Constructs a syntax extension with the given properties
766 /// and other properties converted from attributes.
769 kind: SyntaxExtensionKind,
771 helper_attrs: Vec<Symbol>,
774 attrs: &[ast::Attribute],
775 ) -> SyntaxExtension {
776 let allow_internal_unstable =
777 attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
779 let allow_internal_unsafe = sess.contains_name(attrs, sym::allow_internal_unsafe);
780 let local_inner_macros = sess
781 .find_by_name(attrs, sym::macro_export)
782 .and_then(|macro_export| macro_export.meta_item_list())
783 .map_or(false, |l| attr::list_contains_name(&l, sym::local_inner_macros));
784 let collapse_debuginfo = sess.contains_name(attrs, sym::collapse_debuginfo);
785 tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
787 let (builtin_name, helper_attrs) = sess
788 .find_by_name(attrs, sym::rustc_builtin_macro)
790 // Override `helper_attrs` passed above if it's a built-in macro,
791 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
792 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
793 || (Some(name), Vec::new()),
794 |(name, helper_attrs)| (Some(name), helper_attrs),
797 .unwrap_or_else(|| (None, helper_attrs));
798 let (stability, const_stability, body_stability) = attr::find_stability(&sess, attrs, span);
799 if let Some((_, sp)) = const_stability {
800 sess.emit_err(MacroConstStability {
802 head_span: sess.source_map().guess_head_span(span),
805 if let Some((_, sp)) = body_stability {
806 sess.emit_err(MacroBodyStability {
808 head_span: sess.source_map().guess_head_span(span),
815 allow_internal_unstable: (!allow_internal_unstable.is_empty())
816 .then(|| allow_internal_unstable.into()),
817 stability: stability.map(|(s, _)| s),
818 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
822 allow_internal_unsafe,
828 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
830 _: &'cx mut ExtCtxt<'_>,
833 ) -> Box<dyn MacResult + 'cx> {
834 DummyResult::any(span)
836 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
839 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
845 ) -> Vec<Annotatable> {
848 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
851 pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
852 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
860 macro_def_id: Option<DefId>,
861 parent_module: Option<DefId>,
864 ExpnKind::Macro(self.macro_kind(), descr),
868 self.allow_internal_unstable.clone(),
872 self.allow_internal_unsafe,
873 self.local_inner_macros,
874 self.collapse_debuginfo,
879 /// Error type that denotes indeterminacy.
880 pub struct Indeterminate;
882 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>, bool)>;
884 pub trait ResolverExpand {
885 fn next_node_id(&mut self) -> NodeId;
886 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
888 fn resolve_dollar_crates(&mut self);
889 fn visit_ast_fragment_with_placeholders(
891 expn_id: LocalExpnId,
892 fragment: &AstFragment,
894 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
896 fn expansion_for_ast_pass(
901 parent_module_id: Option<NodeId>,
904 fn resolve_imports(&mut self);
906 fn resolve_macro_invocation(
909 eager_expansion_root: LocalExpnId,
911 ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
913 fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
915 fn check_unused_macros(&mut self);
917 // Resolver interfaces for specific built-in macros.
918 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
919 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
920 /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
923 expn_id: LocalExpnId,
925 derive_paths: &dyn Fn() -> DeriveResolutions,
926 ) -> Result<(), Indeterminate>;
927 /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
928 /// back from resolver.
929 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
930 /// Path resolution logic for `#[cfg_accessible(path)]`.
933 expn_id: LocalExpnId,
935 ) -> Result<bool, Indeterminate>;
937 /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
938 /// No caching is performed.
939 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
941 /// The order of items in the HIR is unrelated to the order of
942 /// items in the AST. However, we generate proc macro harnesses
943 /// based on the AST order, and later refer to these harnesses
944 /// from the HIR. This field keeps track of the order in which
945 /// we generated proc macros harnesses, so that we can map
946 /// HIR proc macros items back to their harness items.
947 fn declare_proc_macro(&mut self, id: NodeId);
949 /// Tools registered with `#![register_tool]` and used by tool attributes and lints.
950 fn registered_tools(&self) -> &FxHashSet<Ident>;
953 pub trait LintStoreExpand {
954 fn pre_expansion_lint(
957 registered_tools: &FxHashSet<Ident>,
965 type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
967 #[derive(Clone, Default)]
968 pub struct ModuleData {
969 /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
970 pub mod_path: Vec<Ident>,
971 /// Stack of paths to files loaded by out-of-line module items,
972 /// used to detect and report recursive module inclusions.
973 pub file_path_stack: Vec<PathBuf>,
974 /// Directory to search child module files in,
975 /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
976 pub dir_path: PathBuf,
980 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
982 mod_path: self.mod_path.clone(),
983 file_path_stack: self.file_path_stack.clone(),
990 pub struct ExpansionData {
993 pub module: Rc<ModuleData>,
994 pub dir_ownership: DirOwnership,
995 pub prior_type_ascription: Option<(Span, bool)>,
996 /// Some parent node that is close to this macro call
997 pub lint_node_id: NodeId,
998 pub is_trailing_mac: bool,
1001 /// One of these is made during expansion and incrementally updated as we go;
1002 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
1003 /// -> expn_data` of their expansion context stored into their span.
1004 pub struct ExtCtxt<'a> {
1005 pub sess: &'a Session,
1006 pub ecfg: expand::ExpansionConfig<'a>,
1007 pub reduced_recursion_limit: Option<Limit>,
1008 pub root_path: PathBuf,
1009 pub resolver: &'a mut dyn ResolverExpand,
1010 pub current_expansion: ExpansionData,
1011 /// Error recovery mode entered when expansion is stuck
1012 /// (or during eager expansion, but that's a hack).
1013 pub force_mode: bool,
1014 pub expansions: FxIndexMap<Span, Vec<String>>,
1015 /// Used for running pre-expansion lints on freshly loaded modules.
1016 pub(super) lint_store: LintStoreExpandDyn<'a>,
1017 /// Used for storing lints generated during expansion, like `NAMED_ARGUMENTS_USED_POSITIONALLY`
1018 pub buffered_early_lint: Vec<BufferedEarlyLint>,
1019 /// When we 'expand' an inert attribute, we leave it
1020 /// in the AST, but insert it here so that we know
1021 /// not to expand it again.
1022 pub(super) expanded_inert_attrs: MarkedAttrs,
1025 impl<'a> ExtCtxt<'a> {
1028 ecfg: expand::ExpansionConfig<'a>,
1029 resolver: &'a mut dyn ResolverExpand,
1030 lint_store: LintStoreExpandDyn<'a>,
1035 reduced_recursion_limit: None,
1038 root_path: PathBuf::new(),
1039 current_expansion: ExpansionData {
1040 id: LocalExpnId::ROOT,
1042 module: Default::default(),
1043 dir_ownership: DirOwnership::Owned { relative: None },
1044 prior_type_ascription: None,
1045 lint_node_id: ast::CRATE_NODE_ID,
1046 is_trailing_mac: false,
1049 expansions: FxIndexMap::default(),
1050 expanded_inert_attrs: MarkedAttrs::new(),
1051 buffered_early_lint: vec![],
1055 /// Returns a `Folder` for deeply expanding all macros in an AST node.
1056 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1057 expand::MacroExpander::new(self, false)
1060 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1061 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1062 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1063 expand::MacroExpander::new(self, true)
1065 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1066 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1068 pub fn source_map(&self) -> &'a SourceMap {
1069 self.sess.parse_sess.source_map()
1071 pub fn parse_sess(&self) -> &'a ParseSess {
1072 &self.sess.parse_sess
1074 pub fn call_site(&self) -> Span {
1075 self.current_expansion.id.expn_data().call_site
1078 /// Returns the current expansion kind's description.
1079 pub(crate) fn expansion_descr(&self) -> String {
1080 let expn_data = self.current_expansion.id.expn_data();
1081 expn_data.kind.descr()
1084 /// Equivalent of `Span::def_site` from the proc macro API,
1085 /// except that the location is taken from the span passed as an argument.
1086 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1087 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1090 /// Equivalent of `Span::call_site` from the proc macro API,
1091 /// except that the location is taken from the span passed as an argument.
1092 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1093 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1096 /// Equivalent of `Span::mixed_site` from the proc macro API,
1097 /// except that the location is taken from the span passed as an argument.
1098 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1099 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1102 /// Returns span for the macro which originally caused the current expansion to happen.
1104 /// Stops backtracing at include! boundary.
1105 pub fn expansion_cause(&self) -> Option<Span> {
1106 self.current_expansion.id.expansion_cause()
1109 #[rustc_lint_diagnostics]
1110 pub fn struct_span_err<S: Into<MultiSpan>>(
1114 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1115 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1120 err: impl IntoDiagnostic<'a>,
1121 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1122 self.sess.create_err(err)
1125 pub fn emit_err(&self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1126 self.sess.emit_err(err)
1129 /// Emit `msg` attached to `sp`, without immediately stopping
1132 /// Compilation will be stopped in the near future (at the end of
1133 /// the macro expansion phase).
1134 #[rustc_lint_diagnostics]
1135 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1136 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1138 #[rustc_lint_diagnostics]
1139 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1140 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1142 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1143 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1145 pub fn trace_macros_diag(&mut self) {
1146 for (sp, notes) in self.expansions.iter() {
1147 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1153 // Fixme: does this result in errors?
1154 self.expansions.clear();
1156 pub fn bug(&self, msg: &str) -> ! {
1157 self.sess.parse_sess.span_diagnostic.bug(msg);
1159 pub fn trace_macros(&self) -> bool {
1162 pub fn set_trace_macros(&mut self, x: bool) {
1163 self.ecfg.trace_mac = x
1165 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1166 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1167 iter::once(Ident::new(kw::DollarCrate, def_site))
1168 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1171 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1172 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1173 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1176 pub fn check_unused_macros(&mut self) {
1177 self.resolver.check_unused_macros();
1181 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1183 /// This unifies the logic used for resolving `include_X!`.
1184 pub fn resolve_path(
1185 parse_sess: &ParseSess,
1186 path: impl Into<PathBuf>,
1188 ) -> PResult<'_, PathBuf> {
1189 let path = path.into();
1191 // Relative paths are resolved relative to the file in which they are found
1192 // after macro expansion (that is, they are unhygienic).
1193 if !path.is_absolute() {
1194 let callsite = span.source_callsite();
1195 let mut result = match parse_sess.source_map().span_to_filename(callsite) {
1196 FileName::Real(name) => name
1198 .expect("attempting to resolve a file path in an external file"),
1199 FileName::DocTest(path, _) => path,
1201 return Err(ResolveRelativePath {
1203 path: parse_sess.source_map().filename_for_diagnostics(&other).to_string(),
1205 .into_diagnostic(&parse_sess.span_diagnostic));
1216 /// Extracts a string literal from the macro expanded version of `expr`,
1217 /// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
1218 /// The returned bool indicates whether an applicable suggestion has already been
1219 /// added to the diagnostic to avoid emitting multiple suggestions. `Err(None)`
1220 /// indicates that an ast error was encountered.
1221 // FIXME(Nilstrieb) Make this function setup translatable
1222 #[allow(rustc::untranslatable_diagnostic)]
1223 pub fn expr_to_spanned_string<'a>(
1224 cx: &'a mut ExtCtxt<'_>,
1227 ) -> Result<(Symbol, ast::StrStyle, Span), Option<(DiagnosticBuilder<'a, ErrorGuaranteed>, bool)>> {
1228 // Perform eager expansion on the expression.
1229 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1230 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1232 Err(match expr.kind {
1233 ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
1234 Ok(ast::LitKind::Str(s, style)) => return Ok((s, style, expr.span)),
1235 Ok(ast::LitKind::ByteStr(_)) => {
1236 let mut err = cx.struct_span_err(expr.span, err_msg);
1237 let span = expr.span.shrink_to_lo();
1238 err.span_suggestion(
1239 span.with_hi(span.lo() + BytePos(1)),
1240 "consider removing the leading `b`",
1242 Applicability::MaybeIncorrect,
1246 Ok(ast::LitKind::Err) => None,
1248 report_lit_error(&cx.sess.parse_sess, err, token_lit, expr.span);
1251 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1253 ast::ExprKind::Err => None,
1254 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1258 /// Extracts a string literal from the macro expanded version of `expr`,
1259 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1260 /// compilation on error, merely emits a non-fatal error and returns `None`.
1261 pub fn expr_to_string(
1262 cx: &mut ExtCtxt<'_>,
1265 ) -> Option<(Symbol, ast::StrStyle)> {
1266 expr_to_spanned_string(cx, expr, err_msg)
1268 err.map(|(mut err, _)| {
1273 .map(|(symbol, style, _)| (symbol, style))
1276 /// Non-fatally assert that `tts` is empty. Note that this function
1277 /// returns even when `tts` is non-empty, macros that *need* to stop
1278 /// compilation should call
1279 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1280 /// done as rarely as possible).
1281 pub fn check_zero_tts(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream, name: &str) {
1282 if !tts.is_empty() {
1283 cx.emit_err(TakesNoArguments { span, name });
1287 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1288 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1289 match p.parse_expr() {
1290 Ok(e) => return Some(e),
1295 while p.token != token::Eof {
1301 /// Interpreting `tts` as a comma-separated sequence of expressions,
1302 /// expect exactly one string literal, or emit an error and return `None`.
1303 pub fn get_single_str_from_tts(
1304 cx: &mut ExtCtxt<'_>,
1308 ) -> Option<Symbol> {
1309 let mut p = cx.new_parser_from_tts(tts);
1310 if p.token == token::Eof {
1311 cx.emit_err(OnlyOneArgument { span, name });
1314 let ret = parse_expr(&mut p)?;
1315 let _ = p.eat(&token::Comma);
1317 if p.token != token::Eof {
1318 cx.emit_err(OnlyOneArgument { span, name });
1320 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s)
1323 /// Extracts comma-separated expressions from `tts`.
1324 /// On error, emit it, and return `None`.
1325 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>, tts: TokenStream) -> Option<Vec<P<ast::Expr>>> {
1326 let mut p = cx.new_parser_from_tts(tts);
1327 let mut es = Vec::new();
1328 while p.token != token::Eof {
1329 let expr = parse_expr(&mut p)?;
1331 // Perform eager expansion on the expression.
1332 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1333 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1336 if p.eat(&token::Comma) {
1339 if p.token != token::Eof {
1340 cx.emit_err(ExpectedCommaInList { span: p.token.span });
1347 pub fn parse_macro_name_and_helper_attrs(
1348 diag: &rustc_errors::Handler,
1351 ) -> Option<(Symbol, Vec<Symbol>)> {
1352 // Once we've located the `#[proc_macro_derive]` attribute, verify
1353 // that it's of the form `#[proc_macro_derive(Foo)]` or
1354 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1355 let list = attr.meta_item_list()?;
1356 if list.len() != 1 && list.len() != 2 {
1357 diag.emit_err(AttrNoArguments { span: attr.span });
1360 let Some(trait_attr) = list[0].meta_item() else {
1361 diag.emit_err(NotAMetaItem {span: list[0].span()});
1364 let trait_ident = match trait_attr.ident() {
1365 Some(trait_ident) if trait_attr.is_word() => trait_ident,
1367 diag.emit_err(OnlyOneWord { span: trait_attr.span });
1372 if !trait_ident.name.can_be_raw() {
1373 diag.emit_err(CannotBeNameOfMacro { span: trait_attr.span, trait_ident, macro_type });
1376 let attributes_attr = list.get(1);
1377 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1378 if !attr.has_name(sym::attributes) {
1379 diag.emit_err(ArgumentNotAttributes { span: attr.span() });
1381 attr.meta_item_list()
1382 .unwrap_or_else(|| {
1383 diag.emit_err(AttributesWrongForm { span: attr.span() });
1387 .filter_map(|attr| {
1388 let Some(attr) = attr.meta_item() else {
1389 diag.emit_err(AttributeMetaItem { span: attr.span() });
1393 let ident = match attr.ident() {
1394 Some(ident) if attr.is_word() => ident,
1396 diag.emit_err(AttributeSingleWord { span: attr.span });
1400 if !ident.name.can_be_raw() {
1401 diag.emit_err(HelperAttributeNameInvalid { span: attr.span, name: ident });
1411 Some((trait_ident.name, proc_attrs))
1414 /// This nonterminal looks like some specific enums from
1415 /// `proc-macro-hack` and `procedural-masquerade` crates.
1416 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1417 /// asserts in old versions of those crates and their wide use in the ecosystem.
1418 /// See issue #73345 for more details.
1419 /// FIXME(#73933): Remove this eventually.
1420 fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool {
1421 let name = item.ident.name;
1422 if name == sym::ProceduralMasqueradeDummyType {
1423 if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1424 if let [variant] = &*enum_def.variants {
1425 if variant.ident.name == sym::Input {
1426 let filename = sess.source_map().span_to_filename(item.ident.span);
1427 if let FileName::Real(RealFileName::LocalPath(path)) = filename {
1428 if let Some(c) = path
1430 .flat_map(|c| c.as_os_str().to_str())
1431 .find(|c| c.starts_with("rental") || c.starts_with("allsorts-rental"))
1433 let crate_matches = if c.starts_with("allsorts-rental") {
1436 let mut version = c.trim_start_matches("rental-").split('.');
1437 version.next() == Some("0")
1438 && version.next() == Some("5")
1441 .and_then(|c| c.parse::<u32>().ok())
1442 .map_or(false, |v| v < 6)
1446 sess.buffer_lint_with_diagnostic(
1447 &PROC_MACRO_BACK_COMPAT,
1450 "using an old version of `rental`",
1451 BuiltinLintDiagnostics::ProcMacroBackCompat(
1452 "older versions of the `rental` crate will stop compiling in future versions of Rust; \
1453 please update to `rental` v0.5.6, or switch to one of the `rental` alternatives".to_string()
1467 pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &ParseSess) -> bool {
1468 let item = match ann {
1469 Annotatable::Item(item) => item,
1470 Annotatable::Stmt(stmt) => match &stmt.kind {
1471 ast::StmtKind::Item(item) => item,
1476 pretty_printing_compatibility_hack(item, sess)
1479 pub(crate) fn nt_pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1480 let item = match nt {
1481 Nonterminal::NtItem(item) => item,
1482 Nonterminal::NtStmt(stmt) => match &stmt.kind {
1483 ast::StmtKind::Item(item) => item,
1488 pretty_printing_compatibility_hack(item, sess)