1 use crate::expand::{self, AstFragment, Invocation};
2 use crate::module::DirOwnership;
5 use rustc_ast::token::{self, Nonterminal};
6 use rustc_ast::tokenstream::{CanSynthesizeMissingTokens, TokenStream};
7 use rustc_ast::visit::{AssocCtxt, Visitor};
8 use rustc_ast::{self as ast, AstLike, Attribute, Item, NodeId, PatKind};
9 use rustc_attr::{self as attr, Deprecation, Stability};
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_data_structures::sync::{self, Lrc};
12 use rustc_errors::{DiagnosticBuilder, ErrorReported};
13 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
14 use rustc_lint_defs::BuiltinLintDiagnostics;
15 use rustc_parse::{self, nt_to_tokenstream, parser, MACRO_ARGUMENTS};
16 use rustc_session::{parse::ParseSess, Limit, Session};
17 use rustc_span::def_id::{CrateNum, DefId};
18 use rustc_span::edition::Edition;
19 use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId};
20 use rustc_span::source_map::SourceMap;
21 use rustc_span::symbol::{kw, sym, Ident, Symbol};
22 use rustc_span::{FileName, MultiSpan, Span, DUMMY_SP};
23 use smallvec::{smallvec, SmallVec};
25 use std::default::Default;
27 use std::path::PathBuf;
30 crate use rustc_span::hygiene::MacroKind;
32 // When adding new variants, make sure to
33 // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
34 // to use `assign_id!`
35 #[derive(Debug, Clone)]
36 pub enum Annotatable {
38 TraitItem(P<ast::AssocItem>),
39 ImplItem(P<ast::AssocItem>),
40 ForeignItem(P<ast::ForeignItem>),
44 ExprField(ast::ExprField),
45 PatField(ast::PatField),
46 GenericParam(ast::GenericParam),
48 FieldDef(ast::FieldDef),
49 Variant(ast::Variant),
53 pub fn span(&self) -> Span {
55 Annotatable::Item(ref item) => item.span,
56 Annotatable::TraitItem(ref trait_item) => trait_item.span,
57 Annotatable::ImplItem(ref impl_item) => impl_item.span,
58 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
59 Annotatable::Stmt(ref stmt) => stmt.span,
60 Annotatable::Expr(ref expr) => expr.span,
61 Annotatable::Arm(ref arm) => arm.span,
62 Annotatable::ExprField(ref field) => field.span,
63 Annotatable::PatField(ref fp) => fp.pat.span,
64 Annotatable::GenericParam(ref gp) => gp.ident.span,
65 Annotatable::Param(ref p) => p.span,
66 Annotatable::FieldDef(ref sf) => sf.span,
67 Annotatable::Variant(ref v) => v.span,
71 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
73 Annotatable::Item(item) => item.visit_attrs(f),
74 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
75 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
76 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
77 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
78 Annotatable::Expr(expr) => expr.visit_attrs(f),
79 Annotatable::Arm(arm) => arm.visit_attrs(f),
80 Annotatable::ExprField(field) => field.visit_attrs(f),
81 Annotatable::PatField(fp) => fp.visit_attrs(f),
82 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
83 Annotatable::Param(p) => p.visit_attrs(f),
84 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
85 Annotatable::Variant(v) => v.visit_attrs(f),
89 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
91 Annotatable::Item(item) => visitor.visit_item(item),
92 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
93 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
94 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
95 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
96 Annotatable::Expr(expr) => visitor.visit_expr(expr),
97 Annotatable::Arm(arm) => visitor.visit_arm(arm),
98 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
99 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
100 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
101 Annotatable::Param(p) => visitor.visit_param(p),
102 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
103 Annotatable::Variant(v) => visitor.visit_variant(v),
107 pub fn into_nonterminal(self) -> Nonterminal {
109 Annotatable::Item(item) => token::NtItem(item),
110 Annotatable::TraitItem(item) | Annotatable::ImplItem(item) => {
111 token::NtItem(P(item.and_then(ast::AssocItem::into_item)))
113 Annotatable::ForeignItem(item) => {
114 token::NtItem(P(item.and_then(ast::ForeignItem::into_item)))
116 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
117 Annotatable::Expr(expr) => token::NtExpr(expr),
119 | Annotatable::ExprField(..)
120 | Annotatable::PatField(..)
121 | Annotatable::GenericParam(..)
122 | Annotatable::Param(..)
123 | Annotatable::FieldDef(..)
124 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
128 crate fn into_tokens(self, sess: &ParseSess) -> TokenStream {
129 nt_to_tokenstream(&self.into_nonterminal(), sess, CanSynthesizeMissingTokens::No)
132 pub fn expect_item(self) -> P<ast::Item> {
134 Annotatable::Item(i) => i,
135 _ => panic!("expected Item"),
139 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
141 Annotatable::TraitItem(i) => i,
142 _ => panic!("expected Item"),
146 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
148 Annotatable::ImplItem(i) => i,
149 _ => panic!("expected Item"),
153 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
155 Annotatable::ForeignItem(i) => i,
156 _ => panic!("expected foreign item"),
160 pub fn expect_stmt(self) -> ast::Stmt {
162 Annotatable::Stmt(stmt) => stmt.into_inner(),
163 _ => panic!("expected statement"),
167 pub fn expect_expr(self) -> P<ast::Expr> {
169 Annotatable::Expr(expr) => expr,
170 _ => panic!("expected expression"),
174 pub fn expect_arm(self) -> ast::Arm {
176 Annotatable::Arm(arm) => arm,
177 _ => panic!("expected match arm"),
181 pub fn expect_expr_field(self) -> ast::ExprField {
183 Annotatable::ExprField(field) => field,
184 _ => panic!("expected field"),
188 pub fn expect_pat_field(self) -> ast::PatField {
190 Annotatable::PatField(fp) => fp,
191 _ => panic!("expected field pattern"),
195 pub fn expect_generic_param(self) -> ast::GenericParam {
197 Annotatable::GenericParam(gp) => gp,
198 _ => panic!("expected generic parameter"),
202 pub fn expect_param(self) -> ast::Param {
204 Annotatable::Param(param) => param,
205 _ => panic!("expected parameter"),
209 pub fn expect_field_def(self) -> ast::FieldDef {
211 Annotatable::FieldDef(sf) => sf,
212 _ => panic!("expected struct field"),
216 pub fn expect_variant(self) -> ast::Variant {
218 Annotatable::Variant(v) => v,
219 _ => panic!("expected variant"),
224 /// Result of an expansion that may need to be retried.
225 /// Consider using this for non-`MultiItemModifier` expanders as well.
226 pub enum ExpandResult<T, U> {
227 /// Expansion produced a result (possibly dummy).
229 /// Expansion could not produce a result and needs to be retried.
233 // `meta_item` is the attribute, and `item` is the item being modified.
234 pub trait MultiItemModifier {
237 ecx: &mut ExtCtxt<'_>,
239 meta_item: &ast::MetaItem,
241 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
244 impl<F> MultiItemModifier for F
246 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
250 ecx: &mut ExtCtxt<'_>,
252 meta_item: &ast::MetaItem,
254 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
255 ExpandResult::Ready(self(ecx, span, meta_item, item))
259 pub trait ProcMacro {
262 ecx: &'cx mut ExtCtxt<'_>,
265 ) -> Result<TokenStream, ErrorReported>;
268 impl<F> ProcMacro for F
270 F: Fn(TokenStream) -> TokenStream,
274 _ecx: &'cx mut ExtCtxt<'_>,
277 ) -> Result<TokenStream, ErrorReported> {
278 // FIXME setup implicit context in TLS before calling self.
283 pub trait AttrProcMacro {
286 ecx: &'cx mut ExtCtxt<'_>,
288 annotation: TokenStream,
289 annotated: TokenStream,
290 ) -> Result<TokenStream, ErrorReported>;
293 impl<F> AttrProcMacro for F
295 F: Fn(TokenStream, TokenStream) -> TokenStream,
299 _ecx: &'cx mut ExtCtxt<'_>,
301 annotation: TokenStream,
302 annotated: TokenStream,
303 ) -> Result<TokenStream, ErrorReported> {
304 // FIXME setup implicit context in TLS before calling self.
305 Ok(self(annotation, annotated))
309 /// Represents a thing that maps token trees to Macro Results
310 pub trait TTMacroExpander {
313 ecx: &'cx mut ExtCtxt<'_>,
316 ) -> Box<dyn MacResult + 'cx>;
319 pub type MacroExpanderFn =
320 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
322 impl<F> TTMacroExpander for F
324 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
328 ecx: &'cx mut ExtCtxt<'_>,
331 ) -> Box<dyn MacResult + 'cx> {
332 self(ecx, span, input)
336 // Use a macro because forwarding to a simple function has type system issues
337 macro_rules! make_stmts_default {
339 $me.make_expr().map(|e| {
340 smallvec![ast::Stmt {
341 id: ast::DUMMY_NODE_ID,
343 kind: ast::StmtKind::Expr(e),
349 /// The result of a macro expansion. The return values of the various
350 /// methods are spliced into the AST at the callsite of the macro.
351 pub trait MacResult {
352 /// Creates an expression.
353 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
356 /// Creates zero or more items.
357 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
361 /// Creates zero or more impl items.
362 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
366 /// Creates zero or more trait items.
367 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
371 /// Creates zero or more items in an `extern {}` block
372 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
376 /// Creates a pattern.
377 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
381 /// Creates zero or more statements.
383 /// By default this attempts to create an expression statement,
384 /// returning None if that fails.
385 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
386 make_stmts_default!(self)
389 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
393 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
397 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
401 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
405 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
409 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
413 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
417 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
422 macro_rules! make_MacEager {
423 ( $( $fld:ident: $t:ty, )* ) => {
424 /// `MacResult` implementation for the common case where you've already
425 /// built each form of AST that you might return.
427 pub struct MacEager {
429 pub $fld: Option<$t>,
435 pub fn $fld(v: $t) -> Box<dyn MacResult> {
449 items: SmallVec<[P<ast::Item>; 1]>,
450 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
451 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
452 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
453 stmts: SmallVec<[ast::Stmt; 1]>,
457 impl MacResult for MacEager {
458 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
462 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
466 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
470 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
474 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
478 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
479 match self.stmts.as_ref().map_or(0, |s| s.len()) {
480 0 => make_stmts_default!(self),
485 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
486 if let Some(p) = self.pat {
489 if let Some(e) = self.expr {
490 if let ast::ExprKind::Lit(_) = e.kind {
491 return Some(P(ast::Pat {
492 id: ast::DUMMY_NODE_ID,
494 kind: PatKind::Lit(e),
502 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
507 /// Fill-in macro expansion result, to allow compilation to continue
508 /// after hitting errors.
509 #[derive(Copy, Clone)]
510 pub struct DummyResult {
516 /// Creates a default MacResult that can be anything.
518 /// Use this as a return value after hitting any errors and
519 /// calling `span_err`.
520 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
521 Box::new(DummyResult { is_error: true, span })
524 /// Same as `any`, but must be a valid fragment, not error.
525 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
526 Box::new(DummyResult { is_error: false, span })
529 /// A plain dummy expression.
530 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
532 id: ast::DUMMY_NODE_ID,
533 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
535 attrs: ast::AttrVec::new(),
540 /// A plain dummy pattern.
541 pub fn raw_pat(sp: Span) -> ast::Pat {
542 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
545 /// A plain dummy type.
546 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
548 id: ast::DUMMY_NODE_ID,
549 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
556 impl MacResult for DummyResult {
557 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
558 Some(DummyResult::raw_expr(self.span, self.is_error))
561 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
562 Some(P(DummyResult::raw_pat(self.span)))
565 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
566 Some(SmallVec::new())
569 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
570 Some(SmallVec::new())
573 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
574 Some(SmallVec::new())
577 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
578 Some(SmallVec::new())
581 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
582 Some(smallvec![ast::Stmt {
583 id: ast::DUMMY_NODE_ID,
584 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
589 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
590 Some(DummyResult::raw_ty(self.span, self.is_error))
593 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
594 Some(SmallVec::new())
597 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
598 Some(SmallVec::new())
601 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
602 Some(SmallVec::new())
605 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
606 Some(SmallVec::new())
609 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
610 Some(SmallVec::new())
613 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
614 Some(SmallVec::new())
617 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
618 Some(SmallVec::new())
622 /// A syntax extension kind.
623 pub enum SyntaxExtensionKind {
624 /// A token-based function-like macro.
626 /// An expander with signature TokenStream -> TokenStream.
627 Box<dyn ProcMacro + sync::Sync + sync::Send>,
630 /// An AST-based function-like macro.
632 /// An expander with signature TokenStream -> AST.
633 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
636 /// A token-based attribute macro.
638 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
639 /// The first TokenSteam is the attribute itself, the second is the annotated item.
640 /// The produced TokenSteam replaces the input TokenSteam.
641 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
644 /// An AST-based attribute macro.
646 /// An expander with signature (AST, AST) -> AST.
647 /// The first AST fragment is the attribute itself, the second is the annotated item.
648 /// The produced AST fragment replaces the input AST fragment.
649 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
652 /// A trivial attribute "macro" that does nothing,
653 /// only keeps the attribute and marks it as inert,
654 /// thus making it ineligible for further expansion.
656 /// Suppresses the `unused_attributes` lint for this attribute.
660 /// A token-based derive macro.
662 /// An expander with signature TokenStream -> TokenStream (not yet).
663 /// The produced TokenSteam is appended to the input TokenSteam.
664 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
667 /// An AST-based derive macro.
669 /// An expander with signature AST -> AST.
670 /// The produced AST fragment is appended to the input AST fragment.
671 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
675 /// A struct representing a macro definition in "lowered" form ready for expansion.
676 pub struct SyntaxExtension {
677 /// A syntax extension kind.
678 pub kind: SyntaxExtensionKind,
679 /// Span of the macro definition.
681 /// List of unstable features that are treated as stable inside this macro.
682 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
683 /// Suppresses the `unsafe_code` lint for code produced by this macro.
684 pub allow_internal_unsafe: bool,
685 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
686 pub local_inner_macros: bool,
687 /// The macro's stability info.
688 pub stability: Option<Stability>,
689 /// The macro's deprecation info.
690 pub deprecation: Option<Deprecation>,
691 /// Names of helper attributes registered by this macro.
692 pub helper_attrs: Vec<Symbol>,
693 /// Edition of the crate in which this macro is defined.
694 pub edition: Edition,
695 /// Built-in macros have a couple of special properties like availability
696 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
697 pub builtin_name: Option<Symbol>,
700 impl SyntaxExtension {
701 /// Returns which kind of macro calls this syntax extension.
702 pub fn macro_kind(&self) -> MacroKind {
704 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
705 SyntaxExtensionKind::Attr(..)
706 | SyntaxExtensionKind::LegacyAttr(..)
707 | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
708 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
714 /// Constructs a syntax extension with default properties.
715 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
718 allow_internal_unstable: None,
719 allow_internal_unsafe: false,
720 local_inner_macros: false,
723 helper_attrs: Vec::new(),
730 /// Constructs a syntax extension with the given properties
731 /// and other properties converted from attributes.
734 kind: SyntaxExtensionKind,
736 helper_attrs: Vec<Symbol>,
739 attrs: &[ast::Attribute],
740 ) -> SyntaxExtension {
741 let allow_internal_unstable =
742 attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
744 let mut local_inner_macros = false;
745 if let Some(macro_export) = sess.find_by_name(attrs, sym::macro_export) {
746 if let Some(l) = macro_export.meta_item_list() {
747 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
751 let (builtin_name, helper_attrs) = sess
752 .find_by_name(attrs, sym::rustc_builtin_macro)
754 // Override `helper_attrs` passed above if it's a built-in macro,
755 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
756 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
757 || (Some(name), Vec::new()),
758 |(name, helper_attrs)| (Some(name), helper_attrs),
761 .unwrap_or_else(|| (None, helper_attrs));
762 let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
763 if let Some((_, sp)) = const_stability {
766 .struct_span_err(sp, "macros cannot have const stability attributes")
767 .span_label(sp, "invalid const stability attribute")
769 sess.source_map().guess_head_span(span),
770 "const stability attribute affects this macro",
778 allow_internal_unstable: (!allow_internal_unstable.is_empty())
779 .then(|| allow_internal_unstable.into()),
780 allow_internal_unsafe: sess.contains_name(attrs, sym::allow_internal_unsafe),
782 stability: stability.map(|(s, _)| s),
783 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
790 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
792 _: &'cx mut ExtCtxt<'_>,
795 ) -> Box<dyn MacResult + 'cx> {
796 DummyResult::any(span)
798 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
801 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
807 ) -> Vec<Annotatable> {
810 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
813 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
814 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
822 macro_def_id: Option<DefId>,
823 parent_module: Option<DefId>,
826 ExpnKind::Macro(self.macro_kind(), descr),
830 self.allow_internal_unstable.clone(),
831 self.allow_internal_unsafe,
832 self.local_inner_macros,
840 /// Error type that denotes indeterminacy.
841 pub struct Indeterminate;
843 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>)>;
845 pub trait ResolverExpand {
846 fn next_node_id(&mut self) -> NodeId;
848 fn resolve_dollar_crates(&mut self);
849 fn visit_ast_fragment_with_placeholders(
851 expn_id: LocalExpnId,
852 fragment: &AstFragment,
854 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
856 fn expansion_for_ast_pass(
861 parent_module_id: Option<NodeId>,
864 fn resolve_imports(&mut self);
866 fn resolve_macro_invocation(
869 eager_expansion_root: LocalExpnId,
871 ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
873 fn check_unused_macros(&mut self);
875 // Resolver interfaces for specific built-in macros.
876 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
877 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
878 /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
881 expn_id: LocalExpnId,
883 derive_paths: &dyn Fn() -> DeriveResolutions,
884 ) -> Result<(), Indeterminate>;
885 /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
886 /// back from resolver.
887 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
888 /// Path resolution logic for `#[cfg_accessible(path)]`.
891 expn_id: LocalExpnId,
893 ) -> Result<bool, Indeterminate>;
895 /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
896 /// No caching is performed.
897 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
900 #[derive(Clone, Default)]
901 pub struct ModuleData {
902 /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
903 pub mod_path: Vec<Ident>,
904 /// Stack of paths to files loaded by out-of-line module items,
905 /// used to detect and report recursive module inclusions.
906 pub file_path_stack: Vec<PathBuf>,
907 /// Directory to search child module files in,
908 /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
909 pub dir_path: PathBuf,
913 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
915 mod_path: self.mod_path.clone(),
916 file_path_stack: self.file_path_stack.clone(),
923 pub struct ExpansionData {
926 pub module: Rc<ModuleData>,
927 pub dir_ownership: DirOwnership,
928 pub prior_type_ascription: Option<(Span, bool)>,
929 /// Some parent node that is close to this macro call
930 pub lint_node_id: NodeId,
933 type OnExternModLoaded<'a> =
934 Option<&'a dyn Fn(Ident, Vec<Attribute>, Vec<P<Item>>, Span) -> (Vec<Attribute>, Vec<P<Item>>)>;
936 /// One of these is made during expansion and incrementally updated as we go;
937 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
938 /// -> expn_data` of their expansion context stored into their span.
939 pub struct ExtCtxt<'a> {
940 pub sess: &'a Session,
941 pub ecfg: expand::ExpansionConfig<'a>,
942 pub reduced_recursion_limit: Option<Limit>,
943 pub root_path: PathBuf,
944 pub resolver: &'a mut dyn ResolverExpand,
945 pub current_expansion: ExpansionData,
946 /// Error recovery mode entered when expansion is stuck
947 /// (or during eager expansion, but that's a hack).
948 pub force_mode: bool,
949 pub expansions: FxHashMap<Span, Vec<String>>,
950 /// Called directly after having parsed an external `mod foo;` in expansion.
952 /// `Ident` is the module name.
953 pub(super) extern_mod_loaded: OnExternModLoaded<'a>,
956 impl<'a> ExtCtxt<'a> {
959 ecfg: expand::ExpansionConfig<'a>,
960 resolver: &'a mut dyn ResolverExpand,
961 extern_mod_loaded: OnExternModLoaded<'a>,
966 reduced_recursion_limit: None,
969 root_path: PathBuf::new(),
970 current_expansion: ExpansionData {
971 id: LocalExpnId::ROOT,
973 module: Default::default(),
974 dir_ownership: DirOwnership::Owned { relative: None },
975 prior_type_ascription: None,
976 lint_node_id: ast::CRATE_NODE_ID,
979 expansions: FxHashMap::default(),
983 /// Returns a `Folder` for deeply expanding all macros in an AST node.
984 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
985 expand::MacroExpander::new(self, false)
988 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
989 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
990 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
991 expand::MacroExpander::new(self, true)
993 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
994 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
996 pub fn source_map(&self) -> &'a SourceMap {
997 self.sess.parse_sess.source_map()
999 pub fn parse_sess(&self) -> &'a ParseSess {
1000 &self.sess.parse_sess
1002 pub fn call_site(&self) -> Span {
1003 self.current_expansion.id.expn_data().call_site
1006 /// Equivalent of `Span::def_site` from the proc macro API,
1007 /// except that the location is taken from the span passed as an argument.
1008 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1009 span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1012 /// Equivalent of `Span::call_site` from the proc macro API,
1013 /// except that the location is taken from the span passed as an argument.
1014 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1015 span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1018 /// Equivalent of `Span::mixed_site` from the proc macro API,
1019 /// except that the location is taken from the span passed as an argument.
1020 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1021 span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1024 /// Returns span for the macro which originally caused the current expansion to happen.
1026 /// Stops backtracing at include! boundary.
1027 pub fn expansion_cause(&self) -> Option<Span> {
1028 self.current_expansion.id.expansion_cause()
1031 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
1032 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1035 /// Emit `msg` attached to `sp`, without immediately stopping
1038 /// Compilation will be stopped in the near future (at the end of
1039 /// the macro expansion phase).
1040 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1041 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1043 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1044 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1046 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1047 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1049 pub fn trace_macros_diag(&mut self) {
1050 for (sp, notes) in self.expansions.iter() {
1051 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1057 // Fixme: does this result in errors?
1058 self.expansions.clear();
1060 pub fn bug(&self, msg: &str) -> ! {
1061 self.sess.parse_sess.span_diagnostic.bug(msg);
1063 pub fn trace_macros(&self) -> bool {
1066 pub fn set_trace_macros(&mut self, x: bool) {
1067 self.ecfg.trace_mac = x
1069 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1070 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1071 iter::once(Ident::new(kw::DollarCrate, def_site))
1072 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1075 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1076 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1077 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1080 pub fn check_unused_macros(&mut self) {
1081 self.resolver.check_unused_macros();
1084 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1086 /// This unifies the logic used for resolving `include_X!`.
1088 /// FIXME: move this to `rustc_builtin_macros` and make it private.
1089 pub fn resolve_path(
1091 path: impl Into<PathBuf>,
1093 ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1094 let path = path.into();
1096 // Relative paths are resolved relative to the file in which they are found
1097 // after macro expansion (that is, they are unhygienic).
1098 if !path.is_absolute() {
1099 let callsite = span.source_callsite();
1100 let mut result = match self.source_map().span_to_filename(callsite) {
1101 FileName::Real(name) => name
1103 .expect("attempting to resolve a file path in an external file"),
1104 FileName::DocTest(path, _) => path,
1106 return Err(self.struct_span_err(
1109 "cannot resolve relative path in non-file source `{}`",
1110 other.prefer_local()
1124 /// Extracts a string literal from the macro expanded version of `expr`,
1125 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1126 /// compilation on error, merely emits a non-fatal error and returns `None`.
1127 pub fn expr_to_spanned_string<'a>(
1128 cx: &'a mut ExtCtxt<'_>,
1131 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1132 // Perform eager expansion on the expression.
1133 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1134 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1136 Err(match expr.kind {
1137 ast::ExprKind::Lit(ref l) => match l.kind {
1138 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1139 ast::LitKind::Err(_) => None,
1140 _ => Some(cx.struct_span_err(l.span, err_msg)),
1142 ast::ExprKind::Err => None,
1143 _ => Some(cx.struct_span_err(expr.span, err_msg)),
1147 pub fn expr_to_string(
1148 cx: &mut ExtCtxt<'_>,
1151 ) -> Option<(Symbol, ast::StrStyle)> {
1152 expr_to_spanned_string(cx, expr, err_msg)
1159 .map(|(symbol, style, _)| (symbol, style))
1162 /// Non-fatally assert that `tts` is empty. Note that this function
1163 /// returns even when `tts` is non-empty, macros that *need* to stop
1164 /// compilation should call
1165 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1166 /// done as rarely as possible).
1167 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1168 if !tts.is_empty() {
1169 cx.span_err(sp, &format!("{} takes no arguments", name));
1173 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1174 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1175 match p.parse_expr() {
1176 Ok(e) => return Some(e),
1177 Err(mut err) => err.emit(),
1179 while p.token != token::Eof {
1185 /// Interpreting `tts` as a comma-separated sequence of expressions,
1186 /// expect exactly one string literal, or emit an error and return `None`.
1187 pub fn get_single_str_from_tts(
1188 cx: &mut ExtCtxt<'_>,
1192 ) -> Option<String> {
1193 let mut p = cx.new_parser_from_tts(tts);
1194 if p.token == token::Eof {
1195 cx.span_err(sp, &format!("{} takes 1 argument", name));
1198 let ret = parse_expr(&mut p)?;
1199 let _ = p.eat(&token::Comma);
1201 if p.token != token::Eof {
1202 cx.span_err(sp, &format!("{} takes 1 argument", name));
1204 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1207 /// Extracts comma-separated expressions from `tts`.
1208 /// On error, emit it, and return `None`.
1209 pub fn get_exprs_from_tts(
1210 cx: &mut ExtCtxt<'_>,
1213 ) -> Option<Vec<P<ast::Expr>>> {
1214 let mut p = cx.new_parser_from_tts(tts);
1215 let mut es = Vec::new();
1216 while p.token != token::Eof {
1217 let expr = parse_expr(&mut p)?;
1219 // Perform eager expansion on the expression.
1220 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1221 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1224 if p.eat(&token::Comma) {
1227 if p.token != token::Eof {
1228 cx.span_err(sp, "expected token: `,`");
1235 pub fn parse_macro_name_and_helper_attrs(
1236 diag: &rustc_errors::Handler,
1239 ) -> Option<(Symbol, Vec<Symbol>)> {
1240 // Once we've located the `#[proc_macro_derive]` attribute, verify
1241 // that it's of the form `#[proc_macro_derive(Foo)]` or
1242 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1243 let list = match attr.meta_item_list() {
1245 None => return None,
1247 if list.len() != 1 && list.len() != 2 {
1248 diag.span_err(attr.span, "attribute must have either one or two arguments");
1251 let trait_attr = match list[0].meta_item() {
1252 Some(meta_item) => meta_item,
1254 diag.span_err(list[0].span(), "not a meta item");
1258 let trait_ident = match trait_attr.ident() {
1259 Some(trait_ident) if trait_attr.is_word() => trait_ident,
1261 diag.span_err(trait_attr.span, "must only be one word");
1266 if !trait_ident.name.can_be_raw() {
1269 &format!("`{}` cannot be a name of {} macro", trait_ident, descr),
1273 let attributes_attr = list.get(1);
1274 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1275 if !attr.has_name(sym::attributes) {
1276 diag.span_err(attr.span(), "second argument must be `attributes`")
1278 attr.meta_item_list()
1279 .unwrap_or_else(|| {
1280 diag.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
1284 .filter_map(|attr| {
1285 let attr = match attr.meta_item() {
1286 Some(meta_item) => meta_item,
1288 diag.span_err(attr.span(), "not a meta item");
1293 let ident = match attr.ident() {
1294 Some(ident) if attr.is_word() => ident,
1296 diag.span_err(attr.span, "must only be one word");
1300 if !ident.name.can_be_raw() {
1303 &format!("`{}` cannot be a name of derive helper attribute", ident),
1314 Some((trait_ident.name, proc_attrs))
1317 /// This nonterminal looks like some specific enums from
1318 /// `proc-macro-hack` and `procedural-masquerade` crates.
1319 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1320 /// asserts in old versions of those crates and their wide use in the ecosystem.
1321 /// See issue #73345 for more details.
1322 /// FIXME(#73933): Remove this eventually.
1323 pub(crate) fn pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1324 let item = match nt {
1325 Nonterminal::NtItem(item) => item,
1326 Nonterminal::NtStmt(stmt) => match &stmt.kind {
1327 ast::StmtKind::Item(item) => item,
1333 let name = item.ident.name;
1334 if name == sym::ProceduralMasqueradeDummyType {
1335 if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1336 if let [variant] = &*enum_def.variants {
1337 if variant.ident.name == sym::Input {
1338 sess.buffer_lint_with_diagnostic(
1339 &PROC_MACRO_BACK_COMPAT,
1342 "using `procedural-masquerade` crate",
1343 BuiltinLintDiagnostics::ProcMacroBackCompat(
1344 "The `procedural-masquerade` crate has been unnecessary since Rust 1.30.0. \
1345 Versions of this crate below 0.1.7 will eventually stop compiling.".to_string())