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::DefId;
18 use rustc_span::edition::Edition;
19 use rustc_span::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind};
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 #[derive(Debug, Clone)]
33 pub enum Annotatable {
35 TraitItem(P<ast::AssocItem>),
36 ImplItem(P<ast::AssocItem>),
37 ForeignItem(P<ast::ForeignItem>),
41 ExprField(ast::ExprField),
42 PatField(ast::PatField),
43 GenericParam(ast::GenericParam),
45 FieldDef(ast::FieldDef),
46 Variant(ast::Variant),
50 pub fn span(&self) -> Span {
52 Annotatable::Item(ref item) => item.span,
53 Annotatable::TraitItem(ref trait_item) => trait_item.span,
54 Annotatable::ImplItem(ref impl_item) => impl_item.span,
55 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
56 Annotatable::Stmt(ref stmt) => stmt.span,
57 Annotatable::Expr(ref expr) => expr.span,
58 Annotatable::Arm(ref arm) => arm.span,
59 Annotatable::ExprField(ref field) => field.span,
60 Annotatable::PatField(ref fp) => fp.pat.span,
61 Annotatable::GenericParam(ref gp) => gp.ident.span,
62 Annotatable::Param(ref p) => p.span,
63 Annotatable::FieldDef(ref sf) => sf.span,
64 Annotatable::Variant(ref v) => v.span,
68 pub fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
70 Annotatable::Item(item) => item.visit_attrs(f),
71 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
72 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
73 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
74 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
75 Annotatable::Expr(expr) => expr.visit_attrs(f),
76 Annotatable::Arm(arm) => arm.visit_attrs(f),
77 Annotatable::ExprField(field) => field.visit_attrs(f),
78 Annotatable::PatField(fp) => fp.visit_attrs(f),
79 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
80 Annotatable::Param(p) => p.visit_attrs(f),
81 Annotatable::FieldDef(sf) => sf.visit_attrs(f),
82 Annotatable::Variant(v) => v.visit_attrs(f),
86 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
88 Annotatable::Item(item) => visitor.visit_item(item),
89 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
90 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
91 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
92 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
93 Annotatable::Expr(expr) => visitor.visit_expr(expr),
94 Annotatable::Arm(arm) => visitor.visit_arm(arm),
95 Annotatable::ExprField(field) => visitor.visit_expr_field(field),
96 Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
97 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
98 Annotatable::Param(p) => visitor.visit_param(p),
99 Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
100 Annotatable::Variant(v) => visitor.visit_variant(v),
104 pub fn into_nonterminal(self) -> Nonterminal {
106 Annotatable::Item(item) => token::NtItem(item),
107 Annotatable::TraitItem(item) | Annotatable::ImplItem(item) => {
108 token::NtItem(P(item.and_then(ast::AssocItem::into_item)))
110 Annotatable::ForeignItem(item) => {
111 token::NtItem(P(item.and_then(ast::ForeignItem::into_item)))
113 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
114 Annotatable::Expr(expr) => token::NtExpr(expr),
116 | Annotatable::ExprField(..)
117 | Annotatable::PatField(..)
118 | Annotatable::GenericParam(..)
119 | Annotatable::Param(..)
120 | Annotatable::FieldDef(..)
121 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
125 crate fn into_tokens(self, sess: &ParseSess) -> TokenStream {
126 nt_to_tokenstream(&self.into_nonterminal(), sess, CanSynthesizeMissingTokens::No)
129 pub fn expect_item(self) -> P<ast::Item> {
131 Annotatable::Item(i) => i,
132 _ => panic!("expected Item"),
136 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
138 Annotatable::TraitItem(i) => i,
139 _ => panic!("expected Item"),
143 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
145 Annotatable::ImplItem(i) => i,
146 _ => panic!("expected Item"),
150 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
152 Annotatable::ForeignItem(i) => i,
153 _ => panic!("expected foreign item"),
157 pub fn expect_stmt(self) -> ast::Stmt {
159 Annotatable::Stmt(stmt) => stmt.into_inner(),
160 _ => panic!("expected statement"),
164 pub fn expect_expr(self) -> P<ast::Expr> {
166 Annotatable::Expr(expr) => expr,
167 _ => panic!("expected expression"),
171 pub fn expect_arm(self) -> ast::Arm {
173 Annotatable::Arm(arm) => arm,
174 _ => panic!("expected match arm"),
178 pub fn expect_expr_field(self) -> ast::ExprField {
180 Annotatable::ExprField(field) => field,
181 _ => panic!("expected field"),
185 pub fn expect_pat_field(self) -> ast::PatField {
187 Annotatable::PatField(fp) => fp,
188 _ => panic!("expected field pattern"),
192 pub fn expect_generic_param(self) -> ast::GenericParam {
194 Annotatable::GenericParam(gp) => gp,
195 _ => panic!("expected generic parameter"),
199 pub fn expect_param(self) -> ast::Param {
201 Annotatable::Param(param) => param,
202 _ => panic!("expected parameter"),
206 pub fn expect_field_def(self) -> ast::FieldDef {
208 Annotatable::FieldDef(sf) => sf,
209 _ => panic!("expected struct field"),
213 pub fn expect_variant(self) -> ast::Variant {
215 Annotatable::Variant(v) => v,
216 _ => panic!("expected variant"),
221 /// Result of an expansion that may need to be retried.
222 /// Consider using this for non-`MultiItemModifier` expanders as well.
223 pub enum ExpandResult<T, U> {
224 /// Expansion produced a result (possibly dummy).
226 /// Expansion could not produce a result and needs to be retried.
230 // `meta_item` is the attribute, and `item` is the item being modified.
231 pub trait MultiItemModifier {
234 ecx: &mut ExtCtxt<'_>,
236 meta_item: &ast::MetaItem,
238 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
241 impl<F> MultiItemModifier for F
243 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
247 ecx: &mut ExtCtxt<'_>,
249 meta_item: &ast::MetaItem,
251 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
252 ExpandResult::Ready(self(ecx, span, meta_item, item))
256 pub trait ProcMacro {
259 ecx: &'cx mut ExtCtxt<'_>,
262 ) -> Result<TokenStream, ErrorReported>;
265 impl<F> ProcMacro for F
267 F: Fn(TokenStream) -> TokenStream,
271 _ecx: &'cx mut ExtCtxt<'_>,
274 ) -> Result<TokenStream, ErrorReported> {
275 // FIXME setup implicit context in TLS before calling self.
280 pub trait AttrProcMacro {
283 ecx: &'cx mut ExtCtxt<'_>,
285 annotation: TokenStream,
286 annotated: TokenStream,
287 ) -> Result<TokenStream, ErrorReported>;
290 impl<F> AttrProcMacro for F
292 F: Fn(TokenStream, TokenStream) -> TokenStream,
296 _ecx: &'cx mut ExtCtxt<'_>,
298 annotation: TokenStream,
299 annotated: TokenStream,
300 ) -> Result<TokenStream, ErrorReported> {
301 // FIXME setup implicit context in TLS before calling self.
302 Ok(self(annotation, annotated))
306 /// Represents a thing that maps token trees to Macro Results
307 pub trait TTMacroExpander {
310 ecx: &'cx mut ExtCtxt<'_>,
313 ) -> Box<dyn MacResult + 'cx>;
316 pub type MacroExpanderFn =
317 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
319 impl<F> TTMacroExpander for F
321 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
325 ecx: &'cx mut ExtCtxt<'_>,
328 ) -> Box<dyn MacResult + 'cx> {
329 self(ecx, span, input)
333 // Use a macro because forwarding to a simple function has type system issues
334 macro_rules! make_stmts_default {
336 $me.make_expr().map(|e| {
337 smallvec![ast::Stmt {
338 id: ast::DUMMY_NODE_ID,
340 kind: ast::StmtKind::Expr(e),
346 /// The result of a macro expansion. The return values of the various
347 /// methods are spliced into the AST at the callsite of the macro.
348 pub trait MacResult {
349 /// Creates an expression.
350 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
353 /// Creates zero or more items.
354 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
358 /// Creates zero or more impl items.
359 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
363 /// Creates zero or more trait items.
364 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
368 /// Creates zero or more items in an `extern {}` block
369 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
373 /// Creates a pattern.
374 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
378 /// Creates zero or more statements.
380 /// By default this attempts to create an expression statement,
381 /// returning None if that fails.
382 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
383 make_stmts_default!(self)
386 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
390 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
394 fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
398 fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
402 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
406 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
410 fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
414 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
419 macro_rules! make_MacEager {
420 ( $( $fld:ident: $t:ty, )* ) => {
421 /// `MacResult` implementation for the common case where you've already
422 /// built each form of AST that you might return.
424 pub struct MacEager {
426 pub $fld: Option<$t>,
432 pub fn $fld(v: $t) -> Box<dyn MacResult> {
446 items: SmallVec<[P<ast::Item>; 1]>,
447 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
448 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
449 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
450 stmts: SmallVec<[ast::Stmt; 1]>,
454 impl MacResult for MacEager {
455 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
459 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
463 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
467 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
471 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
475 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
476 match self.stmts.as_ref().map_or(0, |s| s.len()) {
477 0 => make_stmts_default!(self),
482 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
483 if let Some(p) = self.pat {
486 if let Some(e) = self.expr {
487 if let ast::ExprKind::Lit(_) = e.kind {
488 return Some(P(ast::Pat {
489 id: ast::DUMMY_NODE_ID,
491 kind: PatKind::Lit(e),
499 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
504 /// Fill-in macro expansion result, to allow compilation to continue
505 /// after hitting errors.
506 #[derive(Copy, Clone)]
507 pub struct DummyResult {
513 /// Creates a default MacResult that can be anything.
515 /// Use this as a return value after hitting any errors and
516 /// calling `span_err`.
517 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
518 Box::new(DummyResult { is_error: true, span })
521 /// Same as `any`, but must be a valid fragment, not error.
522 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
523 Box::new(DummyResult { is_error: false, span })
526 /// A plain dummy expression.
527 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
529 id: ast::DUMMY_NODE_ID,
530 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
532 attrs: ast::AttrVec::new(),
537 /// A plain dummy pattern.
538 pub fn raw_pat(sp: Span) -> ast::Pat {
539 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
542 /// A plain dummy type.
543 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
545 id: ast::DUMMY_NODE_ID,
546 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
553 impl MacResult for DummyResult {
554 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
555 Some(DummyResult::raw_expr(self.span, self.is_error))
558 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
559 Some(P(DummyResult::raw_pat(self.span)))
562 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
563 Some(SmallVec::new())
566 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
567 Some(SmallVec::new())
570 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
571 Some(SmallVec::new())
574 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
575 Some(SmallVec::new())
578 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
579 Some(smallvec![ast::Stmt {
580 id: ast::DUMMY_NODE_ID,
581 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
586 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
587 Some(DummyResult::raw_ty(self.span, self.is_error))
590 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
591 Some(SmallVec::new())
594 fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
595 Some(SmallVec::new())
598 fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
599 Some(SmallVec::new())
602 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
603 Some(SmallVec::new())
606 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
607 Some(SmallVec::new())
610 fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
611 Some(SmallVec::new())
614 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
615 Some(SmallVec::new())
619 /// A syntax extension kind.
620 pub enum SyntaxExtensionKind {
621 /// A token-based function-like macro.
623 /// An expander with signature TokenStream -> TokenStream.
624 Box<dyn ProcMacro + sync::Sync + sync::Send>,
627 /// An AST-based function-like macro.
629 /// An expander with signature TokenStream -> AST.
630 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
633 /// A token-based attribute macro.
635 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
636 /// The first TokenSteam is the attribute itself, the second is the annotated item.
637 /// The produced TokenSteam replaces the input TokenSteam.
638 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
641 /// An AST-based attribute macro.
643 /// An expander with signature (AST, AST) -> AST.
644 /// The first AST fragment is the attribute itself, the second is the annotated item.
645 /// The produced AST fragment replaces the input AST fragment.
646 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
649 /// A trivial attribute "macro" that does nothing,
650 /// only keeps the attribute and marks it as inert,
651 /// thus making it ineligible for further expansion.
653 /// Suppresses the `unused_attributes` lint for this attribute.
657 /// A token-based derive macro.
659 /// An expander with signature TokenStream -> TokenStream (not yet).
660 /// The produced TokenSteam is appended to the input TokenSteam.
661 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
664 /// An AST-based derive macro.
666 /// An expander with signature AST -> AST.
667 /// The produced AST fragment is appended to the input AST fragment.
668 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
672 /// A struct representing a macro definition in "lowered" form ready for expansion.
673 pub struct SyntaxExtension {
674 /// A syntax extension kind.
675 pub kind: SyntaxExtensionKind,
676 /// Span of the macro definition.
678 /// List of unstable features that are treated as stable inside this macro.
679 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
680 /// Suppresses the `unsafe_code` lint for code produced by this macro.
681 pub allow_internal_unsafe: bool,
682 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
683 pub local_inner_macros: bool,
684 /// The macro's stability info.
685 pub stability: Option<Stability>,
686 /// The macro's deprecation info.
687 pub deprecation: Option<Deprecation>,
688 /// Names of helper attributes registered by this macro.
689 pub helper_attrs: Vec<Symbol>,
690 /// Edition of the crate in which this macro is defined.
691 pub edition: Edition,
692 /// Built-in macros have a couple of special properties like availability
693 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
694 pub builtin_name: Option<Symbol>,
697 impl SyntaxExtension {
698 /// Returns which kind of macro calls this syntax extension.
699 pub fn macro_kind(&self) -> MacroKind {
701 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
702 SyntaxExtensionKind::Attr(..)
703 | SyntaxExtensionKind::LegacyAttr(..)
704 | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
705 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
711 /// Constructs a syntax extension with default properties.
712 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
715 allow_internal_unstable: None,
716 allow_internal_unsafe: false,
717 local_inner_macros: false,
720 helper_attrs: Vec::new(),
727 /// Constructs a syntax extension with the given properties
728 /// and other properties converted from attributes.
731 kind: SyntaxExtensionKind,
733 helper_attrs: Vec<Symbol>,
736 attrs: &[ast::Attribute],
737 ) -> SyntaxExtension {
738 let allow_internal_unstable =
739 attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
741 let mut local_inner_macros = false;
742 if let Some(macro_export) = sess.find_by_name(attrs, sym::macro_export) {
743 if let Some(l) = macro_export.meta_item_list() {
744 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
748 let builtin_name = sess
749 .find_by_name(attrs, sym::rustc_builtin_macro)
750 .map(|a| a.value_str().unwrap_or(name));
751 let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
752 if let Some((_, sp)) = const_stability {
755 .struct_span_err(sp, "macros cannot have const stability attributes")
756 .span_label(sp, "invalid const stability attribute")
758 sess.source_map().guess_head_span(span),
759 "const stability attribute affects this macro",
767 allow_internal_unstable: (!allow_internal_unstable.is_empty())
768 .then(|| allow_internal_unstable.into()),
769 allow_internal_unsafe: sess.contains_name(attrs, sym::allow_internal_unsafe),
771 stability: stability.map(|(s, _)| s),
772 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
779 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
781 _: &'cx mut ExtCtxt<'_>,
784 ) -> Box<dyn MacResult + 'cx> {
785 DummyResult::any(span)
787 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
790 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
796 ) -> Vec<Annotatable> {
799 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
802 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
803 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
811 macro_def_id: Option<DefId>,
814 ExpnKind::Macro(self.macro_kind(), descr),
818 self.allow_internal_unstable.clone(),
819 self.allow_internal_unsafe,
820 self.local_inner_macros,
827 /// Error type that denotes indeterminacy.
828 pub struct Indeterminate;
830 pub type DeriveResolutions = Vec<(ast::Path, Option<Lrc<SyntaxExtension>>)>;
832 pub trait ResolverExpand {
833 fn next_node_id(&mut self) -> NodeId;
835 fn resolve_dollar_crates(&mut self);
836 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment);
837 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
839 fn expansion_for_ast_pass(
844 parent_module_id: Option<NodeId>,
847 fn resolve_imports(&mut self);
849 fn resolve_macro_invocation(
852 eager_expansion_root: ExpnId,
854 ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
856 fn check_unused_macros(&mut self);
858 /// Some parent node that is close enough to the given macro call.
859 fn lint_node_id(&self, expn_id: ExpnId) -> NodeId;
861 // Resolver interfaces for specific built-in macros.
862 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
863 fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
864 /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
869 derive_paths: &dyn Fn() -> DeriveResolutions,
870 ) -> Result<(), Indeterminate>;
871 /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
872 /// back from resolver.
873 fn take_derive_resolutions(&mut self, expn_id: ExpnId) -> Option<DeriveResolutions>;
874 /// Path resolution logic for `#[cfg_accessible(path)]`.
875 fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate>;
878 #[derive(Clone, Default)]
879 pub struct ModuleData {
880 /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
881 pub mod_path: Vec<Ident>,
882 /// Stack of paths to files loaded by out-of-line module items,
883 /// used to detect and report recursive module inclusions.
884 pub file_path_stack: Vec<PathBuf>,
885 /// Directory to search child module files in,
886 /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
887 pub dir_path: PathBuf,
891 pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
893 mod_path: self.mod_path.clone(),
894 file_path_stack: self.file_path_stack.clone(),
901 pub struct ExpansionData {
904 pub module: Rc<ModuleData>,
905 pub dir_ownership: DirOwnership,
906 pub prior_type_ascription: Option<(Span, bool)>,
909 type OnExternModLoaded<'a> =
910 Option<&'a dyn Fn(Ident, Vec<Attribute>, Vec<P<Item>>, Span) -> (Vec<Attribute>, Vec<P<Item>>)>;
912 /// One of these is made during expansion and incrementally updated as we go;
913 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
914 /// -> expn_data` of their expansion context stored into their span.
915 pub struct ExtCtxt<'a> {
916 pub sess: &'a Session,
917 pub ecfg: expand::ExpansionConfig<'a>,
918 pub reduced_recursion_limit: Option<Limit>,
919 pub root_path: PathBuf,
920 pub resolver: &'a mut dyn ResolverExpand,
921 pub current_expansion: ExpansionData,
922 /// Error recovery mode entered when expansion is stuck
923 /// (or during eager expansion, but that's a hack).
924 pub force_mode: bool,
925 pub expansions: FxHashMap<Span, Vec<String>>,
926 /// Called directly after having parsed an external `mod foo;` in expansion.
928 /// `Ident` is the module name.
929 pub(super) extern_mod_loaded: OnExternModLoaded<'a>,
932 impl<'a> ExtCtxt<'a> {
935 ecfg: expand::ExpansionConfig<'a>,
936 resolver: &'a mut dyn ResolverExpand,
937 extern_mod_loaded: OnExternModLoaded<'a>,
942 reduced_recursion_limit: None,
945 root_path: PathBuf::new(),
946 current_expansion: ExpansionData {
949 module: Default::default(),
950 dir_ownership: DirOwnership::Owned { relative: None },
951 prior_type_ascription: None,
954 expansions: FxHashMap::default(),
958 /// Returns a `Folder` for deeply expanding all macros in an AST node.
959 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
960 expand::MacroExpander::new(self, false)
963 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
964 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
965 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
966 expand::MacroExpander::new(self, true)
968 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
969 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
971 pub fn source_map(&self) -> &'a SourceMap {
972 self.sess.parse_sess.source_map()
974 pub fn parse_sess(&self) -> &'a ParseSess {
975 &self.sess.parse_sess
977 pub fn call_site(&self) -> Span {
978 self.current_expansion.id.expn_data().call_site
981 /// Equivalent of `Span::def_site` from the proc macro API,
982 /// except that the location is taken from the span passed as an argument.
983 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
984 span.with_def_site_ctxt(self.current_expansion.id)
987 /// Equivalent of `Span::call_site` from the proc macro API,
988 /// except that the location is taken from the span passed as an argument.
989 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
990 span.with_call_site_ctxt(self.current_expansion.id)
993 /// Equivalent of `Span::mixed_site` from the proc macro API,
994 /// except that the location is taken from the span passed as an argument.
995 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
996 span.with_mixed_site_ctxt(self.current_expansion.id)
999 /// Returns span for the macro which originally caused the current expansion to happen.
1001 /// Stops backtracing at include! boundary.
1002 pub fn expansion_cause(&self) -> Option<Span> {
1003 self.current_expansion.id.expansion_cause()
1006 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
1007 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1010 /// Emit `msg` attached to `sp`, without immediately stopping
1013 /// Compilation will be stopped in the near future (at the end of
1014 /// the macro expansion phase).
1015 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1016 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1018 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1019 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1021 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1022 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1024 pub fn trace_macros_diag(&mut self) {
1025 for (sp, notes) in self.expansions.iter() {
1026 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1032 // Fixme: does this result in errors?
1033 self.expansions.clear();
1035 pub fn bug(&self, msg: &str) -> ! {
1036 self.sess.parse_sess.span_diagnostic.bug(msg);
1038 pub fn trace_macros(&self) -> bool {
1041 pub fn set_trace_macros(&mut self, x: bool) {
1042 self.ecfg.trace_mac = x
1044 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1045 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1046 iter::once(Ident::new(kw::DollarCrate, def_site))
1047 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1050 pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1051 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1052 components.iter().map(|&s| Ident::new(s, def_site)).collect()
1055 pub fn check_unused_macros(&mut self) {
1056 self.resolver.check_unused_macros();
1059 /// Resolves a path mentioned inside Rust code.
1061 /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
1063 /// Returns an absolute path to the file that `path` refers to.
1064 pub fn resolve_path(
1066 path: impl Into<PathBuf>,
1068 ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1069 let path = path.into();
1071 // Relative paths are resolved relative to the file in which they are found
1072 // after macro expansion (that is, they are unhygienic).
1073 if !path.is_absolute() {
1074 let callsite = span.source_callsite();
1075 let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1076 FileName::Real(name) => name.into_local_path(),
1077 FileName::DocTest(path, _) => path,
1079 return Err(self.struct_span_err(
1081 &format!("cannot resolve relative path in non-file source `{}`", other),
1094 /// Extracts a string literal from the macro expanded version of `expr`,
1095 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1096 /// compilation on error, merely emits a non-fatal error and returns `None`.
1097 pub fn expr_to_spanned_string<'a>(
1098 cx: &'a mut ExtCtxt<'_>,
1101 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1102 // Perform eager expansion on the expression.
1103 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1104 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1106 Err(match expr.kind {
1107 ast::ExprKind::Lit(ref l) => match l.kind {
1108 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1109 ast::LitKind::Err(_) => None,
1110 _ => Some(cx.struct_span_err(l.span, err_msg)),
1112 ast::ExprKind::Err => None,
1113 _ => Some(cx.struct_span_err(expr.span, err_msg)),
1117 pub fn expr_to_string(
1118 cx: &mut ExtCtxt<'_>,
1121 ) -> Option<(Symbol, ast::StrStyle)> {
1122 expr_to_spanned_string(cx, expr, err_msg)
1129 .map(|(symbol, style, _)| (symbol, style))
1132 /// Non-fatally assert that `tts` is empty. Note that this function
1133 /// returns even when `tts` is non-empty, macros that *need* to stop
1134 /// compilation should call
1135 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1136 /// done as rarely as possible).
1137 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1138 if !tts.is_empty() {
1139 cx.span_err(sp, &format!("{} takes no arguments", name));
1143 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1144 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1145 match p.parse_expr() {
1146 Ok(e) => return Some(e),
1147 Err(mut err) => err.emit(),
1149 while p.token != token::Eof {
1155 /// Interpreting `tts` as a comma-separated sequence of expressions,
1156 /// expect exactly one string literal, or emit an error and return `None`.
1157 pub fn get_single_str_from_tts(
1158 cx: &mut ExtCtxt<'_>,
1162 ) -> Option<String> {
1163 let mut p = cx.new_parser_from_tts(tts);
1164 if p.token == token::Eof {
1165 cx.span_err(sp, &format!("{} takes 1 argument", name));
1168 let ret = parse_expr(&mut p)?;
1169 let _ = p.eat(&token::Comma);
1171 if p.token != token::Eof {
1172 cx.span_err(sp, &format!("{} takes 1 argument", name));
1174 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1177 /// Extracts comma-separated expressions from `tts`.
1178 /// On error, emit it, and return `None`.
1179 pub fn get_exprs_from_tts(
1180 cx: &mut ExtCtxt<'_>,
1183 ) -> Option<Vec<P<ast::Expr>>> {
1184 let mut p = cx.new_parser_from_tts(tts);
1185 let mut es = Vec::new();
1186 while p.token != token::Eof {
1187 let expr = parse_expr(&mut p)?;
1189 // Perform eager expansion on the expression.
1190 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1191 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1194 if p.eat(&token::Comma) {
1197 if p.token != token::Eof {
1198 cx.span_err(sp, "expected token: `,`");
1205 /// This nonterminal looks like some specific enums from
1206 /// `proc-macro-hack` and `procedural-masquerade` crates.
1207 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1208 /// asserts in old versions of those crates and their wide use in the ecosystem.
1209 /// See issue #73345 for more details.
1210 /// FIXME(#73933): Remove this eventually.
1211 pub(crate) fn pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1212 let item = match nt {
1213 Nonterminal::NtItem(item) => item,
1214 Nonterminal::NtStmt(stmt) => match &stmt.kind {
1215 ast::StmtKind::Item(item) => item,
1221 let name = item.ident.name;
1222 if name == sym::ProceduralMasqueradeDummyType {
1223 if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1224 if let [variant] = &*enum_def.variants {
1225 if variant.ident.name == sym::Input {
1226 sess.buffer_lint_with_diagnostic(
1227 &PROC_MACRO_BACK_COMPAT,
1230 "using `procedural-masquerade` crate",
1231 BuiltinLintDiagnostics::ProcMacroBackCompat(
1232 "The `procedural-masquerade` crate has been unnecessary since Rust 1.30.0. \
1233 Versions of this crate below 0.1.7 will eventually stop compiling.".to_string())