1 use crate::expand::{self, AstFragment, Invocation};
2 use crate::module::DirectoryOwnership;
6 use rustc_ast::tokenstream::TokenStream;
7 use rustc_ast::visit::{AssocCtxt, Visitor};
8 use rustc_ast::{self as ast, Attribute, NodeId, PatKind};
9 use rustc_attr::{self as attr, Deprecation, HasAttrs, 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_parse::{self, nt_to_tokenstream, parser, MACRO_ARGUMENTS};
14 use rustc_session::{parse::ParseSess, Limit, Session};
15 use rustc_span::def_id::{DefId, LOCAL_CRATE};
16 use rustc_span::edition::Edition;
17 use rustc_span::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind};
18 use rustc_span::source_map::SourceMap;
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::{FileName, MultiSpan, Span, DUMMY_SP};
21 use smallvec::{smallvec, SmallVec};
23 use std::default::Default;
25 use std::path::PathBuf;
28 crate use rustc_span::hygiene::MacroKind;
30 #[derive(Debug, Clone)]
31 pub enum Annotatable {
33 TraitItem(P<ast::AssocItem>),
34 ImplItem(P<ast::AssocItem>),
35 ForeignItem(P<ast::ForeignItem>),
40 FieldPat(ast::FieldPat),
41 GenericParam(ast::GenericParam),
43 StructField(ast::StructField),
44 Variant(ast::Variant),
47 impl HasAttrs for Annotatable {
48 fn attrs(&self) -> &[Attribute] {
50 Annotatable::Item(ref item) => &item.attrs,
51 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
52 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
53 Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
54 Annotatable::Stmt(ref stmt) => stmt.attrs(),
55 Annotatable::Expr(ref expr) => &expr.attrs,
56 Annotatable::Arm(ref arm) => &arm.attrs,
57 Annotatable::Field(ref field) => &field.attrs,
58 Annotatable::FieldPat(ref fp) => &fp.attrs,
59 Annotatable::GenericParam(ref gp) => &gp.attrs,
60 Annotatable::Param(ref p) => &p.attrs,
61 Annotatable::StructField(ref sf) => &sf.attrs,
62 Annotatable::Variant(ref v) => &v.attrs(),
66 fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
68 Annotatable::Item(item) => item.visit_attrs(f),
69 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
70 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
71 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
72 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
73 Annotatable::Expr(expr) => expr.visit_attrs(f),
74 Annotatable::Arm(arm) => arm.visit_attrs(f),
75 Annotatable::Field(field) => field.visit_attrs(f),
76 Annotatable::FieldPat(fp) => fp.visit_attrs(f),
77 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
78 Annotatable::Param(p) => p.visit_attrs(f),
79 Annotatable::StructField(sf) => sf.visit_attrs(f),
80 Annotatable::Variant(v) => v.visit_attrs(f),
86 pub fn span(&self) -> Span {
88 Annotatable::Item(ref item) => item.span,
89 Annotatable::TraitItem(ref trait_item) => trait_item.span,
90 Annotatable::ImplItem(ref impl_item) => impl_item.span,
91 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
92 Annotatable::Stmt(ref stmt) => stmt.span,
93 Annotatable::Expr(ref expr) => expr.span,
94 Annotatable::Arm(ref arm) => arm.span,
95 Annotatable::Field(ref field) => field.span,
96 Annotatable::FieldPat(ref fp) => fp.pat.span,
97 Annotatable::GenericParam(ref gp) => gp.ident.span,
98 Annotatable::Param(ref p) => p.span,
99 Annotatable::StructField(ref sf) => sf.span,
100 Annotatable::Variant(ref v) => v.span,
104 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
106 Annotatable::Item(item) => visitor.visit_item(item),
107 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
108 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
109 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
110 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
111 Annotatable::Expr(expr) => visitor.visit_expr(expr),
112 Annotatable::Arm(arm) => visitor.visit_arm(arm),
113 Annotatable::Field(field) => visitor.visit_field(field),
114 Annotatable::FieldPat(fp) => visitor.visit_field_pattern(fp),
115 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
116 Annotatable::Param(p) => visitor.visit_param(p),
117 Annotatable::StructField(sf) => visitor.visit_struct_field(sf),
118 Annotatable::Variant(v) => visitor.visit_variant(v),
122 crate fn into_tokens(self, sess: &ParseSess) -> TokenStream {
123 let nt = match self {
124 Annotatable::Item(item) => token::NtItem(item),
125 Annotatable::TraitItem(item) | Annotatable::ImplItem(item) => {
126 token::NtItem(P(item.and_then(ast::AssocItem::into_item)))
128 Annotatable::ForeignItem(item) => {
129 token::NtItem(P(item.and_then(ast::ForeignItem::into_item)))
131 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
132 Annotatable::Expr(expr) => token::NtExpr(expr),
134 | Annotatable::Field(..)
135 | Annotatable::FieldPat(..)
136 | Annotatable::GenericParam(..)
137 | Annotatable::Param(..)
138 | Annotatable::StructField(..)
139 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
141 nt_to_tokenstream(&nt, sess, DUMMY_SP)
144 pub fn expect_item(self) -> P<ast::Item> {
146 Annotatable::Item(i) => i,
147 _ => panic!("expected Item"),
151 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
153 Annotatable::TraitItem(i) => i,
154 _ => panic!("expected Item"),
158 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
160 Annotatable::ImplItem(i) => i,
161 _ => panic!("expected Item"),
165 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
167 Annotatable::ForeignItem(i) => i,
168 _ => panic!("expected foreign item"),
172 pub fn expect_stmt(self) -> ast::Stmt {
174 Annotatable::Stmt(stmt) => stmt.into_inner(),
175 _ => panic!("expected statement"),
179 pub fn expect_expr(self) -> P<ast::Expr> {
181 Annotatable::Expr(expr) => expr,
182 _ => panic!("expected expression"),
186 pub fn expect_arm(self) -> ast::Arm {
188 Annotatable::Arm(arm) => arm,
189 _ => panic!("expected match arm"),
193 pub fn expect_field(self) -> ast::Field {
195 Annotatable::Field(field) => field,
196 _ => panic!("expected field"),
200 pub fn expect_field_pattern(self) -> ast::FieldPat {
202 Annotatable::FieldPat(fp) => fp,
203 _ => panic!("expected field pattern"),
207 pub fn expect_generic_param(self) -> ast::GenericParam {
209 Annotatable::GenericParam(gp) => gp,
210 _ => panic!("expected generic parameter"),
214 pub fn expect_param(self) -> ast::Param {
216 Annotatable::Param(param) => param,
217 _ => panic!("expected parameter"),
221 pub fn expect_struct_field(self) -> ast::StructField {
223 Annotatable::StructField(sf) => sf,
224 _ => panic!("expected struct field"),
228 pub fn expect_variant(self) -> ast::Variant {
230 Annotatable::Variant(v) => v,
231 _ => panic!("expected variant"),
235 pub fn derive_allowed(&self) -> bool {
237 Annotatable::Stmt(ref stmt) => match stmt.kind {
238 ast::StmtKind::Item(ref item) => matches!(
240 ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..)
244 Annotatable::Item(ref item) => match item.kind {
245 ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..) => {
255 /// Result of an expansion that may need to be retried.
256 /// Consider using this for non-`MultiItemModifier` expanders as well.
257 pub enum ExpandResult<T, U> {
258 /// Expansion produced a result (possibly dummy).
260 /// Expansion could not produce a result and needs to be retried.
264 // `meta_item` is the attribute, and `item` is the item being modified.
265 pub trait MultiItemModifier {
268 ecx: &mut ExtCtxt<'_>,
270 meta_item: &ast::MetaItem,
272 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
275 impl<F> MultiItemModifier for F
277 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
281 ecx: &mut ExtCtxt<'_>,
283 meta_item: &ast::MetaItem,
285 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
286 ExpandResult::Ready(self(ecx, span, meta_item, item))
290 pub trait ProcMacro {
293 ecx: &'cx mut ExtCtxt<'_>,
296 ) -> Result<TokenStream, ErrorReported>;
299 impl<F> ProcMacro for F
301 F: Fn(TokenStream) -> TokenStream,
305 _ecx: &'cx mut ExtCtxt<'_>,
308 ) -> Result<TokenStream, ErrorReported> {
309 // FIXME setup implicit context in TLS before calling self.
314 pub trait AttrProcMacro {
317 ecx: &'cx mut ExtCtxt<'_>,
319 annotation: TokenStream,
320 annotated: TokenStream,
321 ) -> Result<TokenStream, ErrorReported>;
324 impl<F> AttrProcMacro for F
326 F: Fn(TokenStream, TokenStream) -> TokenStream,
330 _ecx: &'cx mut ExtCtxt<'_>,
332 annotation: TokenStream,
333 annotated: TokenStream,
334 ) -> Result<TokenStream, ErrorReported> {
335 // FIXME setup implicit context in TLS before calling self.
336 Ok(self(annotation, annotated))
340 /// Represents a thing that maps token trees to Macro Results
341 pub trait TTMacroExpander {
344 ecx: &'cx mut ExtCtxt<'_>,
347 ) -> Box<dyn MacResult + 'cx>;
350 pub type MacroExpanderFn =
351 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
353 impl<F> TTMacroExpander for F
355 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
359 ecx: &'cx mut ExtCtxt<'_>,
362 ) -> Box<dyn MacResult + 'cx> {
363 self(ecx, span, input)
367 // Use a macro because forwarding to a simple function has type system issues
368 macro_rules! make_stmts_default {
370 $me.make_expr().map(|e| {
371 smallvec![ast::Stmt {
372 id: ast::DUMMY_NODE_ID,
374 kind: ast::StmtKind::Expr(e),
380 /// The result of a macro expansion. The return values of the various
381 /// methods are spliced into the AST at the callsite of the macro.
382 pub trait MacResult {
383 /// Creates an expression.
384 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
387 /// Creates zero or more items.
388 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
392 /// Creates zero or more impl items.
393 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
397 /// Creates zero or more trait items.
398 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
402 /// Creates zero or more items in an `extern {}` block
403 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
407 /// Creates a pattern.
408 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
412 /// Creates zero or more statements.
414 /// By default this attempts to create an expression statement,
415 /// returning None if that fails.
416 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
417 make_stmts_default!(self)
420 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
424 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
428 fn make_fields(self: Box<Self>) -> Option<SmallVec<[ast::Field; 1]>> {
432 fn make_field_patterns(self: Box<Self>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
436 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
440 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
444 fn make_struct_fields(self: Box<Self>) -> Option<SmallVec<[ast::StructField; 1]>> {
448 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
453 macro_rules! make_MacEager {
454 ( $( $fld:ident: $t:ty, )* ) => {
455 /// `MacResult` implementation for the common case where you've already
456 /// built each form of AST that you might return.
458 pub struct MacEager {
460 pub $fld: Option<$t>,
466 pub fn $fld(v: $t) -> Box<dyn MacResult> {
480 items: SmallVec<[P<ast::Item>; 1]>,
481 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
482 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
483 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
484 stmts: SmallVec<[ast::Stmt; 1]>,
488 impl MacResult for MacEager {
489 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
493 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
497 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
501 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
505 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
509 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
510 match self.stmts.as_ref().map_or(0, |s| s.len()) {
511 0 => make_stmts_default!(self),
516 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
517 if let Some(p) = self.pat {
520 if let Some(e) = self.expr {
521 if let ast::ExprKind::Lit(_) = e.kind {
522 return Some(P(ast::Pat {
523 id: ast::DUMMY_NODE_ID,
525 kind: PatKind::Lit(e),
533 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
538 /// Fill-in macro expansion result, to allow compilation to continue
539 /// after hitting errors.
540 #[derive(Copy, Clone)]
541 pub struct DummyResult {
547 /// Creates a default MacResult that can be anything.
549 /// Use this as a return value after hitting any errors and
550 /// calling `span_err`.
551 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
552 Box::new(DummyResult { is_error: true, span })
555 /// Same as `any`, but must be a valid fragment, not error.
556 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
557 Box::new(DummyResult { is_error: false, span })
560 /// A plain dummy expression.
561 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
563 id: ast::DUMMY_NODE_ID,
564 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
566 attrs: ast::AttrVec::new(),
571 /// A plain dummy pattern.
572 pub fn raw_pat(sp: Span) -> ast::Pat {
573 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
576 /// A plain dummy type.
577 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
579 id: ast::DUMMY_NODE_ID,
580 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
587 impl MacResult for DummyResult {
588 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
589 Some(DummyResult::raw_expr(self.span, self.is_error))
592 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
593 Some(P(DummyResult::raw_pat(self.span)))
596 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
597 Some(SmallVec::new())
600 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
601 Some(SmallVec::new())
604 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
605 Some(SmallVec::new())
608 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
609 Some(SmallVec::new())
612 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
613 Some(smallvec![ast::Stmt {
614 id: ast::DUMMY_NODE_ID,
615 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
620 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
621 Some(DummyResult::raw_ty(self.span, self.is_error))
624 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
625 Some(SmallVec::new())
628 fn make_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::Field; 1]>> {
629 Some(SmallVec::new())
632 fn make_field_patterns(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
633 Some(SmallVec::new())
636 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
637 Some(SmallVec::new())
640 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
641 Some(SmallVec::new())
644 fn make_struct_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::StructField; 1]>> {
645 Some(SmallVec::new())
648 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
649 Some(SmallVec::new())
653 /// A syntax extension kind.
654 pub enum SyntaxExtensionKind {
655 /// A token-based function-like macro.
657 /// An expander with signature TokenStream -> TokenStream.
658 Box<dyn ProcMacro + sync::Sync + sync::Send>,
661 /// An AST-based function-like macro.
663 /// An expander with signature TokenStream -> AST.
664 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
667 /// A token-based attribute macro.
669 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
670 /// The first TokenSteam is the attribute itself, the second is the annotated item.
671 /// The produced TokenSteam replaces the input TokenSteam.
672 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
675 /// An AST-based attribute macro.
677 /// An expander with signature (AST, AST) -> AST.
678 /// The first AST fragment is the attribute itself, the second is the annotated item.
679 /// The produced AST fragment replaces the input AST fragment.
680 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
683 /// A trivial attribute "macro" that does nothing,
684 /// only keeps the attribute and marks it as inert,
685 /// thus making it ineligible for further expansion.
687 /// Suppresses the `unused_attributes` lint for this attribute.
691 /// A token-based derive macro.
693 /// An expander with signature TokenStream -> TokenStream (not yet).
694 /// The produced TokenSteam is appended to the input TokenSteam.
695 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
698 /// An AST-based derive macro.
700 /// An expander with signature AST -> AST.
701 /// The produced AST fragment is appended to the input AST fragment.
702 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
706 /// A struct representing a macro definition in "lowered" form ready for expansion.
707 pub struct SyntaxExtension {
708 /// A syntax extension kind.
709 pub kind: SyntaxExtensionKind,
710 /// Span of the macro definition.
712 /// List of unstable features that are treated as stable inside this macro.
713 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
714 /// Suppresses the `unsafe_code` lint for code produced by this macro.
715 pub allow_internal_unsafe: bool,
716 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
717 pub local_inner_macros: bool,
718 /// The macro's stability info.
719 pub stability: Option<Stability>,
720 /// The macro's deprecation info.
721 pub deprecation: Option<Deprecation>,
722 /// Names of helper attributes registered by this macro.
723 pub helper_attrs: Vec<Symbol>,
724 /// Edition of the crate in which this macro is defined.
725 pub edition: Edition,
726 /// Built-in macros have a couple of special properties like availability
727 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
728 pub is_builtin: bool,
729 /// We have to identify macros providing a `Copy` impl early for compatibility reasons.
730 pub is_derive_copy: bool,
733 impl SyntaxExtension {
734 /// Returns which kind of macro calls this syntax extension.
735 pub fn macro_kind(&self) -> MacroKind {
737 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
738 SyntaxExtensionKind::Attr(..)
739 | SyntaxExtensionKind::LegacyAttr(..)
740 | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
741 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
747 /// Constructs a syntax extension with default properties.
748 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
751 allow_internal_unstable: None,
752 allow_internal_unsafe: false,
753 local_inner_macros: false,
756 helper_attrs: Vec::new(),
759 is_derive_copy: false,
764 /// Constructs a syntax extension with the given properties
765 /// and other properties converted from attributes.
768 kind: SyntaxExtensionKind,
770 helper_attrs: Vec<Symbol>,
773 attrs: &[ast::Attribute],
774 ) -> SyntaxExtension {
775 let allow_internal_unstable = attr::allow_internal_unstable(sess, &attrs)
776 .map(|features| features.collect::<Vec<Symbol>>().into());
778 let mut local_inner_macros = false;
779 if let Some(macro_export) = sess.find_by_name(attrs, sym::macro_export) {
780 if let Some(l) = macro_export.meta_item_list() {
781 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
785 let is_builtin = sess.contains_name(attrs, sym::rustc_builtin_macro);
786 let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
787 if const_stability.is_some() {
790 .span_err(span, "macros cannot have const stability attributes");
796 allow_internal_unstable,
797 allow_internal_unsafe: sess.contains_name(attrs, sym::allow_internal_unsafe),
800 deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
804 is_derive_copy: is_builtin && name == sym::Copy,
808 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
810 _: &'cx mut ExtCtxt<'_>,
813 ) -> Box<dyn MacResult + 'cx> {
814 DummyResult::any(span)
816 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
819 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
825 ) -> Vec<Annotatable> {
828 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
831 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
832 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
840 macro_def_id: Option<DefId>,
843 kind: ExpnKind::Macro(self.macro_kind(), descr),
847 allow_internal_unstable: self.allow_internal_unstable.clone(),
848 allow_internal_unsafe: self.allow_internal_unsafe,
849 local_inner_macros: self.local_inner_macros,
850 edition: self.edition,
858 /// Result of resolving a macro invocation.
859 pub enum InvocationRes {
860 Single(Lrc<SyntaxExtension>),
861 DeriveContainer(Vec<Lrc<SyntaxExtension>>),
864 /// Error type that denotes indeterminacy.
865 pub struct Indeterminate;
867 pub trait ResolverExpand {
868 fn next_node_id(&mut self) -> NodeId;
870 fn resolve_dollar_crates(&mut self);
871 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment);
872 fn register_builtin_macro(&mut self, ident: Ident, ext: SyntaxExtension);
874 fn expansion_for_ast_pass(
879 parent_module_id: Option<NodeId>,
882 fn resolve_imports(&mut self);
884 fn resolve_macro_invocation(
887 eager_expansion_root: ExpnId,
889 ) -> Result<InvocationRes, Indeterminate>;
891 fn check_unused_macros(&mut self);
893 /// Some parent node that is close enough to the given macro call.
894 fn lint_node_id(&mut self, expn_id: ExpnId) -> NodeId;
896 // Resolver interfaces for specific built-in macros.
897 /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
898 fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
899 /// Path resolution logic for `#[cfg_accessible(path)]`.
900 fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate>;
904 pub struct ModuleData {
905 pub mod_path: Vec<Ident>,
906 pub directory: PathBuf,
910 pub struct ExpansionData {
913 pub module: Rc<ModuleData>,
914 pub directory_ownership: DirectoryOwnership,
915 pub prior_type_ascription: Option<(Span, bool)>,
918 /// One of these is made during expansion and incrementally updated as we go;
919 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
920 /// -> expn_data` of their expansion context stored into their span.
921 pub struct ExtCtxt<'a> {
922 pub sess: &'a Session,
923 pub ecfg: expand::ExpansionConfig<'a>,
924 pub reduced_recursion_limit: Option<Limit>,
925 pub root_path: PathBuf,
926 pub resolver: &'a mut dyn ResolverExpand,
927 pub current_expansion: ExpansionData,
928 /// Error recovery mode entered when expansion is stuck
929 /// (or during eager expansion, but that's a hack).
930 pub force_mode: bool,
931 pub expansions: FxHashMap<Span, Vec<String>>,
932 /// Called directly after having parsed an external `mod foo;` in expansion.
933 pub(super) extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>,
936 impl<'a> ExtCtxt<'a> {
939 ecfg: expand::ExpansionConfig<'a>,
940 resolver: &'a mut dyn ResolverExpand,
941 extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>,
946 reduced_recursion_limit: None,
949 root_path: PathBuf::new(),
950 current_expansion: ExpansionData {
953 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
954 directory_ownership: DirectoryOwnership::Owned { relative: None },
955 prior_type_ascription: None,
958 expansions: FxHashMap::default(),
962 /// Returns a `Folder` for deeply expanding all macros in an AST node.
963 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
964 expand::MacroExpander::new(self, false)
967 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
968 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
969 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
970 expand::MacroExpander::new(self, true)
972 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
973 rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
975 pub fn source_map(&self) -> &'a SourceMap {
976 self.sess.parse_sess.source_map()
978 pub fn parse_sess(&self) -> &'a ParseSess {
979 &self.sess.parse_sess
981 pub fn call_site(&self) -> Span {
982 self.current_expansion.id.expn_data().call_site
985 /// Equivalent of `Span::def_site` from the proc macro API,
986 /// except that the location is taken from the span passed as an argument.
987 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
988 span.with_def_site_ctxt(self.current_expansion.id)
991 /// Equivalent of `Span::call_site` from the proc macro API,
992 /// except that the location is taken from the span passed as an argument.
993 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
994 span.with_call_site_ctxt(self.current_expansion.id)
997 /// Equivalent of `Span::mixed_site` from the proc macro API,
998 /// except that the location is taken from the span passed as an argument.
999 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1000 span.with_mixed_site_ctxt(self.current_expansion.id)
1003 /// Returns span for the macro which originally caused the current expansion to happen.
1005 /// Stops backtracing at include! boundary.
1006 pub fn expansion_cause(&self) -> Option<Span> {
1007 self.current_expansion.id.expansion_cause()
1010 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
1011 self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1014 /// Emit `msg` attached to `sp`, without immediately stopping
1017 /// Compilation will be stopped in the near future (at the end of
1018 /// the macro expansion phase).
1019 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1020 self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1022 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1023 self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1025 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1026 self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1028 pub fn trace_macros_diag(&mut self) {
1029 for (sp, notes) in self.expansions.iter() {
1030 let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1036 // Fixme: does this result in errors?
1037 self.expansions.clear();
1039 pub fn bug(&self, msg: &str) -> ! {
1040 self.sess.parse_sess.span_diagnostic.bug(msg);
1042 pub fn trace_macros(&self) -> bool {
1045 pub fn set_trace_macros(&mut self, x: bool) {
1046 self.ecfg.trace_mac = x
1048 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1049 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1050 iter::once(Ident::new(kw::DollarCrate, def_site))
1051 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
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: `,`");