1 use crate::expand::{self, AstFragment, Invocation};
3 use rustc_parse::{self, parser, DirectoryOwnership, MACRO_ARGUMENTS};
4 use rustc_span::edition::Edition;
5 use rustc_span::source_map::SourceMap;
6 use rustc_span::symbol::{kw, sym, Ident, Symbol};
7 use syntax::ast::{self, Attribute, Name, NodeId, PatKind};
8 use syntax::attr::{self, Deprecation, HasAttrs, Stability};
9 use syntax::mut_visit::{self, MutVisitor};
11 use syntax::sess::ParseSess;
13 use syntax::tokenstream::{self, TokenStream};
14 use syntax::visit::Visitor;
16 use errors::{DiagnosticBuilder, DiagnosticId};
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc_data_structures::sync::{self, Lrc};
19 use rustc_span::hygiene::{AstPass, ExpnData, ExpnId, ExpnKind};
20 use rustc_span::{FileName, MultiSpan, Span, DUMMY_SP};
21 use smallvec::{smallvec, SmallVec};
23 use std::default::Default;
25 use std::path::PathBuf;
28 crate use rustc_span::hygiene::MacroKind;
30 #[derive(Debug, Clone)]
31 pub enum Annotatable {
33 TraitItem(P<ast::AssocItem>),
34 ImplItem(P<ast::AssocItem>),
35 ForeignItem(P<ast::ForeignItem>),
40 FieldPat(ast::FieldPat),
41 GenericParam(ast::GenericParam),
43 StructField(ast::StructField),
44 Variant(ast::Variant),
47 impl HasAttrs for Annotatable {
48 fn attrs(&self) -> &[Attribute] {
50 Annotatable::Item(ref item) => &item.attrs,
51 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
52 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
53 Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
54 Annotatable::Stmt(ref stmt) => stmt.attrs(),
55 Annotatable::Expr(ref expr) => &expr.attrs,
56 Annotatable::Arm(ref arm) => &arm.attrs,
57 Annotatable::Field(ref field) => &field.attrs,
58 Annotatable::FieldPat(ref fp) => &fp.attrs,
59 Annotatable::GenericParam(ref gp) => &gp.attrs,
60 Annotatable::Param(ref p) => &p.attrs,
61 Annotatable::StructField(ref sf) => &sf.attrs,
62 Annotatable::Variant(ref v) => &v.attrs(),
66 fn visit_attrs<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
131 F: FnMut(P<ast::Item>) -> P<ast::Item>,
132 G: FnMut(Annotatable) -> Annotatable,
135 Annotatable::Item(i) => Annotatable::Item(f(i)),
140 pub fn expect_trait_item(self) -> ast::AssocItem {
142 Annotatable::TraitItem(i) => i.into_inner(),
143 _ => panic!("expected Item"),
147 pub fn expect_impl_item(self) -> ast::AssocItem {
149 Annotatable::ImplItem(i) => i.into_inner(),
150 _ => panic!("expected Item"),
154 pub fn expect_foreign_item(self) -> ast::ForeignItem {
156 Annotatable::ForeignItem(i) => i.into_inner(),
157 _ => panic!("expected foreign item"),
161 pub fn expect_stmt(self) -> ast::Stmt {
163 Annotatable::Stmt(stmt) => stmt.into_inner(),
164 _ => panic!("expected statement"),
168 pub fn expect_expr(self) -> P<ast::Expr> {
170 Annotatable::Expr(expr) => expr,
171 _ => panic!("expected expression"),
175 pub fn expect_arm(self) -> ast::Arm {
177 Annotatable::Arm(arm) => arm,
178 _ => panic!("expected match arm"),
182 pub fn expect_field(self) -> ast::Field {
184 Annotatable::Field(field) => field,
185 _ => panic!("expected field"),
189 pub fn expect_field_pattern(self) -> ast::FieldPat {
191 Annotatable::FieldPat(fp) => fp,
192 _ => panic!("expected field pattern"),
196 pub fn expect_generic_param(self) -> ast::GenericParam {
198 Annotatable::GenericParam(gp) => gp,
199 _ => panic!("expected generic parameter"),
203 pub fn expect_param(self) -> ast::Param {
205 Annotatable::Param(param) => param,
206 _ => panic!("expected parameter"),
210 pub fn expect_struct_field(self) -> ast::StructField {
212 Annotatable::StructField(sf) => sf,
213 _ => panic!("expected struct field"),
217 pub fn expect_variant(self) -> ast::Variant {
219 Annotatable::Variant(v) => v,
220 _ => panic!("expected variant"),
224 pub fn derive_allowed(&self) -> bool {
226 Annotatable::Item(ref item) => match item.kind {
227 ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..) => {
237 // `meta_item` is the annotation, and `item` is the item being modified.
238 // FIXME Decorators should follow the same pattern too.
239 pub trait MultiItemModifier {
242 ecx: &mut ExtCtxt<'_>,
244 meta_item: &ast::MetaItem,
246 ) -> Vec<Annotatable>;
249 impl<F, T> MultiItemModifier for F
251 F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
252 T: Into<Vec<Annotatable>>,
256 ecx: &mut ExtCtxt<'_>,
258 meta_item: &ast::MetaItem,
260 ) -> Vec<Annotatable> {
261 (*self)(ecx, span, meta_item, item).into()
265 impl Into<Vec<Annotatable>> for Annotatable {
266 fn into(self) -> Vec<Annotatable> {
271 pub trait ProcMacro {
272 fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt<'_>, span: Span, ts: TokenStream) -> TokenStream;
275 impl<F> ProcMacro for F
277 F: Fn(TokenStream) -> TokenStream,
279 fn expand<'cx>(&self, _ecx: &'cx mut ExtCtxt<'_>, _span: Span, ts: TokenStream) -> TokenStream {
280 // FIXME setup implicit context in TLS before calling self.
285 pub trait AttrProcMacro {
288 ecx: &'cx mut ExtCtxt<'_>,
290 annotation: TokenStream,
291 annotated: TokenStream,
295 impl<F> AttrProcMacro for F
297 F: Fn(TokenStream, TokenStream) -> TokenStream,
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) -> Box<dyn MacResult + 'cx>;
324 impl<F> TTMacroExpander for F
326 F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
330 ecx: &'cx mut ExtCtxt<'_>,
332 mut input: TokenStream,
333 ) -> Box<dyn MacResult + 'cx> {
334 struct AvoidInterpolatedIdents;
336 impl MutVisitor for AvoidInterpolatedIdents {
337 fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
338 if let tokenstream::TokenTree::Token(token) = tt {
339 if let token::Interpolated(nt) = &token.kind {
340 if let token::NtIdent(ident, is_raw) = **nt {
341 *tt = tokenstream::TokenTree::token(
342 token::Ident(ident.name, is_raw),
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| {
364 smallvec![ast::Stmt {
365 id: ast::DUMMY_NODE_ID,
367 kind: ast::StmtKind::Expr(e),
373 /// The result of a macro expansion. The return values of the various
374 /// methods are spliced into the AST at the callsite of the macro.
375 pub trait MacResult {
376 /// Creates an expression.
377 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
380 /// Creates zero or more items.
381 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
385 /// Creates zero or more impl items.
386 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::AssocItem; 1]>> {
390 /// Creates zero or more trait items.
391 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::AssocItem; 1]>> {
395 /// Creates zero or more items in an `extern {}` block
396 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
400 /// Creates a pattern.
401 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
405 /// Creates zero or more statements.
407 /// By default this attempts to create an expression statement,
408 /// returning None if that fails.
409 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
410 make_stmts_default!(self)
413 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
417 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
421 fn make_fields(self: Box<Self>) -> Option<SmallVec<[ast::Field; 1]>> {
425 fn make_field_patterns(self: Box<Self>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
429 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
433 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
437 fn make_struct_fields(self: Box<Self>) -> Option<SmallVec<[ast::StructField; 1]>> {
441 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
446 macro_rules! make_MacEager {
447 ( $( $fld:ident: $t:ty, )* ) => {
448 /// `MacResult` implementation for the common case where you've already
449 /// built each form of AST that you might return.
451 pub struct MacEager {
453 pub $fld: Option<$t>,
459 pub fn $fld(v: $t) -> Box<dyn MacResult> {
473 items: SmallVec<[P<ast::Item>; 1]>,
474 impl_items: SmallVec<[ast::AssocItem; 1]>,
475 trait_items: SmallVec<[ast::AssocItem; 1]>,
476 foreign_items: SmallVec<[ast::ForeignItem; 1]>,
477 stmts: SmallVec<[ast::Stmt; 1]>,
481 impl MacResult for MacEager {
482 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
486 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
490 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::AssocItem; 1]>> {
494 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::AssocItem; 1]>> {
498 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
502 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
503 match self.stmts.as_ref().map_or(0, |s| s.len()) {
504 0 => make_stmts_default!(self),
509 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
510 if let Some(p) = self.pat {
513 if let Some(e) = self.expr {
514 if let ast::ExprKind::Lit(_) = e.kind {
515 return Some(P(ast::Pat {
516 id: ast::DUMMY_NODE_ID,
518 kind: PatKind::Lit(e),
525 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
530 /// Fill-in macro expansion result, to allow compilation to continue
531 /// after hitting errors.
532 #[derive(Copy, Clone)]
533 pub struct DummyResult {
539 /// Creates a default MacResult that can be anything.
541 /// Use this as a return value after hitting any errors and
542 /// calling `span_err`.
543 pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
544 Box::new(DummyResult { is_error: true, span })
547 /// Same as `any`, but must be a valid fragment, not error.
548 pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
549 Box::new(DummyResult { is_error: false, span })
552 /// A plain dummy expression.
553 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
555 id: ast::DUMMY_NODE_ID,
556 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
558 attrs: ast::AttrVec::new(),
562 /// A plain dummy pattern.
563 pub fn raw_pat(sp: Span) -> ast::Pat {
564 ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp }
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 kind: 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::AssocItem; 1]>> {
591 Some(SmallVec::new())
594 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::AssocItem; 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 kind: 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(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
728 SyntaxExtensionKind::Attr(..)
729 | SyntaxExtensionKind::LegacyAttr(..)
730 | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
731 SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
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 = attr::allow_internal_unstable(&attrs, &sess.span_diagnostic)
766 .map(|features| features.collect::<Vec<Symbol>>().into());
768 let mut local_inner_macros = false;
769 if let Some(macro_export) = attr::find_by_name(attrs, sym::macro_export) {
770 if let Some(l) = macro_export.meta_item_list() {
771 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
775 let is_builtin = attr::contains_name(attrs, sym::rustc_builtin_macro);
776 let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
777 if const_stability.is_some() {
778 sess.span_diagnostic.span_err(span, "macros cannot have const stability attributes");
784 allow_internal_unstable,
785 allow_internal_unsafe: attr::contains_name(attrs, sym::allow_internal_unsafe),
788 deprecation: attr::find_deprecation(&sess, attrs, span),
792 is_derive_copy: is_builtin && name == sym::Copy,
796 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
798 _: &'cx mut ExtCtxt<'_>,
801 ) -> Box<dyn MacResult + 'cx> {
802 DummyResult::any(span)
804 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
807 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
813 ) -> Vec<Annotatable> {
816 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
819 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
820 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
823 pub fn expn_data(&self, parent: ExpnId, call_site: Span, descr: Symbol) -> ExpnData {
825 kind: ExpnKind::Macro(self.macro_kind(), descr),
829 allow_internal_unstable: self.allow_internal_unstable.clone(),
830 allow_internal_unsafe: self.allow_internal_unsafe,
831 local_inner_macros: self.local_inner_macros,
832 edition: self.edition,
837 /// Result of resolving a macro invocation.
838 pub enum InvocationRes {
839 Single(Lrc<SyntaxExtension>),
840 DeriveContainer(Vec<Lrc<SyntaxExtension>>),
843 /// Error type that denotes indeterminacy.
844 pub struct Indeterminate;
847 fn next_node_id(&mut self) -> NodeId;
849 fn resolve_dollar_crates(&mut self);
850 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment);
851 fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension);
853 fn expansion_for_ast_pass(
858 parent_module_id: Option<NodeId>,
861 fn resolve_imports(&mut self);
863 fn resolve_macro_invocation(
866 eager_expansion_root: ExpnId,
868 ) -> Result<InvocationRes, Indeterminate>;
870 fn check_unused_macros(&mut self);
872 fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
873 fn add_derive_copy(&mut self, expn_id: ExpnId);
877 pub struct ModuleData {
878 pub mod_path: Vec<ast::Ident>,
879 pub directory: PathBuf,
883 pub struct ExpansionData {
886 pub module: Rc<ModuleData>,
887 pub directory_ownership: DirectoryOwnership,
888 pub prior_type_ascription: Option<(Span, bool)>,
891 /// One of these is made during expansion and incrementally updated as we go;
892 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
893 /// -> expn_data` of their expansion context stored into their span.
894 pub struct ExtCtxt<'a> {
895 pub parse_sess: &'a ParseSess,
896 pub ecfg: expand::ExpansionConfig<'a>,
897 pub root_path: PathBuf,
898 pub resolver: &'a mut dyn Resolver,
899 pub current_expansion: ExpansionData,
900 pub expansions: FxHashMap<Span, Vec<String>>,
903 impl<'a> ExtCtxt<'a> {
905 parse_sess: &'a ParseSess,
906 ecfg: expand::ExpansionConfig<'a>,
907 resolver: &'a mut dyn Resolver,
912 root_path: PathBuf::new(),
914 current_expansion: ExpansionData {
917 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
918 directory_ownership: DirectoryOwnership::Owned { relative: None },
919 prior_type_ascription: None,
921 expansions: FxHashMap::default(),
925 /// Returns a `Folder` for deeply expanding all macros in an AST node.
926 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
927 expand::MacroExpander::new(self, false)
930 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
931 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
932 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
933 expand::MacroExpander::new(self, true)
935 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
936 rustc_parse::stream_to_parser(self.parse_sess, stream, MACRO_ARGUMENTS)
938 pub fn source_map(&self) -> &'a SourceMap {
939 self.parse_sess.source_map()
941 pub fn parse_sess(&self) -> &'a ParseSess {
944 pub fn call_site(&self) -> Span {
945 self.current_expansion.id.expn_data().call_site
948 /// Equivalent of `Span::def_site` from the proc macro API,
949 /// except that the location is taken from the span passed as an argument.
950 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
951 span.with_def_site_ctxt(self.current_expansion.id)
954 /// Equivalent of `Span::call_site` from the proc macro API,
955 /// except that the location is taken from the span passed as an argument.
956 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
957 span.with_call_site_ctxt(self.current_expansion.id)
960 /// Equivalent of `Span::mixed_site` from the proc macro API,
961 /// except that the location is taken from the span passed as an argument.
962 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
963 span.with_mixed_site_ctxt(self.current_expansion.id)
966 /// Returns span for the macro which originally caused the current expansion to happen.
968 /// Stops backtracing at include! boundary.
969 pub fn expansion_cause(&self) -> Option<Span> {
970 self.current_expansion.id.expansion_cause()
973 pub fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
974 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
976 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
977 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
979 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
980 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
983 /// Emit `msg` attached to `sp`, and stop compilation immediately.
985 /// `span_err` should be strongly preferred where-ever possible:
986 /// this should *only* be used when:
988 /// - continuing has a high risk of flow-on errors (e.g., errors in
989 /// declaring a macro would cause all uses of that macro to
990 /// complain about "undefined macro"), or
991 /// - there is literally nothing else that can be done (however,
992 /// in most cases one can construct a dummy expression/item to
993 /// substitute; we never hit resolve/type-checking so the dummy
994 /// value doesn't have to match anything)
995 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
996 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
999 /// Emit `msg` attached to `sp`, without immediately stopping
1002 /// Compilation will be stopped in the near future (at the end of
1003 /// the macro expansion phase).
1004 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1005 self.parse_sess.span_diagnostic.span_err(sp, msg);
1007 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
1008 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
1010 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1011 self.parse_sess.span_diagnostic.span_warn(sp, msg);
1013 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1014 self.parse_sess.span_diagnostic.span_bug(sp, msg);
1016 pub fn trace_macros_diag(&mut self) {
1017 for (sp, notes) in self.expansions.iter() {
1018 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1024 // Fixme: does this result in errors?
1025 self.expansions.clear();
1027 pub fn bug(&self, msg: &str) -> ! {
1028 self.parse_sess.span_diagnostic.bug(msg);
1030 pub fn trace_macros(&self) -> bool {
1033 pub fn set_trace_macros(&mut self, x: bool) {
1034 self.ecfg.trace_mac = x
1036 pub fn ident_of(&self, st: &str, sp: Span) -> ast::Ident {
1037 ast::Ident::from_str_and_span(st, sp)
1039 pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
1040 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1041 iter::once(Ident::new(kw::DollarCrate, def_site))
1042 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1045 pub fn name_of(&self, st: &str) -> ast::Name {
1049 pub fn check_unused_macros(&mut self) {
1050 self.resolver.check_unused_macros();
1053 /// Resolves a path mentioned inside Rust code.
1055 /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
1057 /// Returns an absolute path to the file that `path` refers to.
1058 pub fn resolve_path(
1060 path: impl Into<PathBuf>,
1062 ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1063 let path = path.into();
1065 // Relative paths are resolved relative to the file in which they are found
1066 // after macro expansion (that is, they are unhygienic).
1067 if !path.is_absolute() {
1068 let callsite = span.source_callsite();
1069 let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1070 FileName::Real(path) => path,
1071 FileName::DocTest(path, _) => path,
1073 return Err(self.struct_span_err(
1075 &format!("cannot resolve relative path in non-file source `{}`", other),
1088 /// Extracts a string literal from the macro expanded version of `expr`,
1089 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1090 /// compilation on error, merely emits a non-fatal error and returns `None`.
1091 pub fn expr_to_spanned_string<'a>(
1092 cx: &'a mut ExtCtxt<'_>,
1095 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1096 // Perform eager expansion on the expression.
1097 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1098 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1100 Err(match expr.kind {
1101 ast::ExprKind::Lit(ref l) => match l.kind {
1102 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1103 ast::LitKind::Err(_) => None,
1104 _ => Some(cx.struct_span_err(l.span, err_msg)),
1106 ast::ExprKind::Err => None,
1107 _ => Some(cx.struct_span_err(expr.span, err_msg)),
1111 pub fn expr_to_string(
1112 cx: &mut ExtCtxt<'_>,
1115 ) -> Option<(Symbol, ast::StrStyle)> {
1116 expr_to_spanned_string(cx, expr, err_msg)
1117 .map_err(|err| err.map(|mut err| err.emit()))
1119 .map(|(symbol, style, _)| (symbol, style))
1122 /// Non-fatally assert that `tts` is empty. Note that this function
1123 /// returns even when `tts` is non-empty, macros that *need* to stop
1124 /// compilation should call
1125 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1126 /// done as rarely as possible).
1127 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1128 if !tts.is_empty() {
1129 cx.span_err(sp, &format!("{} takes no arguments", name));
1133 /// Interpreting `tts` as a comma-separated sequence of expressions,
1134 /// expect exactly one string literal, or emit an error and return `None`.
1135 pub fn get_single_str_from_tts(
1136 cx: &mut ExtCtxt<'_>,
1140 ) -> Option<String> {
1141 let mut p = cx.new_parser_from_tts(tts);
1142 if p.token == token::Eof {
1143 cx.span_err(sp, &format!("{} takes 1 argument", name));
1146 let ret = panictry!(p.parse_expr());
1147 let _ = p.eat(&token::Comma);
1149 if p.token != token::Eof {
1150 cx.span_err(sp, &format!("{} takes 1 argument", name));
1152 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1155 /// Extracts comma-separated expressions from `tts`. If there is a
1156 /// parsing error, emit a non-fatal error and return `None`.
1157 pub fn get_exprs_from_tts(
1158 cx: &mut ExtCtxt<'_>,
1161 ) -> Option<Vec<P<ast::Expr>>> {
1162 let mut p = cx.new_parser_from_tts(tts);
1163 let mut es = Vec::new();
1164 while p.token != token::Eof {
1165 let expr = panictry!(p.parse_expr());
1167 // Perform eager expansion on the expression.
1168 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1169 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1172 if p.eat(&token::Comma) {
1175 if p.token != token::Eof {
1176 cx.span_err(sp, "expected token: `,`");