1 use crate::expand::{self, AstFragment, Invocation};
2 use crate::module::DirectoryOwnership;
4 use rustc_ast::ast::{self, Attribute, NodeId, PatKind};
5 use rustc_ast::mut_visit::{self, MutVisitor};
8 use rustc_ast::tokenstream::{self, TokenStream};
9 use rustc_ast::visit::{AssocCtxt, Visitor};
10 use rustc_attr::{self as attr, Deprecation, HasAttrs, Stability};
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::sync::{self, Lrc};
13 use rustc_errors::{DiagnosticBuilder, ErrorReported};
14 use rustc_parse::{self, nt_to_tokenstream, parser, MACRO_ARGUMENTS};
15 use rustc_session::{parse::ParseSess, Limit};
16 use rustc_span::def_id::{DefId, LOCAL_CRATE};
17 use rustc_span::edition::Edition;
18 use rustc_span::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind};
19 use rustc_span::source_map::SourceMap;
20 use rustc_span::symbol::{kw, sym, Ident, Symbol};
21 use rustc_span::{FileName, MultiSpan, Span, DUMMY_SP};
22 use smallvec::{smallvec, SmallVec};
24 use std::default::Default;
26 use std::path::PathBuf;
29 crate use rustc_span::hygiene::MacroKind;
31 #[derive(Debug, Clone)]
32 pub enum Annotatable {
34 TraitItem(P<ast::AssocItem>),
35 ImplItem(P<ast::AssocItem>),
36 ForeignItem(P<ast::ForeignItem>),
41 FieldPat(ast::FieldPat),
42 GenericParam(ast::GenericParam),
44 StructField(ast::StructField),
45 Variant(ast::Variant),
48 impl HasAttrs for Annotatable {
49 fn attrs(&self) -> &[Attribute] {
51 Annotatable::Item(ref item) => &item.attrs,
52 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
53 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
54 Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
55 Annotatable::Stmt(ref stmt) => stmt.attrs(),
56 Annotatable::Expr(ref expr) => &expr.attrs,
57 Annotatable::Arm(ref arm) => &arm.attrs,
58 Annotatable::Field(ref field) => &field.attrs,
59 Annotatable::FieldPat(ref fp) => &fp.attrs,
60 Annotatable::GenericParam(ref gp) => &gp.attrs,
61 Annotatable::Param(ref p) => &p.attrs,
62 Annotatable::StructField(ref sf) => &sf.attrs,
63 Annotatable::Variant(ref v) => &v.attrs(),
67 fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
69 Annotatable::Item(item) => item.visit_attrs(f),
70 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
71 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
72 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
73 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
74 Annotatable::Expr(expr) => expr.visit_attrs(f),
75 Annotatable::Arm(arm) => arm.visit_attrs(f),
76 Annotatable::Field(field) => field.visit_attrs(f),
77 Annotatable::FieldPat(fp) => fp.visit_attrs(f),
78 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
79 Annotatable::Param(p) => p.visit_attrs(f),
80 Annotatable::StructField(sf) => sf.visit_attrs(f),
81 Annotatable::Variant(v) => v.visit_attrs(f),
87 pub fn span(&self) -> Span {
89 Annotatable::Item(ref item) => item.span,
90 Annotatable::TraitItem(ref trait_item) => trait_item.span,
91 Annotatable::ImplItem(ref impl_item) => impl_item.span,
92 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
93 Annotatable::Stmt(ref stmt) => stmt.span,
94 Annotatable::Expr(ref expr) => expr.span,
95 Annotatable::Arm(ref arm) => arm.span,
96 Annotatable::Field(ref field) => field.span,
97 Annotatable::FieldPat(ref fp) => fp.pat.span,
98 Annotatable::GenericParam(ref gp) => gp.ident.span,
99 Annotatable::Param(ref p) => p.span,
100 Annotatable::StructField(ref sf) => sf.span,
101 Annotatable::Variant(ref v) => v.span,
105 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
107 Annotatable::Item(item) => visitor.visit_item(item),
108 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
109 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
110 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
111 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
112 Annotatable::Expr(expr) => visitor.visit_expr(expr),
113 Annotatable::Arm(arm) => visitor.visit_arm(arm),
114 Annotatable::Field(field) => visitor.visit_field(field),
115 Annotatable::FieldPat(fp) => visitor.visit_field_pattern(fp),
116 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
117 Annotatable::Param(p) => visitor.visit_param(p),
118 Annotatable::StructField(sf) => visitor.visit_struct_field(sf),
119 Annotatable::Variant(v) => visitor.visit_variant(v),
123 crate fn into_tokens(self, sess: &ParseSess) -> TokenStream {
124 let nt = match self {
125 Annotatable::Item(item) => token::NtItem(item),
126 Annotatable::TraitItem(item) | Annotatable::ImplItem(item) => {
127 token::NtItem(P(item.and_then(ast::AssocItem::into_item)))
129 Annotatable::ForeignItem(item) => {
130 token::NtItem(P(item.and_then(ast::ForeignItem::into_item)))
132 Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
133 Annotatable::Expr(expr) => token::NtExpr(expr),
135 | Annotatable::Field(..)
136 | Annotatable::FieldPat(..)
137 | Annotatable::GenericParam(..)
138 | Annotatable::Param(..)
139 | Annotatable::StructField(..)
140 | Annotatable::Variant(..) => panic!("unexpected annotatable"),
142 nt_to_tokenstream(&nt, sess, DUMMY_SP)
145 pub fn expect_item(self) -> P<ast::Item> {
147 Annotatable::Item(i) => i,
148 _ => panic!("expected Item"),
152 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
154 F: FnMut(P<ast::Item>) -> P<ast::Item>,
155 G: FnMut(Annotatable) -> Annotatable,
158 Annotatable::Item(i) => Annotatable::Item(f(i)),
163 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
165 Annotatable::TraitItem(i) => i,
166 _ => panic!("expected Item"),
170 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
172 Annotatable::ImplItem(i) => i,
173 _ => panic!("expected Item"),
177 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
179 Annotatable::ForeignItem(i) => i,
180 _ => panic!("expected foreign item"),
184 pub fn expect_stmt(self) -> ast::Stmt {
186 Annotatable::Stmt(stmt) => stmt.into_inner(),
187 _ => panic!("expected statement"),
191 pub fn expect_expr(self) -> P<ast::Expr> {
193 Annotatable::Expr(expr) => expr,
194 _ => panic!("expected expression"),
198 pub fn expect_arm(self) -> ast::Arm {
200 Annotatable::Arm(arm) => arm,
201 _ => panic!("expected match arm"),
205 pub fn expect_field(self) -> ast::Field {
207 Annotatable::Field(field) => field,
208 _ => panic!("expected field"),
212 pub fn expect_field_pattern(self) -> ast::FieldPat {
214 Annotatable::FieldPat(fp) => fp,
215 _ => panic!("expected field pattern"),
219 pub fn expect_generic_param(self) -> ast::GenericParam {
221 Annotatable::GenericParam(gp) => gp,
222 _ => panic!("expected generic parameter"),
226 pub fn expect_param(self) -> ast::Param {
228 Annotatable::Param(param) => param,
229 _ => panic!("expected parameter"),
233 pub fn expect_struct_field(self) -> ast::StructField {
235 Annotatable::StructField(sf) => sf,
236 _ => panic!("expected struct field"),
240 pub fn expect_variant(self) -> ast::Variant {
242 Annotatable::Variant(v) => v,
243 _ => panic!("expected variant"),
247 pub fn derive_allowed(&self) -> bool {
249 Annotatable::Item(ref item) => match item.kind {
250 ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..) => {
260 /// Result of an expansion that may need to be retried.
261 /// Consider using this for non-`MultiItemModifier` expanders as well.
262 pub enum ExpandResult<T, U> {
263 /// Expansion produced a result (possibly dummy).
265 /// Expansion could not produce a result and needs to be retried.
266 /// The string is an explanation that will be printed if we are stuck in an infinite retry loop.
270 // `meta_item` is the attribute, and `item` is the item being modified.
271 pub trait MultiItemModifier {
274 ecx: &mut ExtCtxt<'_>,
276 meta_item: &ast::MetaItem,
278 ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
281 impl<F> MultiItemModifier for F
283 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
287 ecx: &mut ExtCtxt<'_>,
289 meta_item: &ast::MetaItem,
291 ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
292 ExpandResult::Ready(self(ecx, span, meta_item, item))
296 pub trait ProcMacro {
299 ecx: &'cx mut ExtCtxt<'_>,
302 ) -> Result<TokenStream, ErrorReported>;
305 impl<F> ProcMacro for F
307 F: Fn(TokenStream) -> TokenStream,
311 _ecx: &'cx mut ExtCtxt<'_>,
314 ) -> Result<TokenStream, ErrorReported> {
315 // FIXME setup implicit context in TLS before calling self.
320 pub trait AttrProcMacro {
323 ecx: &'cx mut ExtCtxt<'_>,
325 annotation: TokenStream,
326 annotated: TokenStream,
327 ) -> Result<TokenStream, ErrorReported>;
330 impl<F> AttrProcMacro for F
332 F: Fn(TokenStream, TokenStream) -> TokenStream,
336 _ecx: &'cx mut ExtCtxt<'_>,
338 annotation: TokenStream,
339 annotated: TokenStream,
340 ) -> Result<TokenStream, ErrorReported> {
341 // FIXME setup implicit context in TLS before calling self.
342 Ok((*self)(annotation, annotated))
346 /// Represents a thing that maps token trees to Macro Results
347 pub trait TTMacroExpander {
350 ecx: &'cx mut ExtCtxt<'_>,
353 ) -> Box<dyn MacResult + 'cx>;
356 pub type MacroExpanderFn =
357 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
359 impl<F> TTMacroExpander for F
361 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
365 ecx: &'cx mut ExtCtxt<'_>,
367 mut input: TokenStream,
368 ) -> Box<dyn MacResult + 'cx> {
369 struct AvoidInterpolatedIdents;
371 impl MutVisitor for AvoidInterpolatedIdents {
372 fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
373 if let tokenstream::TokenTree::Token(token) = tt {
374 if let token::Interpolated(nt) = &token.kind {
375 if let token::NtIdent(ident, is_raw) = **nt {
376 *tt = tokenstream::TokenTree::token(
377 token::Ident(ident.name, is_raw),
383 mut_visit::noop_visit_tt(tt, self)
386 fn visit_mac(&mut self, mac: &mut ast::MacCall) {
387 mut_visit::noop_visit_mac(mac, self)
390 AvoidInterpolatedIdents.visit_tts(&mut input);
391 (*self)(ecx, span, input)
395 // Use a macro because forwarding to a simple function has type system issues
396 macro_rules! make_stmts_default {
398 $me.make_expr().map(|e| {
399 smallvec![ast::Stmt {
400 id: ast::DUMMY_NODE_ID,
402 kind: ast::StmtKind::Expr(e),
408 /// The result of a macro expansion. The return values of the various
409 /// methods are spliced into the AST at the callsite of the macro.
410 pub trait MacResult {
411 /// Creates an expression.
412 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
415 /// Creates zero or more items.
416 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
420 /// Creates zero or more impl items.
421 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
425 /// Creates zero or more trait items.
426 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
430 /// Creates zero or more items in an `extern {}` block
431 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
435 /// Creates a pattern.
436 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
440 /// Creates zero or more statements.
442 /// By default this attempts to create an expression statement,
443 /// returning None if that fails.
444 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
445 make_stmts_default!(self)
448 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
452 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
456 fn make_fields(self: Box<Self>) -> Option<SmallVec<[ast::Field; 1]>> {
460 fn make_field_patterns(self: Box<Self>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
464 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
468 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
472 fn make_struct_fields(self: Box<Self>) -> Option<SmallVec<[ast::StructField; 1]>> {
476 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
481 macro_rules! make_MacEager {
482 ( $( $fld:ident: $t:ty, )* ) => {
483 /// `MacResult` implementation for the common case where you've already
484 /// built each form of AST that you might return.
486 pub struct MacEager {
488 pub $fld: Option<$t>,
494 pub fn $fld(v: $t) -> Box<dyn MacResult> {
508 items: SmallVec<[P<ast::Item>; 1]>,
509 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
510 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
511 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
512 stmts: SmallVec<[ast::Stmt; 1]>,
516 impl MacResult for MacEager {
517 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
521 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
525 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
529 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
533 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
537 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
538 match self.stmts.as_ref().map_or(0, |s| s.len()) {
539 0 => make_stmts_default!(self),
544 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
545 if let Some(p) = self.pat {
548 if let Some(e) = self.expr {
549 if let ast::ExprKind::Lit(_) = e.kind {
550 return Some(P(ast::Pat {
551 id: ast::DUMMY_NODE_ID,
553 kind: PatKind::Lit(e),
560 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
565 /// Fill-in macro expansion result, to allow compilation to continue
566 /// after hitting errors.
567 #[derive(Copy, Clone)]
568 pub struct DummyResult {
574 /// Creates a default MacResult that can be anything.
576 /// Use this as a return value after hitting any errors and
577 /// calling `span_err`.
578 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
579 Box::new(DummyResult { is_error: true, span })
582 /// Same as `any`, but must be a valid fragment, not error.
583 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
584 Box::new(DummyResult { is_error: false, span })
587 /// A plain dummy expression.
588 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
590 id: ast::DUMMY_NODE_ID,
591 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
593 attrs: ast::AttrVec::new(),
598 /// A plain dummy pattern.
599 pub fn raw_pat(sp: Span) -> ast::Pat {
600 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp }
603 /// A plain dummy type.
604 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
606 id: ast::DUMMY_NODE_ID,
607 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
613 impl MacResult for DummyResult {
614 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
615 Some(DummyResult::raw_expr(self.span, self.is_error))
618 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
619 Some(P(DummyResult::raw_pat(self.span)))
622 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
623 Some(SmallVec::new())
626 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
627 Some(SmallVec::new())
630 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
631 Some(SmallVec::new())
634 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
635 Some(SmallVec::new())
638 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
639 Some(smallvec![ast::Stmt {
640 id: ast::DUMMY_NODE_ID,
641 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
646 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
647 Some(DummyResult::raw_ty(self.span, self.is_error))
650 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
651 Some(SmallVec::new())
654 fn make_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::Field; 1]>> {
655 Some(SmallVec::new())
658 fn make_field_patterns(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
659 Some(SmallVec::new())
662 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
663 Some(SmallVec::new())
666 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
667 Some(SmallVec::new())
670 fn make_struct_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::StructField; 1]>> {
671 Some(SmallVec::new())
674 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
675 Some(SmallVec::new())
679 /// A syntax extension kind.
680 pub enum SyntaxExtensionKind {
681 /// A token-based function-like macro.
683 /// An expander with signature TokenStream -> TokenStream.
684 Box<dyn ProcMacro + sync::Sync + sync::Send>,
687 /// An AST-based function-like macro.
689 /// An expander with signature TokenStream -> AST.
690 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
693 /// A token-based attribute macro.
695 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
696 /// The first TokenSteam is the attribute itself, the second is the annotated item.
697 /// The produced TokenSteam replaces the input TokenSteam.
698 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
701 /// An AST-based attribute macro.
703 /// An expander with signature (AST, AST) -> AST.
704 /// The first AST fragment is the attribute itself, the second is the annotated item.
705 /// The produced AST fragment replaces the input AST fragment.
706 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
709 /// A trivial attribute "macro" that does nothing,
710 /// only keeps the attribute and marks it as inert,
711 /// thus making it ineligible for further expansion.
713 /// Suppresses the `unused_attributes` lint for this attribute.
717 /// A token-based derive macro.
719 /// An expander with signature TokenStream -> TokenStream (not yet).
720 /// The produced TokenSteam is appended to the input TokenSteam.
721 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
724 /// An AST-based derive macro.
726 /// An expander with signature AST -> AST.
727 /// The produced AST fragment is appended to the input AST fragment.
728 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
732 /// A struct representing a macro definition in "lowered" form ready for expansion.
733 pub struct SyntaxExtension {
734 /// A syntax extension kind.
735 pub kind: SyntaxExtensionKind,
736 /// Span of the macro definition.
738 /// List of unstable features that are treated as stable inside this macro.
739 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
740 /// Suppresses the `unsafe_code` lint for code produced by this macro.
741 pub allow_internal_unsafe: bool,
742 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
743 pub local_inner_macros: bool,
744 /// The macro's stability info.
745 pub stability: Option<Stability>,
746 /// The macro's deprecation info.
747 pub deprecation: Option<Deprecation>,
748 /// Names of helper attributes registered by this macro.
749 pub helper_attrs: Vec<Symbol>,
750 /// Edition of the crate in which this macro is defined.
751 pub edition: Edition,
752 /// Built-in macros have a couple of special properties like availability
753 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
754 pub is_builtin: bool,
755 /// We have to identify macros providing a `Copy` impl early for compatibility reasons.
756 pub is_derive_copy: bool,
759 impl SyntaxExtension {
760 /// Returns which kind of macro calls this syntax extension.
761 pub fn macro_kind(&self) -> MacroKind {
763 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
764 SyntaxExtensionKind::Attr(..)
765 | SyntaxExtensionKind::LegacyAttr(..)
766 | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
767 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
773 /// Constructs a syntax extension with default properties.
774 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
777 allow_internal_unstable: None,
778 allow_internal_unsafe: false,
779 local_inner_macros: false,
782 helper_attrs: Vec::new(),
785 is_derive_copy: false,
790 /// Constructs a syntax extension with the given properties
791 /// and other properties converted from attributes.
794 kind: SyntaxExtensionKind,
796 helper_attrs: Vec<Symbol>,
799 attrs: &[ast::Attribute],
800 ) -> SyntaxExtension {
801 let allow_internal_unstable = attr::allow_internal_unstable(&attrs, &sess.span_diagnostic)
802 .map(|features| features.collect::<Vec<Symbol>>().into());
804 let mut local_inner_macros = false;
805 if let Some(macro_export) = attr::find_by_name(attrs, sym::macro_export) {
806 if let Some(l) = macro_export.meta_item_list() {
807 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
811 let is_builtin = attr::contains_name(attrs, sym::rustc_builtin_macro);
812 let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
813 if const_stability.is_some() {
814 sess.span_diagnostic.span_err(span, "macros cannot have const stability attributes");
820 allow_internal_unstable,
821 allow_internal_unsafe: attr::contains_name(attrs, sym::allow_internal_unsafe),
824 deprecation: attr::find_deprecation(&sess, attrs, span),
828 is_derive_copy: is_builtin && name == sym::Copy,
832 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
834 _: &'cx mut ExtCtxt<'_>,
837 ) -> Box<dyn MacResult + 'cx> {
838 DummyResult::any(span)
840 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
843 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
849 ) -> Vec<Annotatable> {
852 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
855 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
856 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
864 macro_def_id: Option<DefId>,
867 kind: ExpnKind::Macro(self.macro_kind(), descr),
871 allow_internal_unstable: self.allow_internal_unstable.clone(),
872 allow_internal_unsafe: self.allow_internal_unsafe,
873 local_inner_macros: self.local_inner_macros,
874 edition: self.edition,
882 /// Result of resolving a macro invocation.
883 pub enum InvocationRes {
884 Single(Lrc<SyntaxExtension>),
885 DeriveContainer(Vec<Lrc<SyntaxExtension>>),
888 /// Error type that denotes indeterminacy.
889 pub struct Indeterminate;
891 pub trait ResolverExpand {
892 fn next_node_id(&mut self) -> NodeId;
894 fn resolve_dollar_crates(&mut self);
895 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment);
896 fn register_builtin_macro(&mut self, ident: Ident, ext: SyntaxExtension);
898 fn expansion_for_ast_pass(
903 parent_module_id: Option<NodeId>,
906 fn resolve_imports(&mut self);
908 fn resolve_macro_invocation(
911 eager_expansion_root: ExpnId,
913 ) -> Result<InvocationRes, Indeterminate>;
915 fn check_unused_macros(&mut self);
917 /// Some parent node that is close enough to the given macro call.
918 fn lint_node_id(&mut self, expn_id: ExpnId) -> NodeId;
920 fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
921 fn add_derive_copy(&mut self, expn_id: ExpnId);
922 fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate>;
926 pub struct ModuleData {
927 pub mod_path: Vec<Ident>,
928 pub directory: PathBuf,
932 pub struct ExpansionData {
935 pub module: Rc<ModuleData>,
936 pub directory_ownership: DirectoryOwnership,
937 pub prior_type_ascription: Option<(Span, bool)>,
940 /// One of these is made during expansion and incrementally updated as we go;
941 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
942 /// -> expn_data` of their expansion context stored into their span.
943 pub struct ExtCtxt<'a> {
944 pub parse_sess: &'a ParseSess,
945 pub ecfg: expand::ExpansionConfig<'a>,
946 pub reduced_recursion_limit: Option<Limit>,
947 pub root_path: PathBuf,
948 pub resolver: &'a mut dyn ResolverExpand,
949 pub current_expansion: ExpansionData,
950 pub expansions: FxHashMap<Span, Vec<String>>,
951 /// Called directly after having parsed an external `mod foo;` in expansion.
952 pub(super) extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>,
955 impl<'a> ExtCtxt<'a> {
957 parse_sess: &'a ParseSess,
958 ecfg: expand::ExpansionConfig<'a>,
959 resolver: &'a mut dyn ResolverExpand,
960 extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>,
965 reduced_recursion_limit: None,
968 root_path: PathBuf::new(),
969 current_expansion: ExpansionData {
972 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
973 directory_ownership: DirectoryOwnership::Owned { relative: None },
974 prior_type_ascription: None,
976 expansions: FxHashMap::default(),
980 /// Returns a `Folder` for deeply expanding all macros in an AST node.
981 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
982 expand::MacroExpander::new(self, false)
985 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
986 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
987 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
988 expand::MacroExpander::new(self, true)
990 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
991 rustc_parse::stream_to_parser(self.parse_sess, stream, MACRO_ARGUMENTS)
993 pub fn source_map(&self) -> &'a SourceMap {
994 self.parse_sess.source_map()
996 pub fn parse_sess(&self) -> &'a ParseSess {
999 pub fn call_site(&self) -> Span {
1000 self.current_expansion.id.expn_data().call_site
1003 /// Equivalent of `Span::def_site` from the proc macro API,
1004 /// except that the location is taken from the span passed as an argument.
1005 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1006 span.with_def_site_ctxt(self.current_expansion.id)
1009 /// Equivalent of `Span::call_site` from the proc macro API,
1010 /// except that the location is taken from the span passed as an argument.
1011 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1012 span.with_call_site_ctxt(self.current_expansion.id)
1015 /// Equivalent of `Span::mixed_site` from the proc macro API,
1016 /// except that the location is taken from the span passed as an argument.
1017 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1018 span.with_mixed_site_ctxt(self.current_expansion.id)
1021 /// Returns span for the macro which originally caused the current expansion to happen.
1023 /// Stops backtracing at include! boundary.
1024 pub fn expansion_cause(&self) -> Option<Span> {
1025 self.current_expansion.id.expansion_cause()
1028 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
1029 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1032 /// Emit `msg` attached to `sp`, without immediately stopping
1035 /// Compilation will be stopped in the near future (at the end of
1036 /// the macro expansion phase).
1037 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1038 self.parse_sess.span_diagnostic.span_err(sp, msg);
1040 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1041 self.parse_sess.span_diagnostic.span_warn(sp, msg);
1043 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1044 self.parse_sess.span_diagnostic.span_bug(sp, msg);
1046 pub fn trace_macros_diag(&mut self) {
1047 for (sp, notes) in self.expansions.iter() {
1048 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1054 // Fixme: does this result in errors?
1055 self.expansions.clear();
1057 pub fn bug(&self, msg: &str) -> ! {
1058 self.parse_sess.span_diagnostic.bug(msg);
1060 pub fn trace_macros(&self) -> bool {
1063 pub fn set_trace_macros(&mut self, x: bool) {
1064 self.ecfg.trace_mac = x
1066 pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1067 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1068 iter::once(Ident::new(kw::DollarCrate, def_site))
1069 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1072 pub fn name_of(&self, st: &str) -> Symbol {
1076 pub fn check_unused_macros(&mut self) {
1077 self.resolver.check_unused_macros();
1080 /// Resolves a path mentioned inside Rust code.
1082 /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
1084 /// Returns an absolute path to the file that `path` refers to.
1085 pub fn resolve_path(
1087 path: impl Into<PathBuf>,
1089 ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1090 let path = path.into();
1092 // Relative paths are resolved relative to the file in which they are found
1093 // after macro expansion (that is, they are unhygienic).
1094 if !path.is_absolute() {
1095 let callsite = span.source_callsite();
1096 let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1097 FileName::Real(name) => name.into_local_path(),
1098 FileName::DocTest(path, _) => path,
1100 return Err(self.struct_span_err(
1102 &format!("cannot resolve relative path in non-file source `{}`", other),
1115 /// Extracts a string literal from the macro expanded version of `expr`,
1116 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1117 /// compilation on error, merely emits a non-fatal error and returns `None`.
1118 pub fn expr_to_spanned_string<'a>(
1119 cx: &'a mut ExtCtxt<'_>,
1122 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1123 // Perform eager expansion on the expression.
1124 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1125 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1127 Err(match expr.kind {
1128 ast::ExprKind::Lit(ref l) => match l.kind {
1129 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1130 ast::LitKind::Err(_) => None,
1131 _ => Some(cx.struct_span_err(l.span, err_msg)),
1133 ast::ExprKind::Err => None,
1134 _ => Some(cx.struct_span_err(expr.span, err_msg)),
1138 pub fn expr_to_string(
1139 cx: &mut ExtCtxt<'_>,
1142 ) -> Option<(Symbol, ast::StrStyle)> {
1143 expr_to_spanned_string(cx, expr, err_msg)
1150 .map(|(symbol, style, _)| (symbol, style))
1153 /// Non-fatally assert that `tts` is empty. Note that this function
1154 /// returns even when `tts` is non-empty, macros that *need* to stop
1155 /// compilation should call
1156 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1157 /// done as rarely as possible).
1158 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1159 if !tts.is_empty() {
1160 cx.span_err(sp, &format!("{} takes no arguments", name));
1164 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1165 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1166 match p.parse_expr() {
1167 Ok(e) => return Some(e),
1168 Err(mut err) => err.emit(),
1170 while p.token != token::Eof {
1176 /// Interpreting `tts` as a comma-separated sequence of expressions,
1177 /// expect exactly one string literal, or emit an error and return `None`.
1178 pub fn get_single_str_from_tts(
1179 cx: &mut ExtCtxt<'_>,
1183 ) -> Option<String> {
1184 let mut p = cx.new_parser_from_tts(tts);
1185 if p.token == token::Eof {
1186 cx.span_err(sp, &format!("{} takes 1 argument", name));
1189 let ret = parse_expr(&mut p)?;
1190 let _ = p.eat(&token::Comma);
1192 if p.token != token::Eof {
1193 cx.span_err(sp, &format!("{} takes 1 argument", name));
1195 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1198 /// Extracts comma-separated expressions from `tts`.
1199 /// On error, emit it, and return `None`.
1200 pub fn get_exprs_from_tts(
1201 cx: &mut ExtCtxt<'_>,
1204 ) -> Option<Vec<P<ast::Expr>>> {
1205 let mut p = cx.new_parser_from_tts(tts);
1206 let mut es = Vec::new();
1207 while p.token != token::Eof {
1208 let expr = parse_expr(&mut p)?;
1210 // Perform eager expansion on the expression.
1211 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1212 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1215 if p.eat(&token::Comma) {
1218 if p.token != token::Eof {
1219 cx.span_err(sp, "expected token: `,`");