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};
13 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, PResult};
14 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
15 use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics};
16 use rustc_parse::{self, parser, MACRO_ARGUMENTS};
17 use rustc_session::{parse::ParseSess, Limit, Session, SessionDiagnostic};
18 use rustc_span::def_id::{CrateNum, DefId, LocalDefId};
19 use rustc_span::edition::Edition;
20 use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId};
21 use rustc_span::source_map::SourceMap;
22 use rustc_span::symbol::{kw, sym, Ident, Symbol};
23 use rustc_span::{FileName, Span, DUMMY_SP};
24 use smallvec::{smallvec, SmallVec};
26 use std::default::Default;
28 use std::path::PathBuf;
31 pub(crate) use rustc_span::hygiene::MacroKind;
33 // When adding new variants, make sure to
34 // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
35 // to use `assign_id!`
36 #[derive(Debug, Clone)]
37 pub enum Annotatable {
39 TraitItem(P<ast::AssocItem>),
40 ImplItem(P<ast::AssocItem>),
41 ForeignItem(P<ast::ForeignItem>),
45 ExprField(ast::ExprField),
46 PatField(ast::PatField),
47 GenericParam(ast::GenericParam),
49 FieldDef(ast::FieldDef),
50 Variant(ast::Variant),
55 pub fn span(&self) -> Span {
57 Annotatable::Item(ref item) => item.span,
58 Annotatable::TraitItem(ref trait_item) => trait_item.span,
59 Annotatable::ImplItem(ref impl_item) => impl_item.span,
60 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
61 Annotatable::Stmt(ref stmt) => stmt.span,
62 Annotatable::Expr(ref expr) => expr.span,
63 Annotatable::Arm(ref arm) => arm.span,
64 Annotatable::ExprField(ref field) => field.span,
65 Annotatable::PatField(ref fp) => fp.pat.span,
66 Annotatable::GenericParam(ref gp) => gp.ident.span,
67 Annotatable::Param(ref p) => p.span,
68 Annotatable::FieldDef(ref sf) => sf.span,
69 Annotatable::Variant(ref v) => v.span,
70 Annotatable::Crate(ref c) => c.spans.inner_span,
74 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
76 Annotatable::Item(item) => item.visit_attrs(f),
77 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
78 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
79 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
80 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
81 Annotatable::Expr(expr) => expr.visit_attrs(f),
82 Annotatable::Arm(arm) => arm.visit_attrs(f),
83 Annotatable::ExprField(field) => field.visit_attrs(f),
84 Annotatable::PatField(fp) => fp.visit_attrs(f),
85 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
86 Annotatable::Param(p) => p.visit_attrs(f),
87 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
88 Annotatable::Variant(v) => v.visit_attrs(f),
89 Annotatable::Crate(c) => c.visit_attrs(f),
93 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
95 Annotatable::Item(item) => visitor.visit_item(item),
96 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
97 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
98 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
99 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
100 Annotatable::Expr(expr) => visitor.visit_expr(expr),
101 Annotatable::Arm(arm) => visitor.visit_arm(arm),
102 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
103 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
104 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
105 Annotatable::Param(p) => visitor.visit_param(p),
106 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
107 Annotatable::Variant(v) => visitor.visit_variant(v),
108 Annotatable::Crate(c) => visitor.visit_crate(c),
112 pub fn to_tokens(&self) -> TokenStream {
114 Annotatable::Item(node) => TokenStream::from_ast(node),
115 Annotatable::TraitItem(node) | Annotatable::ImplItem(node) => {
116 TokenStream::from_ast(node)
118 Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
119 Annotatable::Stmt(node) => {
120 assert!(!matches!(node.kind, ast::StmtKind::Empty));
121 TokenStream::from_ast(node)
123 Annotatable::Expr(node) => TokenStream::from_ast(node),
125 | Annotatable::ExprField(..)
126 | Annotatable::PatField(..)
127 | Annotatable::GenericParam(..)
128 | Annotatable::Param(..)
129 | Annotatable::FieldDef(..)
130 | Annotatable::Variant(..)
131 | Annotatable::Crate(..) => panic!("unexpected annotatable"),
135 pub fn expect_item(self) -> P<ast::Item> {
137 Annotatable::Item(i) => i,
138 _ => panic!("expected Item"),
142 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
144 Annotatable::TraitItem(i) => i,
145 _ => panic!("expected Item"),
149 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
151 Annotatable::ImplItem(i) => i,
152 _ => panic!("expected Item"),
156 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
158 Annotatable::ForeignItem(i) => i,
159 _ => panic!("expected foreign item"),
163 pub fn expect_stmt(self) -> ast::Stmt {
165 Annotatable::Stmt(stmt) => stmt.into_inner(),
166 _ => panic!("expected statement"),
170 pub fn expect_expr(self) -> P<ast::Expr> {
172 Annotatable::Expr(expr) => expr,
173 _ => panic!("expected expression"),
177 pub fn expect_arm(self) -> ast::Arm {
179 Annotatable::Arm(arm) => arm,
180 _ => panic!("expected match arm"),
184 pub fn expect_expr_field(self) -> ast::ExprField {
186 Annotatable::ExprField(field) => field,
187 _ => panic!("expected field"),
191 pub fn expect_pat_field(self) -> ast::PatField {
193 Annotatable::PatField(fp) => fp,
194 _ => panic!("expected field pattern"),
198 pub fn expect_generic_param(self) -> ast::GenericParam {
200 Annotatable::GenericParam(gp) => gp,
201 _ => panic!("expected generic parameter"),
205 pub fn expect_param(self) -> ast::Param {
207 Annotatable::Param(param) => param,
208 _ => panic!("expected parameter"),
212 pub fn expect_field_def(self) -> ast::FieldDef {
214 Annotatable::FieldDef(sf) => sf,
215 _ => panic!("expected struct field"),
219 pub fn expect_variant(self) -> ast::Variant {
221 Annotatable::Variant(v) => v,
222 _ => panic!("expected variant"),
226 pub fn expect_crate(self) -> ast::Crate {
228 Annotatable::Crate(krate) => krate,
229 _ => panic!("expected krate"),
234 /// Result of an expansion that may need to be retried.
235 /// Consider using this for non-`MultiItemModifier` expanders as well.
236 pub enum ExpandResult<T, U> {
237 /// Expansion produced a result (possibly dummy).
239 /// Expansion could not produce a result and needs to be retried.
243 // `meta_item` is the attribute, and `item` is the item being modified.
244 pub trait MultiItemModifier {
247 ecx: &mut ExtCtxt<'_>,
249 meta_item: &ast::MetaItem,
251 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
254 impl<F> MultiItemModifier for F
256 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
260 ecx: &mut ExtCtxt<'_>,
262 meta_item: &ast::MetaItem,
264 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
265 ExpandResult::Ready(self(ecx, span, meta_item, item))
269 pub trait BangProcMacro {
272 ecx: &'cx mut ExtCtxt<'_>,
275 ) -> Result<TokenStream, ErrorGuaranteed>;
278 impl<F> BangProcMacro for F
280 F: Fn(TokenStream) -> TokenStream,
284 _ecx: &'cx mut ExtCtxt<'_>,
287 ) -> Result<TokenStream, ErrorGuaranteed> {
288 // FIXME setup implicit context in TLS before calling self.
293 pub trait AttrProcMacro {
296 ecx: &'cx mut ExtCtxt<'_>,
298 annotation: TokenStream,
299 annotated: TokenStream,
300 ) -> Result<TokenStream, ErrorGuaranteed>;
303 impl<F> AttrProcMacro for F
305 F: Fn(TokenStream, TokenStream) -> TokenStream,
309 _ecx: &'cx mut ExtCtxt<'_>,
311 annotation: TokenStream,
312 annotated: TokenStream,
313 ) -> Result<TokenStream, ErrorGuaranteed> {
314 // FIXME setup implicit context in TLS before calling self.
315 Ok(self(annotation, annotated))
319 /// Represents a thing that maps token trees to Macro Results
320 pub trait TTMacroExpander {
323 ecx: &'cx mut ExtCtxt<'_>,
326 ) -> Box<dyn MacResult + 'cx>;
329 pub type MacroExpanderFn =
330 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
332 impl<F> TTMacroExpander for F
334 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
338 ecx: &'cx mut ExtCtxt<'_>,
341 ) -> Box<dyn MacResult + 'cx> {
342 self(ecx, span, input)
346 // Use a macro because forwarding to a simple function has type system issues
347 macro_rules! make_stmts_default {
349 $me.make_expr().map(|e| {
350 smallvec![ast::Stmt {
351 id: ast::DUMMY_NODE_ID,
353 kind: ast::StmtKind::Expr(e),
359 /// The result of a macro expansion. The return values of the various
360 /// methods are spliced into the AST at the callsite of the macro.
361 pub trait MacResult {
362 /// Creates an expression.
363 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
367 /// Creates zero or more items.
368 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
372 /// Creates zero or more impl items.
373 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
377 /// Creates zero or more trait items.
378 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
382 /// Creates zero or more items in an `extern {}` block
383 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
387 /// Creates a pattern.
388 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
392 /// Creates zero or more statements.
394 /// By default this attempts to create an expression statement,
395 /// returning None if that fails.
396 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
397 make_stmts_default!(self)
400 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
404 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
408 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
412 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
416 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
420 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
424 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
428 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
432 fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
433 // Fn-like macros cannot produce a crate.
438 macro_rules! make_MacEager {
439 ( $( $fld:ident: $t:ty, )* ) => {
440 /// `MacResult` implementation for the common case where you've already
441 /// built each form of AST that you might return.
443 pub struct MacEager {
445 pub $fld: Option<$t>,
451 pub fn $fld(v: $t) -> Box<dyn MacResult> {
465 items: SmallVec<[P<ast::Item>; 1]>,
466 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
467 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
468 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
469 stmts: SmallVec<[ast::Stmt; 1]>,
473 impl MacResult for MacEager {
474 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
478 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
482 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
486 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
490 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
494 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
495 match self.stmts.as_ref().map_or(0, |s| s.len()) {
496 0 => make_stmts_default!(self),
501 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
502 if let Some(p) = self.pat {
505 if let Some(e) = self.expr {
506 if let ast::ExprKind::Lit(_) = e.kind {
507 return Some(P(ast::Pat {
508 id: ast::DUMMY_NODE_ID,
510 kind: PatKind::Lit(e),
518 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
523 /// Fill-in macro expansion result, to allow compilation to continue
524 /// after hitting errors.
525 #[derive(Copy, Clone)]
526 pub struct DummyResult {
532 /// Creates a default MacResult that can be anything.
534 /// Use this as a return value after hitting any errors and
535 /// calling `span_err`.
536 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
537 Box::new(DummyResult { is_error: true, span })
540 /// Same as `any`, but must be a valid fragment, not error.
541 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
542 Box::new(DummyResult { is_error: false, span })
545 /// A plain dummy expression.
546 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
548 id: ast::DUMMY_NODE_ID,
549 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
551 attrs: ast::AttrVec::new(),
556 /// A plain dummy pattern.
557 pub fn raw_pat(sp: Span) -> ast::Pat {
558 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
561 /// A plain dummy type.
562 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
564 id: ast::DUMMY_NODE_ID,
565 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
572 impl MacResult for DummyResult {
573 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
574 Some(DummyResult::raw_expr(self.span, self.is_error))
577 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
578 Some(P(DummyResult::raw_pat(self.span)))
581 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
582 Some(SmallVec::new())
585 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
586 Some(SmallVec::new())
589 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
590 Some(SmallVec::new())
593 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
594 Some(SmallVec::new())
597 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
598 Some(smallvec![ast::Stmt {
599 id: ast::DUMMY_NODE_ID,
600 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
605 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
606 Some(DummyResult::raw_ty(self.span, self.is_error))
609 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
610 Some(SmallVec::new())
613 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
614 Some(SmallVec::new())
617 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
618 Some(SmallVec::new())
621 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
622 Some(SmallVec::new())
625 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
626 Some(SmallVec::new())
629 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
630 Some(SmallVec::new())
633 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
634 Some(SmallVec::new())
638 /// A syntax extension kind.
639 pub enum SyntaxExtensionKind {
640 /// A token-based function-like macro.
642 /// An expander with signature TokenStream -> TokenStream.
643 Box<dyn BangProcMacro + sync::Sync + sync::Send>,
646 /// An AST-based function-like macro.
648 /// An expander with signature TokenStream -> AST.
649 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
652 /// A token-based attribute macro.
654 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
655 /// The first TokenSteam is the attribute itself, the second is the annotated item.
656 /// The produced TokenSteam replaces the input TokenSteam.
657 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
660 /// An AST-based attribute macro.
662 /// An expander with signature (AST, AST) -> AST.
663 /// The first AST fragment is the attribute itself, the second is the annotated item.
664 /// The produced AST fragment replaces the input AST fragment.
665 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
668 /// A trivial attribute "macro" that does nothing,
669 /// only keeps the attribute and marks it as inert,
670 /// thus making it ineligible for further expansion.
673 /// A token-based derive macro.
675 /// An expander with signature TokenStream -> TokenStream (not yet).
676 /// The produced TokenSteam is appended to the input TokenSteam.
677 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
680 /// An AST-based derive macro.
682 /// An expander with signature AST -> AST.
683 /// The produced AST fragment is appended to the input AST fragment.
684 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
688 /// A struct representing a macro definition in "lowered" form ready for expansion.
689 pub struct SyntaxExtension {
690 /// A syntax extension kind.
691 pub kind: SyntaxExtensionKind,
692 /// Span of the macro definition.
694 /// List of unstable features that are treated as stable inside this macro.
695 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
696 /// The macro's stability info.
697 pub stability: Option<Stability>,
698 /// The macro's deprecation info.
699 pub deprecation: Option<Deprecation>,
700 /// Names of helper attributes registered by this macro.
701 pub helper_attrs: Vec<Symbol>,
702 /// Edition of the crate in which this macro is defined.
703 pub edition: Edition,
704 /// Built-in macros have a couple of special properties like availability
705 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
706 pub builtin_name: Option<Symbol>,
707 /// Suppresses the `unsafe_code` lint for code produced by this macro.
708 pub allow_internal_unsafe: bool,
709 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
710 pub local_inner_macros: bool,
711 /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
712 /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
713 pub collapse_debuginfo: bool,
716 impl SyntaxExtension {
717 /// Returns which kind of macro calls this syntax extension.
718 pub fn macro_kind(&self) -> MacroKind {
720 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
721 SyntaxExtensionKind::Attr(..)
722 | SyntaxExtensionKind::LegacyAttr(..)
723 | SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
724 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
730 /// Constructs a syntax extension with default properties.
731 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
734 allow_internal_unstable: None,
737 helper_attrs: Vec::new(),
741 allow_internal_unsafe: false,
742 local_inner_macros: false,
743 collapse_debuginfo: false,
747 /// Constructs a syntax extension with the given properties
748 /// and other properties converted from attributes.
751 kind: SyntaxExtensionKind,
753 helper_attrs: Vec<Symbol>,
756 attrs: &[ast::Attribute],
757 ) -> SyntaxExtension {
758 let allow_internal_unstable =
759 attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
761 let allow_internal_unsafe = sess.contains_name(attrs, sym::allow_internal_unsafe);
762 let local_inner_macros = sess
763 .find_by_name(attrs, sym::macro_export)
764 .and_then(|macro_export| macro_export.meta_item_list())
765 .map_or(false, |l| attr::list_contains_name(&l, sym::local_inner_macros));
766 let collapse_debuginfo = sess.contains_name(attrs, sym::collapse_debuginfo);
767 tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
769 let (builtin_name, helper_attrs) = sess
770 .find_by_name(attrs, sym::rustc_builtin_macro)
772 // Override `helper_attrs` passed above if it's a built-in macro,
773 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
774 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
775 || (Some(name), Vec::new()),
776 |(name, helper_attrs)| (Some(name), helper_attrs),
779 .unwrap_or_else(|| (None, helper_attrs));
780 let (stability, const_stability, body_stability) = attr::find_stability(&sess, attrs, span);
781 if let Some((_, sp)) = const_stability {
784 .struct_span_err(sp, "macros cannot have const stability attributes")
785 .span_label(sp, "invalid const stability attribute")
787 sess.source_map().guess_head_span(span),
788 "const stability attribute affects this macro",
792 if let Some((_, sp)) = body_stability {
795 .struct_span_err(sp, "macros cannot have body stability attributes")
796 .span_label(sp, "invalid body stability attribute")
798 sess.source_map().guess_head_span(span),
799 "body stability attribute affects this macro",
807 allow_internal_unstable: (!allow_internal_unstable.is_empty())
808 .then(|| allow_internal_unstable.into()),
809 stability: stability.map(|(s, _)| s),
810 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
814 allow_internal_unsafe,
820 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
822 _: &'cx mut ExtCtxt<'_>,
825 ) -> Box<dyn MacResult + 'cx> {
826 DummyResult::any(span)
828 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
831 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
837 ) -> Vec<Annotatable> {
840 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
843 pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
844 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
852 macro_def_id: Option<DefId>,
853 parent_module: Option<DefId>,
856 ExpnKind::Macro(self.macro_kind(), descr),
860 self.allow_internal_unstable.clone(),
864 self.allow_internal_unsafe,
865 self.local_inner_macros,
866 self.collapse_debuginfo,
871 /// Error type that denotes indeterminacy.
872 pub struct Indeterminate;
874 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>)>;
876 pub trait ResolverExpand {
877 fn next_node_id(&mut self) -> NodeId;
878 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
880 fn resolve_dollar_crates(&mut self);
881 fn visit_ast_fragment_with_placeholders(
883 expn_id: LocalExpnId,
884 fragment: &AstFragment,
886 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
888 fn expansion_for_ast_pass(
893 parent_module_id: Option<NodeId>,
896 fn resolve_imports(&mut self);
898 fn resolve_macro_invocation(
901 eager_expansion_root: LocalExpnId,
903 ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
905 fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
907 fn check_unused_macros(&mut self);
909 // Resolver interfaces for specific built-in macros.
910 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
911 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
912 /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
915 expn_id: LocalExpnId,
917 derive_paths: &dyn Fn() -> DeriveResolutions,
918 ) -> Result<(), Indeterminate>;
919 /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
920 /// back from resolver.
921 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
922 /// Path resolution logic for `#[cfg_accessible(path)]`.
925 expn_id: LocalExpnId,
927 ) -> Result<bool, Indeterminate>;
929 /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
930 /// No caching is performed.
931 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
933 /// The order of items in the HIR is unrelated to the order of
934 /// items in the AST. However, we generate proc macro harnesses
935 /// based on the AST order, and later refer to these harnesses
936 /// from the HIR. This field keeps track of the order in which
937 /// we generated proc macros harnesses, so that we can map
938 /// HIR proc macros items back to their harness items.
939 fn declare_proc_macro(&mut self, id: NodeId);
941 /// Tools registered with `#![register_tool]` and used by tool attributes and lints.
942 fn registered_tools(&self) -> &FxHashSet<Ident>;
945 pub trait LintStoreExpand {
946 fn pre_expansion_lint(
949 registered_tools: &FxHashSet<Ident>,
957 type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
959 #[derive(Clone, Default)]
960 pub struct ModuleData {
961 /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
962 pub mod_path: Vec<Ident>,
963 /// Stack of paths to files loaded by out-of-line module items,
964 /// used to detect and report recursive module inclusions.
965 pub file_path_stack: Vec<PathBuf>,
966 /// Directory to search child module files in,
967 /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
968 pub dir_path: PathBuf,
972 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
974 mod_path: self.mod_path.clone(),
975 file_path_stack: self.file_path_stack.clone(),
982 pub struct ExpansionData {
985 pub module: Rc<ModuleData>,
986 pub dir_ownership: DirOwnership,
987 pub prior_type_ascription: Option<(Span, bool)>,
988 /// Some parent node that is close to this macro call
989 pub lint_node_id: NodeId,
990 pub is_trailing_mac: bool,
993 /// One of these is made during expansion and incrementally updated as we go;
994 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
995 /// -> expn_data` of their expansion context stored into their span.
996 pub struct ExtCtxt<'a> {
997 pub sess: &'a Session,
998 pub ecfg: expand::ExpansionConfig<'a>,
999 pub reduced_recursion_limit: Option<Limit>,
1000 pub root_path: PathBuf,
1001 pub resolver: &'a mut dyn ResolverExpand,
1002 pub current_expansion: ExpansionData,
1003 /// Error recovery mode entered when expansion is stuck
1004 /// (or during eager expansion, but that's a hack).
1005 pub force_mode: bool,
1006 pub expansions: FxIndexMap<Span, Vec<String>>,
1007 /// Used for running pre-expansion lints on freshly loaded modules.
1008 pub(super) lint_store: LintStoreExpandDyn<'a>,
1009 /// Used for storing lints generated during expansion, like `NAMED_ARGUMENTS_USED_POSITIONALLY`
1010 pub buffered_early_lint: Vec<BufferedEarlyLint>,
1011 /// When we 'expand' an inert attribute, we leave it
1012 /// in the AST, but insert it here so that we know
1013 /// not to expand it again.
1014 pub(super) expanded_inert_attrs: MarkedAttrs,
1017 impl<'a> ExtCtxt<'a> {
1020 ecfg: expand::ExpansionConfig<'a>,
1021 resolver: &'a mut dyn ResolverExpand,
1022 lint_store: LintStoreExpandDyn<'a>,
1027 reduced_recursion_limit: None,
1030 root_path: PathBuf::new(),
1031 current_expansion: ExpansionData {
1032 id: LocalExpnId::ROOT,
1034 module: Default::default(),
1035 dir_ownership: DirOwnership::Owned { relative: None },
1036 prior_type_ascription: None,
1037 lint_node_id: ast::CRATE_NODE_ID,
1038 is_trailing_mac: false,
1041 expansions: FxIndexMap::default(),
1042 expanded_inert_attrs: MarkedAttrs::new(),
1043 buffered_early_lint: vec![],
1047 /// Returns a `Folder` for deeply expanding all macros in an AST node.
1048 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1049 expand::MacroExpander::new(self, false)
1052 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1053 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1054 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1055 expand::MacroExpander::new(self, true)
1057 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1058 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1060 pub fn source_map(&self) -> &'a SourceMap {
1061 self.sess.parse_sess.source_map()
1063 pub fn parse_sess(&self) -> &'a ParseSess {
1064 &self.sess.parse_sess
1066 pub fn call_site(&self) -> Span {
1067 self.current_expansion.id.expn_data().call_site
1070 /// Returns the current expansion kind's description.
1071 pub(crate) fn expansion_descr(&self) -> String {
1072 let expn_data = self.current_expansion.id.expn_data();
1073 expn_data.kind.descr()
1076 /// Equivalent of `Span::def_site` from the proc macro API,
1077 /// except that the location is taken from the span passed as an argument.
1078 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1079 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1082 /// Equivalent of `Span::call_site` from the proc macro API,
1083 /// except that the location is taken from the span passed as an argument.
1084 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1085 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1088 /// Equivalent of `Span::mixed_site` from the proc macro API,
1089 /// except that the location is taken from the span passed as an argument.
1090 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1091 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1094 /// Returns span for the macro which originally caused the current expansion to happen.
1096 /// Stops backtracing at include! boundary.
1097 pub fn expansion_cause(&self) -> Option<Span> {
1098 self.current_expansion.id.expansion_cause()
1101 #[rustc_lint_diagnostics]
1102 pub fn struct_span_err<S: Into<MultiSpan>>(
1106 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1107 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1112 err: impl SessionDiagnostic<'a>,
1113 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1114 self.sess.create_err(err)
1117 pub fn emit_err(&self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed {
1118 self.sess.emit_err(err)
1121 /// Emit `msg` attached to `sp`, without immediately stopping
1124 /// Compilation will be stopped in the near future (at the end of
1125 /// the macro expansion phase).
1126 #[rustc_lint_diagnostics]
1127 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1128 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1130 #[rustc_lint_diagnostics]
1131 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1132 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1134 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1135 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1137 pub fn trace_macros_diag(&mut self) {
1138 for (sp, notes) in self.expansions.iter() {
1139 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1145 // Fixme: does this result in errors?
1146 self.expansions.clear();
1148 pub fn bug(&self, msg: &str) -> ! {
1149 self.sess.parse_sess.span_diagnostic.bug(msg);
1151 pub fn trace_macros(&self) -> bool {
1154 pub fn set_trace_macros(&mut self, x: bool) {
1155 self.ecfg.trace_mac = x
1157 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1158 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1159 iter::once(Ident::new(kw::DollarCrate, def_site))
1160 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1163 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1164 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1165 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1168 pub fn check_unused_macros(&mut self) {
1169 self.resolver.check_unused_macros();
1173 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1175 /// This unifies the logic used for resolving `include_X!`.
1176 pub fn resolve_path(
1177 parse_sess: &ParseSess,
1178 path: impl Into<PathBuf>,
1180 ) -> PResult<'_, PathBuf> {
1181 let path = path.into();
1183 // Relative paths are resolved relative to the file in which they are found
1184 // after macro expansion (that is, they are unhygienic).
1185 if !path.is_absolute() {
1186 let callsite = span.source_callsite();
1187 let mut result = match parse_sess.source_map().span_to_filename(callsite) {
1188 FileName::Real(name) => name
1190 .expect("attempting to resolve a file path in an external file"),
1191 FileName::DocTest(path, _) => path,
1193 return Err(parse_sess.span_diagnostic.struct_span_err(
1196 "cannot resolve relative path in non-file source `{}`",
1197 parse_sess.source_map().filename_for_diagnostics(&other)
1210 /// Extracts a string literal from the macro expanded version of `expr`,
1211 /// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
1212 /// The returned bool indicates whether an applicable suggestion has already been
1213 /// added to the diagnostic to avoid emitting multiple suggestions. `Err(None)`
1214 /// indicates that an ast error was encountered.
1215 pub fn expr_to_spanned_string<'a>(
1216 cx: &'a mut ExtCtxt<'_>,
1219 ) -> Result<(Symbol, ast::StrStyle, Span), Option<(DiagnosticBuilder<'a, ErrorGuaranteed>, bool)>> {
1220 // Perform eager expansion on the expression.
1221 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1222 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1224 Err(match expr.kind {
1225 ast::ExprKind::Lit(ref l) => match l.kind {
1226 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1227 ast::LitKind::ByteStr(_) => {
1228 let mut err = cx.struct_span_err(l.span, err_msg);
1229 err.span_suggestion(
1230 expr.span.shrink_to_lo(),
1231 "consider removing the leading `b`",
1233 Applicability::MaybeIncorrect,
1237 ast::LitKind::Err => None,
1238 _ => Some((cx.struct_span_err(l.span, err_msg), false)),
1240 ast::ExprKind::Err => None,
1241 _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1245 /// Extracts a string literal from the macro expanded version of `expr`,
1246 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1247 /// compilation on error, merely emits a non-fatal error and returns `None`.
1248 pub fn expr_to_string(
1249 cx: &mut ExtCtxt<'_>,
1252 ) -> Option<(Symbol, ast::StrStyle)> {
1253 expr_to_spanned_string(cx, expr, err_msg)
1255 err.map(|(mut err, _)| {
1260 .map(|(symbol, style, _)| (symbol, style))
1263 /// Non-fatally assert that `tts` is empty. Note that this function
1264 /// returns even when `tts` is non-empty, macros that *need* to stop
1265 /// compilation should call
1266 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1267 /// done as rarely as possible).
1268 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1269 if !tts.is_empty() {
1270 cx.span_err(sp, &format!("{} takes no arguments", name));
1274 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1275 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1276 match p.parse_expr() {
1277 Ok(e) => return Some(e),
1282 while p.token != token::Eof {
1288 /// Interpreting `tts` as a comma-separated sequence of expressions,
1289 /// expect exactly one string literal, or emit an error and return `None`.
1290 pub fn get_single_str_from_tts(
1291 cx: &mut ExtCtxt<'_>,
1295 ) -> Option<Symbol> {
1296 let mut p = cx.new_parser_from_tts(tts);
1297 if p.token == token::Eof {
1298 cx.span_err(sp, &format!("{} takes 1 argument", name));
1301 let ret = parse_expr(&mut p)?;
1302 let _ = p.eat(&token::Comma);
1304 if p.token != token::Eof {
1305 cx.span_err(sp, &format!("{} takes 1 argument", name));
1307 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s)
1310 /// Extracts comma-separated expressions from `tts`.
1311 /// On error, emit it, and return `None`.
1312 pub fn get_exprs_from_tts(
1313 cx: &mut ExtCtxt<'_>,
1316 ) -> Option<Vec<P<ast::Expr>>> {
1317 let mut p = cx.new_parser_from_tts(tts);
1318 let mut es = Vec::new();
1319 while p.token != token::Eof {
1320 let expr = parse_expr(&mut p)?;
1322 // Perform eager expansion on the expression.
1323 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1324 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1327 if p.eat(&token::Comma) {
1330 if p.token != token::Eof {
1331 cx.span_err(sp, "expected token: `,`");
1338 pub fn parse_macro_name_and_helper_attrs(
1339 diag: &rustc_errors::Handler,
1342 ) -> Option<(Symbol, Vec<Symbol>)> {
1343 // Once we've located the `#[proc_macro_derive]` attribute, verify
1344 // that it's of the form `#[proc_macro_derive(Foo)]` or
1345 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1346 let list = attr.meta_item_list()?;
1347 if list.len() != 1 && list.len() != 2 {
1348 diag.span_err(attr.span, "attribute must have either one or two arguments");
1351 let Some(trait_attr) = list[0].meta_item() else {
1352 diag.span_err(list[0].span(), "not a meta item");
1355 let trait_ident = match trait_attr.ident() {
1356 Some(trait_ident) if trait_attr.is_word() => trait_ident,
1358 diag.span_err(trait_attr.span, "must only be one word");
1363 if !trait_ident.name.can_be_raw() {
1366 &format!("`{}` cannot be a name of {} macro", trait_ident, descr),
1370 let attributes_attr = list.get(1);
1371 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1372 if !attr.has_name(sym::attributes) {
1373 diag.span_err(attr.span(), "second argument must be `attributes`");
1375 attr.meta_item_list()
1376 .unwrap_or_else(|| {
1377 diag.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
1381 .filter_map(|attr| {
1382 let Some(attr) = attr.meta_item() else {
1383 diag.span_err(attr.span(), "not a meta item");
1387 let ident = match attr.ident() {
1388 Some(ident) if attr.is_word() => ident,
1390 diag.span_err(attr.span, "must only be one word");
1394 if !ident.name.can_be_raw() {
1397 &format!("`{}` cannot be a name of derive helper attribute", ident),
1408 Some((trait_ident.name, proc_attrs))
1411 /// This nonterminal looks like some specific enums from
1412 /// `proc-macro-hack` and `procedural-masquerade` crates.
1413 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1414 /// asserts in old versions of those crates and their wide use in the ecosystem.
1415 /// See issue #73345 for more details.
1416 /// FIXME(#73933): Remove this eventually.
1417 fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool {
1418 let name = item.ident.name;
1419 if name == sym::ProceduralMasqueradeDummyType {
1420 if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1421 if let [variant] = &*enum_def.variants {
1422 if variant.ident.name == sym::Input {
1423 sess.buffer_lint_with_diagnostic(
1424 &PROC_MACRO_BACK_COMPAT,
1427 "using `procedural-masquerade` crate",
1428 BuiltinLintDiagnostics::ProcMacroBackCompat(
1429 "The `procedural-masquerade` crate has been unnecessary since Rust 1.30.0. \
1430 Versions of this crate below 0.1.7 will eventually stop compiling.".to_string())
1440 pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &ParseSess) -> bool {
1441 let item = match ann {
1442 Annotatable::Item(item) => item,
1443 Annotatable::Stmt(stmt) => match &stmt.kind {
1444 ast::StmtKind::Item(item) => item,
1449 pretty_printing_compatibility_hack(item, sess)
1452 pub(crate) fn nt_pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1453 let item = match nt {
1454 Nonterminal::NtItem(item) => item,
1455 Nonterminal::NtStmt(stmt) => match &stmt.kind {
1456 ast::StmtKind::Item(item) => item,
1461 pretty_printing_compatibility_hack(item, sess)