1 use crate::expand::{self, AstFragment, Invocation};
3 use rustc_attr::{self as attr, Deprecation, HasAttrs, Stability};
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_data_structures::sync::{self, Lrc};
6 use rustc_errors::{DiagnosticBuilder, DiagnosticId};
7 use rustc_parse::{self, parser, DirectoryOwnership, MACRO_ARGUMENTS};
8 use rustc_session::parse::ParseSess;
9 use rustc_span::edition::Edition;
10 use rustc_span::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind};
11 use rustc_span::source_map::SourceMap;
12 use rustc_span::symbol::{kw, sym, Ident, Symbol};
13 use rustc_span::{FileName, MultiSpan, Span, DUMMY_SP};
14 use smallvec::{smallvec, SmallVec};
15 use syntax::ast::{self, Attribute, Name, NodeId, PatKind};
16 use syntax::mut_visit::{self, MutVisitor};
19 use syntax::tokenstream::{self, TokenStream};
20 use syntax::visit::{AssocCtxt, Visitor};
22 use std::default::Default;
24 use std::path::PathBuf;
27 crate use rustc_span::hygiene::MacroKind;
29 #[derive(Debug, Clone)]
30 pub enum Annotatable {
32 TraitItem(P<ast::AssocItem>),
33 ImplItem(P<ast::AssocItem>),
34 ForeignItem(P<ast::ForeignItem>),
39 FieldPat(ast::FieldPat),
40 GenericParam(ast::GenericParam),
42 StructField(ast::StructField),
43 Variant(ast::Variant),
46 impl HasAttrs for Annotatable {
47 fn attrs(&self) -> &[Attribute] {
49 Annotatable::Item(ref item) => &item.attrs,
50 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
51 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
52 Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
53 Annotatable::Stmt(ref stmt) => stmt.attrs(),
54 Annotatable::Expr(ref expr) => &expr.attrs,
55 Annotatable::Arm(ref arm) => &arm.attrs,
56 Annotatable::Field(ref field) => &field.attrs,
57 Annotatable::FieldPat(ref fp) => &fp.attrs,
58 Annotatable::GenericParam(ref gp) => &gp.attrs,
59 Annotatable::Param(ref p) => &p.attrs,
60 Annotatable::StructField(ref sf) => &sf.attrs,
61 Annotatable::Variant(ref v) => &v.attrs(),
65 fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<Attribute>)) {
67 Annotatable::Item(item) => item.visit_attrs(f),
68 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
69 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
70 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
71 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
72 Annotatable::Expr(expr) => expr.visit_attrs(f),
73 Annotatable::Arm(arm) => arm.visit_attrs(f),
74 Annotatable::Field(field) => field.visit_attrs(f),
75 Annotatable::FieldPat(fp) => fp.visit_attrs(f),
76 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
77 Annotatable::Param(p) => p.visit_attrs(f),
78 Annotatable::StructField(sf) => sf.visit_attrs(f),
79 Annotatable::Variant(v) => v.visit_attrs(f),
85 pub fn span(&self) -> Span {
87 Annotatable::Item(ref item) => item.span,
88 Annotatable::TraitItem(ref trait_item) => trait_item.span,
89 Annotatable::ImplItem(ref impl_item) => impl_item.span,
90 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
91 Annotatable::Stmt(ref stmt) => stmt.span,
92 Annotatable::Expr(ref expr) => expr.span,
93 Annotatable::Arm(ref arm) => arm.span,
94 Annotatable::Field(ref field) => field.span,
95 Annotatable::FieldPat(ref fp) => fp.pat.span,
96 Annotatable::GenericParam(ref gp) => gp.ident.span,
97 Annotatable::Param(ref p) => p.span,
98 Annotatable::StructField(ref sf) => sf.span,
99 Annotatable::Variant(ref v) => v.span,
103 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
105 Annotatable::Item(item) => visitor.visit_item(item),
106 Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
107 Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
108 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
109 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
110 Annotatable::Expr(expr) => visitor.visit_expr(expr),
111 Annotatable::Arm(arm) => visitor.visit_arm(arm),
112 Annotatable::Field(field) => visitor.visit_field(field),
113 Annotatable::FieldPat(fp) => visitor.visit_field_pattern(fp),
114 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
115 Annotatable::Param(p) => visitor.visit_param(p),
116 Annotatable::StructField(sf) => visitor.visit_struct_field(sf),
117 Annotatable::Variant(v) => visitor.visit_variant(v),
121 pub fn expect_item(self) -> P<ast::Item> {
123 Annotatable::Item(i) => i,
124 _ => panic!("expected Item"),
128 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
130 F: FnMut(P<ast::Item>) -> P<ast::Item>,
131 G: FnMut(Annotatable) -> Annotatable,
134 Annotatable::Item(i) => Annotatable::Item(f(i)),
139 pub fn expect_trait_item(self) -> P<ast::AssocItem> {
141 Annotatable::TraitItem(i) => i,
142 _ => panic!("expected Item"),
146 pub fn expect_impl_item(self) -> P<ast::AssocItem> {
148 Annotatable::ImplItem(i) => i,
149 _ => panic!("expected Item"),
153 pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
155 Annotatable::ForeignItem(i) => i,
156 _ => panic!("expected foreign item"),
160 pub fn expect_stmt(self) -> ast::Stmt {
162 Annotatable::Stmt(stmt) => stmt.into_inner(),
163 _ => panic!("expected statement"),
167 pub fn expect_expr(self) -> P<ast::Expr> {
169 Annotatable::Expr(expr) => expr,
170 _ => panic!("expected expression"),
174 pub fn expect_arm(self) -> ast::Arm {
176 Annotatable::Arm(arm) => arm,
177 _ => panic!("expected match arm"),
181 pub fn expect_field(self) -> ast::Field {
183 Annotatable::Field(field) => field,
184 _ => panic!("expected field"),
188 pub fn expect_field_pattern(self) -> ast::FieldPat {
190 Annotatable::FieldPat(fp) => fp,
191 _ => panic!("expected field pattern"),
195 pub fn expect_generic_param(self) -> ast::GenericParam {
197 Annotatable::GenericParam(gp) => gp,
198 _ => panic!("expected generic parameter"),
202 pub fn expect_param(self) -> ast::Param {
204 Annotatable::Param(param) => param,
205 _ => panic!("expected parameter"),
209 pub fn expect_struct_field(self) -> ast::StructField {
211 Annotatable::StructField(sf) => sf,
212 _ => panic!("expected struct field"),
216 pub fn expect_variant(self) -> ast::Variant {
218 Annotatable::Variant(v) => v,
219 _ => panic!("expected variant"),
223 pub fn derive_allowed(&self) -> bool {
225 Annotatable::Item(ref item) => match item.kind {
226 ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..) => {
236 // `meta_item` is the annotation, and `item` is the item being modified.
237 // FIXME Decorators should follow the same pattern too.
238 pub trait MultiItemModifier {
241 ecx: &mut ExtCtxt<'_>,
243 meta_item: &ast::MetaItem,
245 ) -> Vec<Annotatable>;
248 impl<F, T> MultiItemModifier for F
250 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
251 T: Into<Vec<Annotatable>>,
255 ecx: &mut ExtCtxt<'_>,
257 meta_item: &ast::MetaItem,
259 ) -> Vec<Annotatable> {
260 (*self)(ecx, span, meta_item, item).into()
264 impl Into<Vec<Annotatable>> for Annotatable {
265 fn into(self) -> Vec<Annotatable> {
270 pub trait ProcMacro {
271 fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt<'_>, span: Span, ts: TokenStream) -> TokenStream;
274 impl<F> ProcMacro for F
276 F: Fn(TokenStream) -> TokenStream,
278 fn expand<'cx>(&self, _ecx: &'cx mut ExtCtxt<'_>, _span: Span, ts: TokenStream) -> TokenStream {
279 // FIXME setup implicit context in TLS before calling self.
284 pub trait AttrProcMacro {
287 ecx: &'cx mut ExtCtxt<'_>,
289 annotation: TokenStream,
290 annotated: TokenStream,
294 impl<F> AttrProcMacro for F
296 F: Fn(TokenStream, TokenStream) -> TokenStream,
300 _ecx: &'cx mut ExtCtxt<'_>,
302 annotation: TokenStream,
303 annotated: TokenStream,
305 // FIXME setup implicit context in TLS before calling self.
306 (*self)(annotation, annotated)
310 /// Represents a thing that maps token trees to Macro Results
311 pub trait TTMacroExpander {
314 ecx: &'cx mut ExtCtxt<'_>,
317 ) -> Box<dyn MacResult + 'cx>;
320 pub type MacroExpanderFn =
321 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
323 impl<F> TTMacroExpander for F
325 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
329 ecx: &'cx mut ExtCtxt<'_>,
331 mut input: TokenStream,
332 ) -> Box<dyn MacResult + 'cx> {
333 struct AvoidInterpolatedIdents;
335 impl MutVisitor for AvoidInterpolatedIdents {
336 fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
337 if let tokenstream::TokenTree::Token(token) = tt {
338 if let token::Interpolated(nt) = &token.kind {
339 if let token::NtIdent(ident, is_raw) = **nt {
340 *tt = tokenstream::TokenTree::token(
341 token::Ident(ident.name, is_raw),
347 mut_visit::noop_visit_tt(tt, self)
350 fn visit_mac(&mut self, mac: &mut ast::Mac) {
351 mut_visit::noop_visit_mac(mac, self)
354 AvoidInterpolatedIdents.visit_tts(&mut input);
355 (*self)(ecx, span, input)
359 // Use a macro because forwarding to a simple function has type system issues
360 macro_rules! make_stmts_default {
362 $me.make_expr().map(|e| {
363 smallvec![ast::Stmt {
364 id: ast::DUMMY_NODE_ID,
366 kind: ast::StmtKind::Expr(e),
372 /// The result of a macro expansion. The return values of the various
373 /// methods are spliced into the AST at the callsite of the macro.
374 pub trait MacResult {
375 /// Creates an expression.
376 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
379 /// Creates zero or more items.
380 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
384 /// Creates zero or more impl items.
385 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
389 /// Creates zero or more trait items.
390 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
394 /// Creates zero or more items in an `extern {}` block
395 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
399 /// Creates a pattern.
400 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
404 /// Creates zero or more statements.
406 /// By default this attempts to create an expression statement,
407 /// returning None if that fails.
408 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
409 make_stmts_default!(self)
412 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
416 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
420 fn make_fields(self: Box<Self>) -> Option<SmallVec<[ast::Field; 1]>> {
424 fn make_field_patterns(self: Box<Self>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
428 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
432 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
436 fn make_struct_fields(self: Box<Self>) -> Option<SmallVec<[ast::StructField; 1]>> {
440 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
445 macro_rules! make_MacEager {
446 ( $( $fld:ident: $t:ty, )* ) => {
447 /// `MacResult` implementation for the common case where you've already
448 /// built each form of AST that you might return.
450 pub struct MacEager {
452 pub $fld: Option<$t>,
458 pub fn $fld(v: $t) -> Box<dyn MacResult> {
472 items: SmallVec<[P<ast::Item>; 1]>,
473 impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
474 trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
475 foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
476 stmts: SmallVec<[ast::Stmt; 1]>,
480 impl MacResult for MacEager {
481 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
485 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
489 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
493 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
497 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
501 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
502 match self.stmts.as_ref().map_or(0, |s| s.len()) {
503 0 => make_stmts_default!(self),
508 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
509 if let Some(p) = self.pat {
512 if let Some(e) = self.expr {
513 if let ast::ExprKind::Lit(_) = e.kind {
514 return Some(P(ast::Pat {
515 id: ast::DUMMY_NODE_ID,
517 kind: PatKind::Lit(e),
524 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
529 /// Fill-in macro expansion result, to allow compilation to continue
530 /// after hitting errors.
531 #[derive(Copy, Clone)]
532 pub struct DummyResult {
538 /// Creates a default MacResult that can be anything.
540 /// Use this as a return value after hitting any errors and
541 /// calling `span_err`.
542 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
543 Box::new(DummyResult { is_error: true, span })
546 /// Same as `any`, but must be a valid fragment, not error.
547 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
548 Box::new(DummyResult { is_error: false, span })
551 /// A plain dummy expression.
552 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
554 id: ast::DUMMY_NODE_ID,
555 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
557 attrs: ast::AttrVec::new(),
561 /// A plain dummy pattern.
562 pub fn raw_pat(sp: Span) -> ast::Pat {
563 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp }
566 /// A plain dummy type.
567 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
569 id: ast::DUMMY_NODE_ID,
570 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
576 impl MacResult for DummyResult {
577 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
578 Some(DummyResult::raw_expr(self.span, self.is_error))
581 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
582 Some(P(DummyResult::raw_pat(self.span)))
585 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
586 Some(SmallVec::new())
589 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
590 Some(SmallVec::new())
593 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
594 Some(SmallVec::new())
597 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
598 Some(SmallVec::new())
601 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
602 Some(smallvec![ast::Stmt {
603 id: ast::DUMMY_NODE_ID,
604 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
609 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
610 Some(DummyResult::raw_ty(self.span, self.is_error))
613 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
614 Some(SmallVec::new())
617 fn make_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::Field; 1]>> {
618 Some(SmallVec::new())
621 fn make_field_patterns(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
622 Some(SmallVec::new())
625 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
626 Some(SmallVec::new())
629 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
630 Some(SmallVec::new())
633 fn make_struct_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::StructField; 1]>> {
634 Some(SmallVec::new())
637 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
638 Some(SmallVec::new())
642 /// A syntax extension kind.
643 pub enum SyntaxExtensionKind {
644 /// A token-based function-like macro.
646 /// An expander with signature TokenStream -> TokenStream.
647 Box<dyn ProcMacro + sync::Sync + sync::Send>,
650 /// An AST-based function-like macro.
652 /// An expander with signature TokenStream -> AST.
653 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
656 /// A token-based attribute macro.
658 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
659 /// The first TokenSteam is the attribute itself, the second is the annotated item.
660 /// The produced TokenSteam replaces the input TokenSteam.
661 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
664 /// An AST-based attribute macro.
666 /// An expander with signature (AST, AST) -> AST.
667 /// The first AST fragment is the attribute itself, the second is the annotated item.
668 /// The produced AST fragment replaces the input AST fragment.
669 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
672 /// A trivial attribute "macro" that does nothing,
673 /// only keeps the attribute and marks it as inert,
674 /// thus making it ineligible for further expansion.
676 /// Suppresses the `unused_attributes` lint for this attribute.
680 /// A token-based derive macro.
682 /// An expander with signature TokenStream -> TokenStream (not yet).
683 /// The produced TokenSteam is appended to the input TokenSteam.
684 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
687 /// An AST-based derive macro.
689 /// An expander with signature AST -> AST.
690 /// The produced AST fragment is appended to the input AST fragment.
691 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
695 /// A struct representing a macro definition in "lowered" form ready for expansion.
696 pub struct SyntaxExtension {
697 /// A syntax extension kind.
698 pub kind: SyntaxExtensionKind,
699 /// Span of the macro definition.
701 /// Whitelist of unstable features that are treated as stable inside this macro.
702 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
703 /// Suppresses the `unsafe_code` lint for code produced by this macro.
704 pub allow_internal_unsafe: bool,
705 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
706 pub local_inner_macros: bool,
707 /// The macro's stability info.
708 pub stability: Option<Stability>,
709 /// The macro's deprecation info.
710 pub deprecation: Option<Deprecation>,
711 /// Names of helper attributes registered by this macro.
712 pub helper_attrs: Vec<Symbol>,
713 /// Edition of the crate in which this macro is defined.
714 pub edition: Edition,
715 /// Built-in macros have a couple of special properties like availability
716 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
717 pub is_builtin: bool,
718 /// We have to identify macros providing a `Copy` impl early for compatibility reasons.
719 pub is_derive_copy: bool,
722 impl SyntaxExtension {
723 /// Returns which kind of macro calls this syntax extension.
724 pub fn macro_kind(&self) -> MacroKind {
726 SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
727 SyntaxExtensionKind::Attr(..)
728 | SyntaxExtensionKind::LegacyAttr(..)
729 | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
730 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
736 /// Constructs a syntax extension with default properties.
737 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
740 allow_internal_unstable: None,
741 allow_internal_unsafe: false,
742 local_inner_macros: false,
745 helper_attrs: Vec::new(),
748 is_derive_copy: false,
753 /// Constructs a syntax extension with the given properties
754 /// and other properties converted from attributes.
757 kind: SyntaxExtensionKind,
759 helper_attrs: Vec<Symbol>,
762 attrs: &[ast::Attribute],
763 ) -> SyntaxExtension {
764 let allow_internal_unstable = attr::allow_internal_unstable(&attrs, &sess.span_diagnostic)
765 .map(|features| features.collect::<Vec<Symbol>>().into());
767 let mut local_inner_macros = false;
768 if let Some(macro_export) = attr::find_by_name(attrs, sym::macro_export) {
769 if let Some(l) = macro_export.meta_item_list() {
770 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
774 let is_builtin = attr::contains_name(attrs, sym::rustc_builtin_macro);
775 let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
776 if const_stability.is_some() {
777 sess.span_diagnostic.span_err(span, "macros cannot have const stability attributes");
783 allow_internal_unstable,
784 allow_internal_unsafe: attr::contains_name(attrs, sym::allow_internal_unsafe),
787 deprecation: attr::find_deprecation(&sess, attrs, span),
791 is_derive_copy: is_builtin && name == sym::Copy,
795 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
797 _: &'cx mut ExtCtxt<'_>,
800 ) -> Box<dyn MacResult + 'cx> {
801 DummyResult::any(span)
803 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
806 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
812 ) -> Vec<Annotatable> {
815 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
818 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
819 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
822 pub fn expn_data(&self, parent: ExpnId, call_site: Span, descr: Symbol) -> ExpnData {
824 kind: ExpnKind::Macro(self.macro_kind(), descr),
828 allow_internal_unstable: self.allow_internal_unstable.clone(),
829 allow_internal_unsafe: self.allow_internal_unsafe,
830 local_inner_macros: self.local_inner_macros,
831 edition: self.edition,
836 /// Result of resolving a macro invocation.
837 pub enum InvocationRes {
838 Single(Lrc<SyntaxExtension>),
839 DeriveContainer(Vec<Lrc<SyntaxExtension>>),
842 /// Error type that denotes indeterminacy.
843 pub struct Indeterminate;
846 fn next_node_id(&mut self) -> NodeId;
848 fn resolve_dollar_crates(&mut self);
849 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment);
850 fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension);
852 fn expansion_for_ast_pass(
857 parent_module_id: Option<NodeId>,
860 fn resolve_imports(&mut self);
862 fn resolve_macro_invocation(
865 eager_expansion_root: ExpnId,
867 ) -> Result<InvocationRes, Indeterminate>;
869 fn check_unused_macros(&mut self);
871 fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
872 fn add_derive_copy(&mut self, expn_id: ExpnId);
876 pub struct ModuleData {
877 pub mod_path: Vec<ast::Ident>,
878 pub directory: PathBuf,
882 pub struct ExpansionData {
885 pub module: Rc<ModuleData>,
886 pub directory_ownership: DirectoryOwnership,
887 pub prior_type_ascription: Option<(Span, bool)>,
890 /// One of these is made during expansion and incrementally updated as we go;
891 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
892 /// -> expn_data` of their expansion context stored into their span.
893 pub struct ExtCtxt<'a> {
894 pub parse_sess: &'a ParseSess,
895 pub ecfg: expand::ExpansionConfig<'a>,
896 pub root_path: PathBuf,
897 pub resolver: &'a mut dyn Resolver,
898 pub current_expansion: ExpansionData,
899 pub expansions: FxHashMap<Span, Vec<String>>,
902 impl<'a> ExtCtxt<'a> {
904 parse_sess: &'a ParseSess,
905 ecfg: expand::ExpansionConfig<'a>,
906 resolver: &'a mut dyn Resolver,
911 root_path: PathBuf::new(),
913 current_expansion: ExpansionData {
916 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
917 directory_ownership: DirectoryOwnership::Owned { relative: None },
918 prior_type_ascription: None,
920 expansions: FxHashMap::default(),
924 /// Returns a `Folder` for deeply expanding all macros in an AST node.
925 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
926 expand::MacroExpander::new(self, false)
929 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
930 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
931 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
932 expand::MacroExpander::new(self, true)
934 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
935 rustc_parse::stream_to_parser(self.parse_sess, stream, MACRO_ARGUMENTS)
937 pub fn source_map(&self) -> &'a SourceMap {
938 self.parse_sess.source_map()
940 pub fn parse_sess(&self) -> &'a ParseSess {
943 pub fn call_site(&self) -> Span {
944 self.current_expansion.id.expn_data().call_site
947 /// Equivalent of `Span::def_site` from the proc macro API,
948 /// except that the location is taken from the span passed as an argument.
949 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
950 span.with_def_site_ctxt(self.current_expansion.id)
953 /// Equivalent of `Span::call_site` from the proc macro API,
954 /// except that the location is taken from the span passed as an argument.
955 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
956 span.with_call_site_ctxt(self.current_expansion.id)
959 /// Equivalent of `Span::mixed_site` from the proc macro API,
960 /// except that the location is taken from the span passed as an argument.
961 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
962 span.with_mixed_site_ctxt(self.current_expansion.id)
965 /// Returns span for the macro which originally caused the current expansion to happen.
967 /// Stops backtracing at include! boundary.
968 pub fn expansion_cause(&self) -> Option<Span> {
969 self.current_expansion.id.expansion_cause()
972 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
973 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
975 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
976 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
978 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
979 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
982 /// Emit `msg` attached to `sp`, and stop compilation immediately.
984 /// `span_err` should be strongly preferred where-ever possible:
985 /// this should *only* be used when:
987 /// - continuing has a high risk of flow-on errors (e.g., errors in
988 /// declaring a macro would cause all uses of that macro to
989 /// complain about "undefined macro"), or
990 /// - there is literally nothing else that can be done (however,
991 /// in most cases one can construct a dummy expression/item to
992 /// substitute; we never hit resolve/type-checking so the dummy
993 /// value doesn't have to match anything)
994 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
995 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
998 /// Emit `msg` attached to `sp`, without immediately stopping
1001 /// Compilation will be stopped in the near future (at the end of
1002 /// the macro expansion phase).
1003 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1004 self.parse_sess.span_diagnostic.span_err(sp, msg);
1006 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
1007 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
1009 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1010 self.parse_sess.span_diagnostic.span_warn(sp, msg);
1012 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1013 self.parse_sess.span_diagnostic.span_bug(sp, msg);
1015 pub fn trace_macros_diag(&mut self) {
1016 for (sp, notes) in self.expansions.iter() {
1017 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1023 // Fixme: does this result in errors?
1024 self.expansions.clear();
1026 pub fn bug(&self, msg: &str) -> ! {
1027 self.parse_sess.span_diagnostic.bug(msg);
1029 pub fn trace_macros(&self) -> bool {
1032 pub fn set_trace_macros(&mut self, x: bool) {
1033 self.ecfg.trace_mac = x
1035 pub fn ident_of(&self, st: &str, sp: Span) -> ast::Ident {
1036 ast::Ident::from_str_and_span(st, sp)
1038 pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
1039 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1040 iter::once(Ident::new(kw::DollarCrate, def_site))
1041 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1044 pub fn name_of(&self, st: &str) -> ast::Name {
1048 pub fn check_unused_macros(&mut self) {
1049 self.resolver.check_unused_macros();
1052 /// Resolves a path mentioned inside Rust code.
1054 /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
1056 /// Returns an absolute path to the file that `path` refers to.
1057 pub fn resolve_path(
1059 path: impl Into<PathBuf>,
1061 ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1062 let path = path.into();
1064 // Relative paths are resolved relative to the file in which they are found
1065 // after macro expansion (that is, they are unhygienic).
1066 if !path.is_absolute() {
1067 let callsite = span.source_callsite();
1068 let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1069 FileName::Real(path) => path,
1070 FileName::DocTest(path, _) => path,
1072 return Err(self.struct_span_err(
1074 &format!("cannot resolve relative path in non-file source `{}`", other),
1087 /// Extracts a string literal from the macro expanded version of `expr`,
1088 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1089 /// compilation on error, merely emits a non-fatal error and returns `None`.
1090 pub fn expr_to_spanned_string<'a>(
1091 cx: &'a mut ExtCtxt<'_>,
1094 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1095 // Perform eager expansion on the expression.
1096 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1097 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1099 Err(match expr.kind {
1100 ast::ExprKind::Lit(ref l) => match l.kind {
1101 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1102 ast::LitKind::Err(_) => None,
1103 _ => Some(cx.struct_span_err(l.span, err_msg)),
1105 ast::ExprKind::Err => None,
1106 _ => Some(cx.struct_span_err(expr.span, err_msg)),
1110 pub fn expr_to_string(
1111 cx: &mut ExtCtxt<'_>,
1114 ) -> Option<(Symbol, ast::StrStyle)> {
1115 expr_to_spanned_string(cx, expr, err_msg)
1122 .map(|(symbol, style, _)| (symbol, style))
1125 /// Non-fatally assert that `tts` is empty. Note that this function
1126 /// returns even when `tts` is non-empty, macros that *need* to stop
1127 /// compilation should call
1128 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1129 /// done as rarely as possible).
1130 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1131 if !tts.is_empty() {
1132 cx.span_err(sp, &format!("{} takes no arguments", name));
1136 /// Interpreting `tts` as a comma-separated sequence of expressions,
1137 /// expect exactly one string literal, or emit an error and return `None`.
1138 pub fn get_single_str_from_tts(
1139 cx: &mut ExtCtxt<'_>,
1143 ) -> Option<String> {
1144 let mut p = cx.new_parser_from_tts(tts);
1145 if p.token == token::Eof {
1146 cx.span_err(sp, &format!("{} takes 1 argument", name));
1149 let ret = panictry!(p.parse_expr());
1150 let _ = p.eat(&token::Comma);
1152 if p.token != token::Eof {
1153 cx.span_err(sp, &format!("{} takes 1 argument", name));
1155 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1158 /// Extracts comma-separated expressions from `tts`. If there is a
1159 /// parsing error, emit a non-fatal error and return `None`.
1160 pub fn get_exprs_from_tts(
1161 cx: &mut ExtCtxt<'_>,
1164 ) -> Option<Vec<P<ast::Expr>>> {
1165 let mut p = cx.new_parser_from_tts(tts);
1166 let mut es = Vec::new();
1167 while p.token != token::Eof {
1168 let expr = panictry!(p.parse_expr());
1170 // Perform eager expansion on the expression.
1171 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1172 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1175 if p.eat(&token::Comma) {
1178 if p.token != token::Eof {
1179 cx.span_err(sp, "expected token: `,`");