1 use crate::expand::{self, AstFragment, Invocation};
3 use rustc_parse::{self, parser, DirectoryOwnership, MACRO_ARGUMENTS};
4 use syntax::ast::{self, NodeId, Attribute, Name, PatKind};
5 use syntax::attr::{self, HasAttrs, Stability, Deprecation};
6 use syntax::source_map::SourceMap;
7 use syntax::edition::Edition;
8 use syntax::mut_visit::{self, MutVisitor};
10 use syntax::sess::ParseSess;
11 use syntax::symbol::{kw, sym, Ident, Symbol};
14 use syntax::tokenstream::{self, TokenStream};
15 use syntax::visit::Visitor;
17 use errors::{DiagnosticBuilder, DiagnosticId};
18 use smallvec::{smallvec, SmallVec};
19 use syntax_pos::{FileName, Span, MultiSpan, DUMMY_SP};
20 use syntax_pos::hygiene::{AstPass, ExpnId, ExpnData, ExpnKind};
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_data_structures::sync::{self, Lrc};
25 use std::path::PathBuf;
27 use std::default::Default;
29 crate use syntax_pos::hygiene::MacroKind;
31 #[derive(Debug,Clone)]
32 pub enum Annotatable {
34 TraitItem(P<ast::TraitItem>),
35 ImplItem(P<ast::ImplItem>),
36 ForeignItem(P<ast::ForeignItem>),
41 FieldPat(ast::FieldPat),
42 GenericParam(ast::GenericParam),
44 StructField(ast::StructField),
45 Variant(ast::Variant),
48 impl HasAttrs for Annotatable {
49 fn attrs(&self) -> &[Attribute] {
51 Annotatable::Item(ref item) => &item.attrs,
52 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
53 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
54 Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
55 Annotatable::Stmt(ref stmt) => stmt.attrs(),
56 Annotatable::Expr(ref expr) => &expr.attrs,
57 Annotatable::Arm(ref arm) => &arm.attrs,
58 Annotatable::Field(ref field) => &field.attrs,
59 Annotatable::FieldPat(ref fp) => &fp.attrs,
60 Annotatable::GenericParam(ref gp) => &gp.attrs,
61 Annotatable::Param(ref p) => &p.attrs,
62 Annotatable::StructField(ref sf) => &sf.attrs,
63 Annotatable::Variant(ref v) => &v.attrs(),
67 fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
69 Annotatable::Item(item) => item.visit_attrs(f),
70 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
71 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
72 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
73 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
74 Annotatable::Expr(expr) => expr.visit_attrs(f),
75 Annotatable::Arm(arm) => arm.visit_attrs(f),
76 Annotatable::Field(field) => field.visit_attrs(f),
77 Annotatable::FieldPat(fp) => fp.visit_attrs(f),
78 Annotatable::GenericParam(gp) => gp.visit_attrs(f),
79 Annotatable::Param(p) => p.visit_attrs(f),
80 Annotatable::StructField(sf) => sf.visit_attrs(f),
81 Annotatable::Variant(v) => v.visit_attrs(f),
87 pub fn span(&self) -> Span {
89 Annotatable::Item(ref item) => item.span,
90 Annotatable::TraitItem(ref trait_item) => trait_item.span,
91 Annotatable::ImplItem(ref impl_item) => impl_item.span,
92 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
93 Annotatable::Stmt(ref stmt) => stmt.span,
94 Annotatable::Expr(ref expr) => expr.span,
95 Annotatable::Arm(ref arm) => arm.span,
96 Annotatable::Field(ref field) => field.span,
97 Annotatable::FieldPat(ref fp) => fp.pat.span,
98 Annotatable::GenericParam(ref gp) => gp.ident.span,
99 Annotatable::Param(ref p) => p.span,
100 Annotatable::StructField(ref sf) => sf.span,
101 Annotatable::Variant(ref v) => v.span,
105 pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
107 Annotatable::Item(item) => visitor.visit_item(item),
108 Annotatable::TraitItem(trait_item) => visitor.visit_trait_item(trait_item),
109 Annotatable::ImplItem(impl_item) => visitor.visit_impl_item(impl_item),
110 Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
111 Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
112 Annotatable::Expr(expr) => visitor.visit_expr(expr),
113 Annotatable::Arm(arm) => visitor.visit_arm(arm),
114 Annotatable::Field(field) => visitor.visit_field(field),
115 Annotatable::FieldPat(fp) => visitor.visit_field_pattern(fp),
116 Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
117 Annotatable::Param(p) => visitor.visit_param(p),
118 Annotatable::StructField(sf) =>visitor.visit_struct_field(sf),
119 Annotatable::Variant(v) => visitor.visit_variant(v),
123 pub fn expect_item(self) -> P<ast::Item> {
125 Annotatable::Item(i) => i,
126 _ => panic!("expected Item")
130 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
131 where 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::TraitItem {
142 Annotatable::TraitItem(i) => i.into_inner(),
143 _ => panic!("expected Item")
147 pub fn expect_impl_item(self) -> ast::ImplItem {
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(..) |
228 ast::ItemKind::Enum(..) |
229 ast::ItemKind::Union(..) => true,
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 {
241 ecx: &mut ExtCtxt<'_>,
243 meta_item: &ast::MetaItem,
248 impl<F, T> MultiItemModifier for F
249 where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
250 T: Into<Vec<Annotatable>>,
253 ecx: &mut ExtCtxt<'_>,
255 meta_item: &ast::MetaItem,
257 -> Vec<Annotatable> {
258 (*self)(ecx, span, meta_item, item).into()
262 impl Into<Vec<Annotatable>> for Annotatable {
263 fn into(self) -> Vec<Annotatable> {
268 pub trait ProcMacro {
269 fn expand<'cx>(&self,
270 ecx: &'cx mut ExtCtxt<'_>,
276 impl<F> ProcMacro for F
277 where F: Fn(TokenStream) -> TokenStream
279 fn expand<'cx>(&self,
280 _ecx: &'cx mut ExtCtxt<'_>,
284 // FIXME setup implicit context in TLS before calling self.
289 pub trait AttrProcMacro {
290 fn expand<'cx>(&self,
291 ecx: &'cx mut ExtCtxt<'_>,
293 annotation: TokenStream,
294 annotated: TokenStream)
298 impl<F> AttrProcMacro for F
299 where F: Fn(TokenStream, TokenStream) -> TokenStream
301 fn expand<'cx>(&self,
302 _ecx: &'cx mut ExtCtxt<'_>,
304 annotation: TokenStream,
305 annotated: TokenStream)
307 // FIXME setup implicit context in TLS before calling self.
308 (*self)(annotation, annotated)
312 /// Represents a thing that maps token trees to Macro Results
313 pub trait TTMacroExpander {
316 ecx: &'cx mut ExtCtxt<'_>,
319 ) -> Box<dyn MacResult+'cx>;
322 pub type MacroExpanderFn =
323 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream)
324 -> Box<dyn MacResult+'cx>;
326 impl<F> TTMacroExpander for F
327 where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream)
328 -> Box<dyn MacResult+'cx>
332 ecx: &'cx mut ExtCtxt<'_>,
334 mut input: TokenStream,
335 ) -> Box<dyn MacResult+'cx> {
336 struct AvoidInterpolatedIdents;
338 impl MutVisitor for AvoidInterpolatedIdents {
339 fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
340 if let tokenstream::TokenTree::Token(token) = tt {
341 if let token::Interpolated(nt) = &token.kind {
342 if let token::NtIdent(ident, is_raw) = **nt {
343 *tt = tokenstream::TokenTree::token(
344 token::Ident(ident.name, is_raw), ident.span
349 mut_visit::noop_visit_tt(tt, self)
352 fn visit_mac(&mut self, mac: &mut ast::Mac) {
353 mut_visit::noop_visit_mac(mac, self)
356 AvoidInterpolatedIdents.visit_tts(&mut input);
357 (*self)(ecx, span, input)
361 // Use a macro because forwarding to a simple function has type system issues
362 macro_rules! make_stmts_default {
364 $me.make_expr().map(|e| smallvec![ast::Stmt {
365 id: ast::DUMMY_NODE_ID,
367 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<[ast::ImplItem; 1]>> {
389 /// Creates zero or more trait items.
390 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
394 /// Creates zero or more items in an `extern {}` block
395 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None }
397 /// Creates a pattern.
398 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
402 /// Creates zero or more statements.
404 /// By default this attempts to create an expression statement,
405 /// returning None if that fails.
406 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
407 make_stmts_default!(self)
410 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
414 fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
418 fn make_fields(self: Box<Self>) -> Option<SmallVec<[ast::Field; 1]>> {
422 fn make_field_patterns(self: Box<Self>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
426 fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
430 fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
434 fn make_struct_fields(self: Box<Self>) -> Option<SmallVec<[ast::StructField; 1]>> {
438 fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
443 macro_rules! make_MacEager {
444 ( $( $fld:ident: $t:ty, )* ) => {
445 /// `MacResult` implementation for the common case where you've already
446 /// built each form of AST that you might return.
448 pub struct MacEager {
450 pub $fld: Option<$t>,
456 pub fn $fld(v: $t) -> Box<dyn MacResult> {
470 items: SmallVec<[P<ast::Item>; 1]>,
471 impl_items: SmallVec<[ast::ImplItem; 1]>,
472 trait_items: SmallVec<[ast::TraitItem; 1]>,
473 foreign_items: SmallVec<[ast::ForeignItem; 1]>,
474 stmts: SmallVec<[ast::Stmt; 1]>,
478 impl MacResult for MacEager {
479 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
483 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
487 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
491 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
495 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
499 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
500 match self.stmts.as_ref().map_or(0, |s| s.len()) {
501 0 => make_stmts_default!(self),
506 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
507 if let Some(p) = self.pat {
510 if let Some(e) = self.expr {
511 if let ast::ExprKind::Lit(_) = e.kind {
512 return Some(P(ast::Pat {
513 id: ast::DUMMY_NODE_ID,
515 kind: PatKind::Lit(e),
522 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
527 /// Fill-in macro expansion result, to allow compilation to continue
528 /// after hitting errors.
529 #[derive(Copy, Clone)]
530 pub struct DummyResult {
536 /// Creates a default MacResult that can be anything.
538 /// Use this as a return value after hitting any errors and
539 /// calling `span_err`.
540 pub fn any(span: Span) -> Box<dyn MacResult+'static> {
541 Box::new(DummyResult { is_error: true, span })
544 /// Same as `any`, but must be a valid fragment, not error.
545 pub fn any_valid(span: Span) -> Box<dyn MacResult+'static> {
546 Box::new(DummyResult { is_error: false, span })
549 /// A plain dummy expression.
550 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
552 id: ast::DUMMY_NODE_ID,
553 kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
555 attrs: ThinVec::new(),
559 /// A plain dummy pattern.
560 pub fn raw_pat(sp: Span) -> ast::Pat {
562 id: ast::DUMMY_NODE_ID,
568 /// A plain dummy type.
569 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
571 id: ast::DUMMY_NODE_ID,
572 kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
578 impl MacResult for DummyResult {
579 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
580 Some(DummyResult::raw_expr(self.span, self.is_error))
583 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
584 Some(P(DummyResult::raw_pat(self.span)))
587 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
588 Some(SmallVec::new())
591 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
592 Some(SmallVec::new())
595 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
596 Some(SmallVec::new())
599 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
600 Some(SmallVec::new())
603 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
604 Some(smallvec![ast::Stmt {
605 id: ast::DUMMY_NODE_ID,
606 kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
611 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
612 Some(DummyResult::raw_ty(self.span, self.is_error))
615 fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
616 Some(SmallVec::new())
619 fn make_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::Field; 1]>> {
620 Some(SmallVec::new())
623 fn make_field_patterns(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
624 Some(SmallVec::new())
627 fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
628 Some(SmallVec::new())
631 fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
632 Some(SmallVec::new())
635 fn make_struct_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::StructField; 1]>> {
636 Some(SmallVec::new())
639 fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
640 Some(SmallVec::new())
644 /// A syntax extension kind.
645 pub enum SyntaxExtensionKind {
646 /// A token-based function-like macro.
648 /// An expander with signature TokenStream -> TokenStream.
649 Box<dyn ProcMacro + sync::Sync + sync::Send>,
652 /// An AST-based function-like macro.
654 /// An expander with signature TokenStream -> AST.
655 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
658 /// A token-based attribute macro.
660 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
661 /// The first TokenSteam is the attribute itself, the second is the annotated item.
662 /// The produced TokenSteam replaces the input TokenSteam.
663 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
666 /// An AST-based attribute macro.
668 /// An expander with signature (AST, AST) -> AST.
669 /// The first AST fragment is the attribute itself, the second is the annotated item.
670 /// The produced AST fragment replaces the input AST fragment.
671 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
674 /// A trivial attribute "macro" that does nothing,
675 /// only keeps the attribute and marks it as inert,
676 /// thus making it ineligible for further expansion.
678 /// Suppresses the `unused_attributes` lint for this attribute.
682 /// A token-based derive macro.
684 /// An expander with signature TokenStream -> TokenStream (not yet).
685 /// The produced TokenSteam is appended to the input TokenSteam.
686 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
689 /// An AST-based derive macro.
691 /// An expander with signature AST -> AST.
692 /// The produced AST fragment is appended to the input AST fragment.
693 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
697 /// A struct representing a macro definition in "lowered" form ready for expansion.
698 pub struct SyntaxExtension {
699 /// A syntax extension kind.
700 pub kind: SyntaxExtensionKind,
701 /// Span of the macro definition.
703 /// Whitelist of unstable features that are treated as stable inside this macro.
704 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
705 /// Suppresses the `unsafe_code` lint for code produced by this macro.
706 pub allow_internal_unsafe: bool,
707 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
708 pub local_inner_macros: bool,
709 /// The macro's stability info.
710 pub stability: Option<Stability>,
711 /// The macro's deprecation info.
712 pub deprecation: Option<Deprecation>,
713 /// Names of helper attributes registered by this macro.
714 pub helper_attrs: Vec<Symbol>,
715 /// Edition of the crate in which this macro is defined.
716 pub edition: Edition,
717 /// Built-in macros have a couple of special properties like availability
718 /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
719 pub is_builtin: bool,
720 /// We have to identify macros providing a `Copy` impl early for compatibility reasons.
721 pub is_derive_copy: bool,
724 impl SyntaxExtension {
725 /// Returns which kind of macro calls this syntax extension.
726 pub fn macro_kind(&self) -> MacroKind {
728 SyntaxExtensionKind::Bang(..) |
729 SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
730 SyntaxExtensionKind::Attr(..) |
731 SyntaxExtensionKind::LegacyAttr(..) |
732 SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
733 SyntaxExtensionKind::Derive(..) |
734 SyntaxExtensionKind::LegacyDerive(..) => MacroKind::Derive,
738 /// Constructs a syntax extension with default properties.
739 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
742 allow_internal_unstable: None,
743 allow_internal_unsafe: false,
744 local_inner_macros: false,
747 helper_attrs: Vec::new(),
750 is_derive_copy: false,
755 /// Constructs a syntax extension with the given properties
756 /// and other properties converted from attributes.
759 kind: SyntaxExtensionKind,
761 helper_attrs: Vec<Symbol>,
764 attrs: &[ast::Attribute],
765 ) -> SyntaxExtension {
766 let allow_internal_unstable = attr::allow_internal_unstable(
767 &attrs, &sess.span_diagnostic,
768 ).map(|features| features.collect::<Vec<Symbol>>().into());
770 let mut local_inner_macros = false;
771 if let Some(macro_export) = attr::find_by_name(attrs, sym::macro_export) {
772 if let Some(l) = macro_export.meta_item_list() {
773 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
777 let is_builtin = attr::contains_name(attrs, sym::rustc_builtin_macro);
782 allow_internal_unstable,
783 allow_internal_unsafe: attr::contains_name(attrs, sym::allow_internal_unsafe),
785 stability: attr::find_stability(&sess, attrs, span),
786 deprecation: attr::find_deprecation(&sess, attrs, span),
790 is_derive_copy: is_builtin && name == sym::Copy,
794 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
795 fn expander<'cx>(_: &'cx mut ExtCtxt<'_>, span: Span, _: TokenStream)
796 -> Box<dyn MacResult + 'cx> {
797 DummyResult::any(span)
799 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
802 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
803 fn expander(_: &mut ExtCtxt<'_>, _: Span, _: &ast::MetaItem, _: Annotatable)
804 -> Vec<Annotatable> {
807 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
810 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
811 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
814 pub fn expn_data(&self, parent: ExpnId, call_site: Span, descr: Symbol) -> ExpnData {
816 kind: ExpnKind::Macro(self.macro_kind(), descr),
820 allow_internal_unstable: self.allow_internal_unstable.clone(),
821 allow_internal_unsafe: self.allow_internal_unsafe,
822 local_inner_macros: self.local_inner_macros,
823 edition: self.edition,
828 /// Result of resolving a macro invocation.
829 pub enum InvocationRes {
830 Single(Lrc<SyntaxExtension>),
831 DeriveContainer(Vec<Lrc<SyntaxExtension>>),
834 /// Error type that denotes indeterminacy.
835 pub struct Indeterminate;
838 fn next_node_id(&mut self) -> NodeId;
840 fn resolve_dollar_crates(&mut self);
841 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment);
842 fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension);
844 fn expansion_for_ast_pass(
849 parent_module_id: Option<NodeId>,
852 fn resolve_imports(&mut self);
854 fn resolve_macro_invocation(
855 &mut self, invoc: &Invocation, eager_expansion_root: ExpnId, force: bool
856 ) -> Result<InvocationRes, Indeterminate>;
858 fn check_unused_macros(&mut self);
860 fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
861 fn add_derive_copy(&mut self, expn_id: ExpnId);
865 pub struct ModuleData {
866 pub mod_path: Vec<ast::Ident>,
867 pub directory: PathBuf,
871 pub struct ExpansionData {
874 pub module: Rc<ModuleData>,
875 pub directory_ownership: DirectoryOwnership,
876 pub prior_type_ascription: Option<(Span, bool)>,
879 /// One of these is made during expansion and incrementally updated as we go;
880 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
881 /// -> expn_data` of their expansion context stored into their span.
882 pub struct ExtCtxt<'a> {
883 pub parse_sess: &'a ParseSess,
884 pub ecfg: expand::ExpansionConfig<'a>,
885 pub root_path: PathBuf,
886 pub resolver: &'a mut dyn Resolver,
887 pub current_expansion: ExpansionData,
888 pub expansions: FxHashMap<Span, Vec<String>>,
891 impl<'a> ExtCtxt<'a> {
892 pub fn new(parse_sess: &'a ParseSess,
893 ecfg: expand::ExpansionConfig<'a>,
894 resolver: &'a mut dyn Resolver)
899 root_path: PathBuf::new(),
901 current_expansion: ExpansionData {
904 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
905 directory_ownership: DirectoryOwnership::Owned { relative: None },
906 prior_type_ascription: None,
908 expansions: FxHashMap::default(),
912 /// Returns a `Folder` for deeply expanding all macros in an AST node.
913 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
914 expand::MacroExpander::new(self, false)
917 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
918 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
919 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
920 expand::MacroExpander::new(self, true)
922 pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
923 rustc_parse::stream_to_parser(self.parse_sess, stream, MACRO_ARGUMENTS)
925 pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
926 pub fn parse_sess(&self) -> &'a ParseSess { self.parse_sess }
927 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
928 pub fn call_site(&self) -> Span {
929 self.current_expansion.id.expn_data().call_site
932 /// Equivalent of `Span::def_site` from the proc macro API,
933 /// except that the location is taken from the span passed as an argument.
934 pub fn with_def_site_ctxt(&self, span: Span) -> Span {
935 span.with_def_site_ctxt(self.current_expansion.id)
938 /// Equivalent of `Span::call_site` from the proc macro API,
939 /// except that the location is taken from the span passed as an argument.
940 pub fn with_call_site_ctxt(&self, span: Span) -> Span {
941 span.with_call_site_ctxt(self.current_expansion.id)
944 /// Equivalent of `Span::mixed_site` from the proc macro API,
945 /// except that the location is taken from the span passed as an argument.
946 pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
947 span.with_mixed_site_ctxt(self.current_expansion.id)
950 /// Returns span for the macro which originally caused the current expansion to happen.
952 /// Stops backtracing at include! boundary.
953 pub fn expansion_cause(&self) -> Option<Span> {
954 self.current_expansion.id.expansion_cause()
957 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
960 -> DiagnosticBuilder<'a> {
961 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
963 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
966 -> DiagnosticBuilder<'a> {
967 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
969 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
972 -> DiagnosticBuilder<'a> {
973 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
976 /// Emit `msg` attached to `sp`, and stop compilation immediately.
978 /// `span_err` should be strongly preferred where-ever possible:
979 /// this should *only* be used when:
981 /// - continuing has a high risk of flow-on errors (e.g., errors in
982 /// declaring a macro would cause all uses of that macro to
983 /// complain about "undefined macro"), or
984 /// - there is literally nothing else that can be done (however,
985 /// in most cases one can construct a dummy expression/item to
986 /// substitute; we never hit resolve/type-checking so the dummy
987 /// value doesn't have to match anything)
988 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
989 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
992 /// Emit `msg` attached to `sp`, without immediately stopping
995 /// Compilation will be stopped in the near future (at the end of
996 /// the macro expansion phase).
997 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
998 self.parse_sess.span_diagnostic.span_err(sp, msg);
1000 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
1001 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
1003 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1004 self.parse_sess.span_diagnostic.span_warn(sp, msg);
1006 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1007 self.parse_sess.span_diagnostic.span_bug(sp, msg);
1009 pub fn trace_macros_diag(&mut self) {
1010 for (sp, notes) in self.expansions.iter() {
1011 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1017 // Fixme: does this result in errors?
1018 self.expansions.clear();
1020 pub fn bug(&self, msg: &str) -> ! {
1021 self.parse_sess.span_diagnostic.bug(msg);
1023 pub fn trace_macros(&self) -> bool {
1026 pub fn set_trace_macros(&mut self, x: bool) {
1027 self.ecfg.trace_mac = x
1029 pub fn ident_of(&self, st: &str, sp: Span) -> ast::Ident {
1030 ast::Ident::from_str_and_span(st, sp)
1032 pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
1033 let def_site = self.with_def_site_ctxt(DUMMY_SP);
1034 iter::once(Ident::new(kw::DollarCrate, def_site))
1035 .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1038 pub fn name_of(&self, st: &str) -> ast::Name {
1042 pub fn check_unused_macros(&mut self) {
1043 self.resolver.check_unused_macros();
1046 /// Resolves a path mentioned inside Rust code.
1048 /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
1050 /// Returns an absolute path to the file that `path` refers to.
1051 pub fn resolve_path(
1053 path: impl Into<PathBuf>,
1055 ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1056 let path = path.into();
1058 // Relative paths are resolved relative to the file in which they are found
1059 // after macro expansion (that is, they are unhygienic).
1060 if !path.is_absolute() {
1061 let callsite = span.source_callsite();
1062 let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1063 FileName::Real(path) => path,
1064 FileName::DocTest(path, _) => path,
1065 other => return Err(self.struct_span_err(
1067 &format!("cannot resolve relative path in non-file source `{}`", other),
1079 /// Extracts a string literal from the macro expanded version of `expr`,
1080 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1081 /// compilation on error, merely emits a non-fatal error and returns `None`.
1082 pub fn expr_to_spanned_string<'a>(
1083 cx: &'a mut ExtCtxt<'_>,
1086 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1087 // Perform eager expansion on the expression.
1088 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1089 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1091 Err(match expr.kind {
1092 ast::ExprKind::Lit(ref l) => match l.kind {
1093 ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1094 ast::LitKind::Err(_) => None,
1095 _ => Some(cx.struct_span_err(l.span, err_msg))
1097 ast::ExprKind::Err => None,
1098 _ => Some(cx.struct_span_err(expr.span, err_msg))
1102 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
1103 -> Option<(Symbol, ast::StrStyle)> {
1104 expr_to_spanned_string(cx, expr, err_msg)
1105 .map_err(|err| err.map(|mut err| err.emit()))
1107 .map(|(symbol, style, _)| (symbol, style))
1110 /// Non-fatally assert that `tts` is empty. Note that this function
1111 /// returns even when `tts` is non-empty, macros that *need* to stop
1112 /// compilation should call
1113 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1114 /// done as rarely as possible).
1115 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
1119 if !tts.is_empty() {
1120 cx.span_err(sp, &format!("{} takes no arguments", name));
1124 /// Interpreting `tts` as a comma-separated sequence of expressions,
1125 /// expect exactly one string literal, or emit an error and return `None`.
1126 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
1131 let mut p = cx.new_parser_from_tts(tts);
1132 if p.token == token::Eof {
1133 cx.span_err(sp, &format!("{} takes 1 argument", name));
1136 let ret = panictry!(p.parse_expr());
1137 let _ = p.eat(&token::Comma);
1139 if p.token != token::Eof {
1140 cx.span_err(sp, &format!("{} takes 1 argument", name));
1142 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1147 /// Extracts comma-separated expressions from `tts`. If there is a
1148 /// parsing error, emit a non-fatal error and return `None`.
1149 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
1151 tts: TokenStream) -> Option<Vec<P<ast::Expr>>> {
1152 let mut p = cx.new_parser_from_tts(tts);
1153 let mut es = Vec::new();
1154 while p.token != token::Eof {
1155 let expr = panictry!(p.parse_expr());
1157 // Perform eager expansion on the expression.
1158 // We want to be able to handle e.g., `concat!("foo", "bar")`.
1159 let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1162 if p.eat(&token::Comma) {
1165 if p.token != token::Eof {
1166 cx.span_err(sp, "expected token: `,`");