1 use crate::ast::{self, NodeId, Attribute, Name, PatKind};
2 use crate::attr::{self, HasAttrs, Stability, Deprecation};
3 use crate::source_map::SourceMap;
4 use crate::edition::Edition;
5 use crate::ext::expand::{self, AstFragment, Invocation};
6 use crate::ext::hygiene::ExpnId;
7 use crate::mut_visit::{self, MutVisitor};
8 use crate::parse::{self, parser, ParseSess, DirectoryOwnership};
9 use crate::parse::token;
11 use crate::symbol::{kw, sym, Ident, Symbol};
12 use crate::{ThinVec, MACRO_ARGUMENTS};
13 use crate::tokenstream::{self, TokenStream};
14 use crate::visit::Visitor;
16 use errors::{DiagnosticBuilder, DiagnosticId};
17 use smallvec::{smallvec, SmallVec};
18 use syntax_pos::{FileName, Span, MultiSpan, DUMMY_SP};
19 use syntax_pos::hygiene::{AstPass, ExpnData, ExpnKind};
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_data_structures::sync::{self, Lrc};
24 use std::path::PathBuf;
26 use std::default::Default;
28 pub use syntax_pos::hygiene::MacroKind;
30 #[derive(Debug,Clone)]
31 pub enum Annotatable {
33 TraitItem(P<ast::TraitItem>),
34 ImplItem(P<ast::ImplItem>),
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<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
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(trait_item) => visitor.visit_trait_item(trait_item),
108 Annotatable::ImplItem(impl_item) => visitor.visit_impl_item(impl_item),
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 pub fn expect_item(self) -> P<ast::Item> {
124 Annotatable::Item(i) => i,
125 _ => panic!("expected Item")
129 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
130 where 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) -> ast::TraitItem {
141 Annotatable::TraitItem(i) => i.into_inner(),
142 _ => panic!("expected Item")
146 pub fn expect_impl_item(self) -> ast::ImplItem {
148 Annotatable::ImplItem(i) => i.into_inner(),
149 _ => panic!("expected Item")
153 pub fn expect_foreign_item(self) -> ast::ForeignItem {
155 Annotatable::ForeignItem(i) => i.into_inner(),
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.node {
226 ast::ItemKind::Struct(..) |
227 ast::ItemKind::Enum(..) |
228 ast::ItemKind::Union(..) => true,
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 {
240 ecx: &mut ExtCtxt<'_>,
242 meta_item: &ast::MetaItem,
247 impl<F, T> MultiItemModifier for F
248 where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
249 T: Into<Vec<Annotatable>>,
252 ecx: &mut ExtCtxt<'_>,
254 meta_item: &ast::MetaItem,
256 -> Vec<Annotatable> {
257 (*self)(ecx, span, meta_item, item).into()
261 impl Into<Vec<Annotatable>> for Annotatable {
262 fn into(self) -> Vec<Annotatable> {
267 pub trait ProcMacro {
268 fn expand<'cx>(&self,
269 ecx: &'cx mut ExtCtxt<'_>,
275 impl<F> ProcMacro for F
276 where F: Fn(TokenStream) -> TokenStream
278 fn expand<'cx>(&self,
279 _ecx: &'cx mut ExtCtxt<'_>,
283 // FIXME setup implicit context in TLS before calling self.
288 pub trait AttrProcMacro {
289 fn expand<'cx>(&self,
290 ecx: &'cx mut ExtCtxt<'_>,
292 annotation: TokenStream,
293 annotated: TokenStream)
297 impl<F> AttrProcMacro for F
298 where F: Fn(TokenStream, TokenStream) -> TokenStream
300 fn expand<'cx>(&self,
301 _ecx: &'cx mut ExtCtxt<'_>,
303 annotation: TokenStream,
304 annotated: TokenStream)
306 // FIXME setup implicit context in TLS before calling self.
307 (*self)(annotation, annotated)
311 /// Represents a thing that maps token trees to Macro Results
312 pub trait TTMacroExpander {
315 ecx: &'cx mut ExtCtxt<'_>,
318 ) -> Box<dyn MacResult+'cx>;
321 pub type MacroExpanderFn =
322 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream)
323 -> Box<dyn MacResult+'cx>;
325 impl<F> TTMacroExpander for F
326 where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream)
327 -> Box<dyn MacResult+'cx>
331 ecx: &'cx mut ExtCtxt<'_>,
333 mut input: TokenStream,
334 ) -> Box<dyn MacResult+'cx> {
335 struct AvoidInterpolatedIdents;
337 impl MutVisitor for AvoidInterpolatedIdents {
338 fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
339 if let tokenstream::TokenTree::Token(token) = tt {
340 if let token::Interpolated(nt) = &token.kind {
341 if let token::NtIdent(ident, is_raw) = **nt {
342 *tt = tokenstream::TokenTree::token(
343 token::Ident(ident.name, is_raw), ident.span
348 mut_visit::noop_visit_tt(tt, self)
351 fn visit_mac(&mut self, mac: &mut ast::Mac) {
352 mut_visit::noop_visit_mac(mac, self)
355 AvoidInterpolatedIdents.visit_tts(&mut input);
356 (*self)(ecx, span, input)
360 // Use a macro because forwarding to a simple function has type system issues
361 macro_rules! make_stmts_default {
363 $me.make_expr().map(|e| smallvec![ast::Stmt {
364 id: ast::DUMMY_NODE_ID,
366 node: ast::StmtKind::Expr(e),
371 /// The result of a macro expansion. The return values of the various
372 /// methods are spliced into the AST at the callsite of the macro.
373 pub trait MacResult {
374 /// Creates an expression.
375 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
378 /// Creates zero or more items.
379 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
383 /// Creates zero or more impl items.
384 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
388 /// Creates zero or more trait items.
389 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
393 /// Creates zero or more items in an `extern {}` block
394 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None }
396 /// Creates a pattern.
397 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
401 /// Creates zero or more statements.
403 /// By default this attempts to create an expression statement,
404 /// returning None if that fails.
405 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
406 make_stmts_default!(self)
409 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
413 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
417 fn make_fields(self: Box<Self>) -> Option<SmallVec<[ast::Field; 1]>> {
421 fn make_field_patterns(self: Box<Self>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
425 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
429 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
433 fn make_struct_fields(self: Box<Self>) -> Option<SmallVec<[ast::StructField; 1]>> {
437 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
442 macro_rules! make_MacEager {
443 ( $( $fld:ident: $t:ty, )* ) => {
444 /// `MacResult` implementation for the common case where you've already
445 /// built each form of AST that you might return.
447 pub struct MacEager {
449 pub $fld: Option<$t>,
455 pub fn $fld(v: $t) -> Box<dyn MacResult> {
469 items: SmallVec<[P<ast::Item>; 1]>,
470 impl_items: SmallVec<[ast::ImplItem; 1]>,
471 trait_items: SmallVec<[ast::TraitItem; 1]>,
472 foreign_items: SmallVec<[ast::ForeignItem; 1]>,
473 stmts: SmallVec<[ast::Stmt; 1]>,
477 impl MacResult for MacEager {
478 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
482 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
486 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
490 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
494 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
498 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
499 match self.stmts.as_ref().map_or(0, |s| s.len()) {
500 0 => make_stmts_default!(self),
505 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
506 if let Some(p) = self.pat {
509 if let Some(e) = self.expr {
510 if let ast::ExprKind::Lit(_) = e.node {
511 return Some(P(ast::Pat {
512 id: ast::DUMMY_NODE_ID,
514 node: PatKind::Lit(e),
521 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
526 /// Fill-in macro expansion result, to allow compilation to continue
527 /// after hitting errors.
528 #[derive(Copy, Clone)]
529 pub struct DummyResult {
535 /// Creates a default MacResult that can be anything.
537 /// Use this as a return value after hitting any errors and
538 /// calling `span_err`.
539 pub fn any(span: Span) -> Box<dyn MacResult+'static> {
540 Box::new(DummyResult { is_error: true, span })
543 /// Same as `any`, but must be a valid fragment, not error.
544 pub fn any_valid(span: Span) -> Box<dyn MacResult+'static> {
545 Box::new(DummyResult { is_error: false, span })
548 /// A plain dummy expression.
549 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
551 id: ast::DUMMY_NODE_ID,
552 node: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
554 attrs: ThinVec::new(),
558 /// A plain dummy pattern.
559 pub fn raw_pat(sp: Span) -> ast::Pat {
561 id: ast::DUMMY_NODE_ID,
567 /// A plain dummy type.
568 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
570 id: ast::DUMMY_NODE_ID,
571 node: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
577 impl MacResult for DummyResult {
578 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
579 Some(DummyResult::raw_expr(self.span, self.is_error))
582 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
583 Some(P(DummyResult::raw_pat(self.span)))
586 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
587 Some(SmallVec::new())
590 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
591 Some(SmallVec::new())
594 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
595 Some(SmallVec::new())
598 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
599 Some(SmallVec::new())
602 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
603 Some(smallvec![ast::Stmt {
604 id: ast::DUMMY_NODE_ID,
605 node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
610 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
611 Some(DummyResult::raw_ty(self.span, self.is_error))
614 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
615 Some(SmallVec::new())
618 fn make_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::Field; 1]>> {
619 Some(SmallVec::new())
622 fn make_field_patterns(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
623 Some(SmallVec::new())
626 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
627 Some(SmallVec::new())
630 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
631 Some(SmallVec::new())
634 fn make_struct_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::StructField; 1]>> {
635 Some(SmallVec::new())
638 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
639 Some(SmallVec::new())
643 /// A syntax extension kind.
644 pub enum SyntaxExtensionKind {
645 /// A token-based function-like macro.
647 /// An expander with signature TokenStream -> TokenStream.
648 Box<dyn ProcMacro + sync::Sync + sync::Send>,
651 /// An AST-based function-like macro.
653 /// An expander with signature TokenStream -> AST.
654 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
657 /// A token-based attribute macro.
659 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
660 /// The first TokenSteam is the attribute itself, the second is the annotated item.
661 /// The produced TokenSteam replaces the input TokenSteam.
662 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
665 /// An AST-based attribute macro.
667 /// An expander with signature (AST, AST) -> AST.
668 /// The first AST fragment is the attribute itself, the second is the annotated item.
669 /// The produced AST fragment replaces the input AST fragment.
670 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
673 /// A trivial attribute "macro" that does nothing,
674 /// only keeps the attribute and marks it as inert,
675 /// thus making it ineligible for further expansion.
677 /// Suppresses the `unused_attributes` lint for this attribute.
681 /// A token-based derive macro.
683 /// An expander with signature TokenStream -> TokenStream (not yet).
684 /// The produced TokenSteam is appended to the input TokenSteam.
685 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
688 /// An AST-based derive macro.
690 /// An expander with signature AST -> AST.
691 /// The produced AST fragment is appended to the input AST fragment.
692 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
696 /// A struct representing a macro definition in "lowered" form ready for expansion.
697 pub struct SyntaxExtension {
698 /// A syntax extension kind.
699 pub kind: SyntaxExtensionKind,
700 /// Span of the macro definition.
702 /// Whitelist of unstable features that are treated as stable inside this macro.
703 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
704 /// Suppresses the `unsafe_code` lint for code produced by this macro.
705 pub allow_internal_unsafe: bool,
706 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
707 pub local_inner_macros: bool,
708 /// The macro's stability info.
709 pub stability: Option<Stability>,
710 /// The macro's deprecation info.
711 pub deprecation: Option<Deprecation>,
712 /// Names of helper attributes registered by this macro.
713 pub helper_attrs: Vec<Symbol>,
714 /// Edition of the crate in which this macro is defined.
715 pub edition: Edition,
716 /// Built-in macros have a couple of special properties like availability
717 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
718 pub is_builtin: bool,
719 /// We have to identify macros providing a `Copy` impl early for compatibility reasons.
720 pub is_derive_copy: bool,
723 impl SyntaxExtension {
724 /// Returns which kind of macro calls this syntax extension.
725 pub fn macro_kind(&self) -> MacroKind {
727 SyntaxExtensionKind::Bang(..) |
728 SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
729 SyntaxExtensionKind::Attr(..) |
730 SyntaxExtensionKind::LegacyAttr(..) |
731 SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
732 SyntaxExtensionKind::Derive(..) |
733 SyntaxExtensionKind::LegacyDerive(..) => MacroKind::Derive,
737 /// Constructs a syntax extension with default properties.
738 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
741 allow_internal_unstable: None,
742 allow_internal_unsafe: false,
743 local_inner_macros: false,
746 helper_attrs: Vec::new(),
749 is_derive_copy: false,
754 /// Constructs a syntax extension with the given properties
755 /// and other properties converted from attributes.
758 kind: SyntaxExtensionKind,
760 helper_attrs: Vec<Symbol>,
763 attrs: &[ast::Attribute],
764 ) -> SyntaxExtension {
765 let allow_internal_unstable =
766 attr::find_by_name(attrs, sym::allow_internal_unstable).map(|attr| {
767 attr.meta_item_list()
771 let name = it.ident().map(|ident| ident.name);
773 sess.span_diagnostic.span_err(
774 it.span(), "allow internal unstable expects feature names"
779 .collect::<Vec<Symbol>>()
783 sess.span_diagnostic.span_warn(
785 "allow_internal_unstable expects list of feature names. In the future \
786 this will become a hard error. Please use `allow_internal_unstable(\
787 foo, bar)` to only allow the `foo` and `bar` features",
789 vec![sym::allow_internal_unstable_backcompat_hack].into()
793 let mut local_inner_macros = false;
794 if let Some(macro_export) = attr::find_by_name(attrs, sym::macro_export) {
795 if let Some(l) = macro_export.meta_item_list() {
796 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
800 let is_builtin = attr::contains_name(attrs, sym::rustc_builtin_macro);
805 allow_internal_unstable,
806 allow_internal_unsafe: attr::contains_name(attrs, sym::allow_internal_unsafe),
808 stability: attr::find_stability(&sess, attrs, span),
809 deprecation: attr::find_deprecation(&sess, attrs, span),
813 is_derive_copy: is_builtin && name == sym::Copy,
817 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
818 fn expander<'cx>(_: &'cx mut ExtCtxt<'_>, span: Span, _: TokenStream)
819 -> Box<dyn MacResult + 'cx> {
820 DummyResult::any(span)
822 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
825 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
826 fn expander(_: &mut ExtCtxt<'_>, _: Span, _: &ast::MetaItem, _: Annotatable)
827 -> Vec<Annotatable> {
830 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
833 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
834 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
837 pub fn expn_data(&self, parent: ExpnId, call_site: Span, descr: Symbol) -> ExpnData {
839 kind: ExpnKind::Macro(self.macro_kind(), descr),
843 allow_internal_unstable: self.allow_internal_unstable.clone(),
844 allow_internal_unsafe: self.allow_internal_unsafe,
845 local_inner_macros: self.local_inner_macros,
846 edition: self.edition,
851 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
853 /// Result of resolving a macro invocation.
854 pub enum InvocationRes {
855 Single(Lrc<SyntaxExtension>),
856 DeriveContainer(Vec<Lrc<SyntaxExtension>>),
859 /// Error type that denotes indeterminacy.
860 pub struct Indeterminate;
862 bitflags::bitflags! {
863 /// Built-in derives that need some extra tracking beyond the usual macro functionality.
865 pub struct SpecialDerives: u8 {
866 const PARTIAL_EQ = 1 << 0;
873 fn next_node_id(&mut self) -> NodeId;
875 fn resolve_dollar_crates(&mut self);
876 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment,
877 extra_placeholders: &[NodeId]);
878 fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension);
880 fn expansion_for_ast_pass(
885 parent_module_id: Option<NodeId>,
888 fn resolve_imports(&mut self);
890 fn resolve_macro_invocation(
891 &mut self, invoc: &Invocation, eager_expansion_root: ExpnId, force: bool
892 ) -> Result<InvocationRes, Indeterminate>;
894 fn check_unused_macros(&self);
896 fn has_derives(&self, expn_id: ExpnId, derives: SpecialDerives) -> bool;
897 fn add_derives(&mut self, expn_id: ExpnId, derives: SpecialDerives);
901 pub struct ModuleData {
902 pub mod_path: Vec<ast::Ident>,
903 pub directory: PathBuf,
907 pub struct ExpansionData {
910 pub module: Rc<ModuleData>,
911 pub directory_ownership: DirectoryOwnership,
912 pub prior_type_ascription: Option<(Span, bool)>,
915 /// One of these is made during expansion and incrementally updated as we go;
916 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
917 /// -> expn_data` of their expansion context stored into their span.
918 pub struct ExtCtxt<'a> {
919 pub parse_sess: &'a parse::ParseSess,
920 pub ecfg: expand::ExpansionConfig<'a>,
921 pub root_path: PathBuf,
922 pub resolver: &'a mut dyn Resolver,
923 pub current_expansion: ExpansionData,
924 pub expansions: FxHashMap<Span, Vec<String>>,
927 impl<'a> ExtCtxt<'a> {
928 pub fn new(parse_sess: &'a parse::ParseSess,
929 ecfg: expand::ExpansionConfig<'a>,
930 resolver: &'a mut dyn Resolver)
935 root_path: PathBuf::new(),
937 current_expansion: ExpansionData {
940 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
941 directory_ownership: DirectoryOwnership::Owned { relative: None },
942 prior_type_ascription: None,
944 expansions: FxHashMap::default(),
948 /// Returns a `Folder` for deeply expanding all macros in an AST node.
949 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
950 expand::MacroExpander::new(self, false)
953 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
954 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
955 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
956 expand::MacroExpander::new(self, true)
958 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
959 parse::stream_to_parser(self.parse_sess, stream, MACRO_ARGUMENTS)
961 pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
962 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
963 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
964 pub fn call_site(&self) -> Span {
965 self.current_expansion.id.expn_data().call_site
968 /// Equivalent of `Span::def_site` from the proc macro API,
969 /// except that the location is taken from the span passed as an argument.
970 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
971 span.with_def_site_ctxt(self.current_expansion.id)
974 /// Equivalent of `Span::call_site` from the proc macro API,
975 /// except that the location is taken from the span passed as an argument.
976 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
977 span.with_call_site_ctxt(self.current_expansion.id)
980 /// Returns span for the macro which originally caused the current expansion to happen.
982 /// Stops backtracing at include! boundary.
983 pub fn expansion_cause(&self) -> Option<Span> {
984 let mut expn_id = self.current_expansion.id;
985 let mut last_macro = None;
987 let expn_data = expn_id.expn_data();
988 // Stop going up the backtrace once include! is encountered
989 if expn_data.is_root() || expn_data.kind.descr() == sym::include {
992 expn_id = expn_data.call_site.ctxt().outer_expn();
993 last_macro = Some(expn_data.call_site);
998 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
1001 -> DiagnosticBuilder<'a> {
1002 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
1004 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
1007 -> DiagnosticBuilder<'a> {
1008 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1010 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
1013 -> DiagnosticBuilder<'a> {
1014 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
1017 /// Emit `msg` attached to `sp`, and stop compilation immediately.
1019 /// `span_err` should be strongly preferred where-ever possible:
1020 /// this should *only* be used when:
1022 /// - continuing has a high risk of flow-on errors (e.g., errors in
1023 /// declaring a macro would cause all uses of that macro to
1024 /// complain about "undefined macro"), or
1025 /// - there is literally nothing else that can be done (however,
1026 /// in most cases one can construct a dummy expression/item to
1027 /// substitute; we never hit resolve/type-checking so the dummy
1028 /// value doesn't have to match anything)
1029 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1030 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
1033 /// Emit `msg` attached to `sp`, without immediately stopping
1036 /// Compilation will be stopped in the near future (at the end of
1037 /// the macro expansion phase).
1038 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1039 self.parse_sess.span_diagnostic.span_err(sp, msg);
1041 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
1042 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
1044 pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
1045 -> DiagnosticBuilder<'a> {
1046 self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
1048 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1049 self.parse_sess.span_diagnostic.span_warn(sp, msg);
1051 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1052 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
1054 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1055 self.parse_sess.span_diagnostic.span_bug(sp, msg);
1057 pub fn trace_macros_diag(&mut self) {
1058 for (sp, notes) in self.expansions.iter() {
1059 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1065 // Fixme: does this result in errors?
1066 self.expansions.clear();
1068 pub fn bug(&self, msg: &str) -> ! {
1069 self.parse_sess.span_diagnostic.bug(msg);
1071 pub fn trace_macros(&self) -> bool {
1074 pub fn set_trace_macros(&mut self, x: bool) {
1075 self.ecfg.trace_mac = x
1077 pub fn ident_of(&self, st: &str, sp: Span) -> ast::Ident {
1078 ast::Ident::from_str_and_span(st, sp)
1080 pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
1081 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1082 iter::once(Ident::new(kw::DollarCrate, def_site))
1083 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1086 pub fn name_of(&self, st: &str) -> ast::Name {
1090 pub fn check_unused_macros(&self) {
1091 self.resolver.check_unused_macros();
1094 /// Resolves a path mentioned inside Rust code.
1096 /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
1098 /// Returns an absolute path to the file that `path` refers to.
1099 pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PathBuf {
1100 let path = path.into();
1102 // Relative paths are resolved relative to the file in which they are found
1103 // after macro expansion (that is, they are unhygienic).
1104 if !path.is_absolute() {
1105 let callsite = span.source_callsite();
1106 let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1107 FileName::Real(path) => path,
1108 FileName::DocTest(path, _) => path,
1109 other => panic!("cannot resolve relative path in non-file source `{}`", other),
1120 /// Extracts a string literal from the macro expanded version of `expr`,
1121 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1122 /// compilation on error, merely emits a non-fatal error and returns `None`.
1123 pub fn expr_to_spanned_string<'a>(
1124 cx: &'a mut ExtCtxt<'_>,
1127 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1128 // Perform eager expansion on the expression.
1129 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1130 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1132 Err(match expr.node {
1133 ast::ExprKind::Lit(ref l) => match l.node {
1134 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1135 ast::LitKind::Err(_) => None,
1136 _ => Some(cx.struct_span_err(l.span, err_msg))
1138 ast::ExprKind::Err => None,
1139 _ => Some(cx.struct_span_err(expr.span, err_msg))
1143 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
1144 -> Option<(Symbol, ast::StrStyle)> {
1145 expr_to_spanned_string(cx, expr, err_msg)
1146 .map_err(|err| err.map(|mut err| err.emit()))
1148 .map(|(symbol, style, _)| (symbol, style))
1151 /// Non-fatally assert that `tts` is empty. Note that this function
1152 /// returns even when `tts` is non-empty, macros that *need* to stop
1153 /// compilation should call
1154 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1155 /// done as rarely as possible).
1156 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
1160 if !tts.is_empty() {
1161 cx.span_err(sp, &format!("{} takes no arguments", name));
1165 /// Interpreting `tts` as a comma-separated sequence of expressions,
1166 /// expect exactly one string literal, or emit an error and return `None`.
1167 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
1172 let mut p = cx.new_parser_from_tts(tts);
1173 if p.token == token::Eof {
1174 cx.span_err(sp, &format!("{} takes 1 argument", name));
1177 let ret = panictry!(p.parse_expr());
1178 let _ = p.eat(&token::Comma);
1180 if p.token != token::Eof {
1181 cx.span_err(sp, &format!("{} takes 1 argument", name));
1183 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1188 /// Extracts comma-separated expressions from `tts`. If there is a
1189 /// parsing error, emit a non-fatal error and return `None`.
1190 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
1192 tts: TokenStream) -> Option<Vec<P<ast::Expr>>> {
1193 let mut p = cx.new_parser_from_tts(tts);
1194 let mut es = Vec::new();
1195 while p.token != token::Eof {
1196 let expr = panictry!(p.parse_expr());
1198 // Perform eager expansion on the expression.
1199 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1200 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1203 if p.eat(&token::Comma) {
1206 if p.token != token::Eof {
1207 cx.span_err(sp, "expected token: `,`");