1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::SyntaxExtension::*;
13 use ast::{self, Attribute, Name, PatKind, MetaItem};
15 use source_map::{self, SourceMap, Spanned, respan};
16 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
18 use errors::{DiagnosticBuilder, DiagnosticId};
19 use ext::expand::{self, AstFragment, Invocation};
20 use ext::hygiene::{self, Mark, SyntaxContext, Transparency};
21 use fold::{self, Folder};
22 use parse::{self, parser, DirectoryOwnership};
26 use symbol::{keywords, Ident, Symbol};
29 use std::collections::HashMap;
31 use std::path::PathBuf;
33 use rustc_data_structures::sync::{self, Lrc};
34 use std::default::Default;
35 use tokenstream::{self, TokenStream};
38 #[derive(Debug,Clone)]
39 pub enum Annotatable {
41 TraitItem(P<ast::TraitItem>),
42 ImplItem(P<ast::ImplItem>),
43 ForeignItem(P<ast::ForeignItem>),
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,
60 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
62 Annotatable::Item(item) => Annotatable::Item(item.map_attrs(f)),
63 Annotatable::TraitItem(trait_item) => Annotatable::TraitItem(trait_item.map_attrs(f)),
64 Annotatable::ImplItem(impl_item) => Annotatable::ImplItem(impl_item.map_attrs(f)),
65 Annotatable::ForeignItem(foreign_item) =>
66 Annotatable::ForeignItem(foreign_item.map_attrs(f)),
67 Annotatable::Stmt(stmt) => Annotatable::Stmt(stmt.map_attrs(f)),
68 Annotatable::Expr(expr) => Annotatable::Expr(expr.map_attrs(f)),
74 pub fn span(&self) -> Span {
76 Annotatable::Item(ref item) => item.span,
77 Annotatable::TraitItem(ref trait_item) => trait_item.span,
78 Annotatable::ImplItem(ref impl_item) => impl_item.span,
79 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
80 Annotatable::Stmt(ref stmt) => stmt.span,
81 Annotatable::Expr(ref expr) => expr.span,
85 pub fn expect_item(self) -> P<ast::Item> {
87 Annotatable::Item(i) => i,
88 _ => panic!("expected Item")
92 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
93 where F: FnMut(P<ast::Item>) -> P<ast::Item>,
94 G: FnMut(Annotatable) -> Annotatable
97 Annotatable::Item(i) => Annotatable::Item(f(i)),
102 pub fn expect_trait_item(self) -> ast::TraitItem {
104 Annotatable::TraitItem(i) => i.into_inner(),
105 _ => panic!("expected Item")
109 pub fn expect_impl_item(self) -> ast::ImplItem {
111 Annotatable::ImplItem(i) => i.into_inner(),
112 _ => panic!("expected Item")
116 pub fn expect_foreign_item(self) -> ast::ForeignItem {
118 Annotatable::ForeignItem(i) => i.into_inner(),
119 _ => panic!("expected foreign item")
123 pub fn expect_stmt(self) -> ast::Stmt {
125 Annotatable::Stmt(stmt) => stmt.into_inner(),
126 _ => panic!("expected statement"),
130 pub fn expect_expr(self) -> P<ast::Expr> {
132 Annotatable::Expr(expr) => expr,
133 _ => panic!("expected expression"),
137 pub fn derive_allowed(&self) -> bool {
139 Annotatable::Item(ref item) => match item.node {
140 ast::ItemKind::Struct(..) |
141 ast::ItemKind::Enum(..) |
142 ast::ItemKind::Union(..) => true,
150 // A more flexible ItemDecorator.
151 pub trait MultiItemDecorator {
155 meta_item: &ast::MetaItem,
157 push: &mut dyn FnMut(Annotatable));
160 impl<F> MultiItemDecorator for F
161 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut dyn FnMut(Annotatable))
166 meta_item: &ast::MetaItem,
168 push: &mut dyn FnMut(Annotatable)) {
169 (*self)(ecx, sp, meta_item, item, push)
173 // `meta_item` is the annotation, and `item` is the item being modified.
174 // FIXME Decorators should follow the same pattern too.
175 pub trait MultiItemModifier {
179 meta_item: &ast::MetaItem,
184 impl<F, T> MultiItemModifier for F
185 where F: Fn(&mut ExtCtxt, Span, &ast::MetaItem, Annotatable) -> T,
186 T: Into<Vec<Annotatable>>,
191 meta_item: &ast::MetaItem,
193 -> Vec<Annotatable> {
194 (*self)(ecx, span, meta_item, item).into()
198 impl Into<Vec<Annotatable>> for Annotatable {
199 fn into(self) -> Vec<Annotatable> {
204 pub trait ProcMacro {
205 fn expand<'cx>(&self,
206 ecx: &'cx mut ExtCtxt,
212 impl<F> ProcMacro for F
213 where F: Fn(TokenStream) -> TokenStream
215 fn expand<'cx>(&self,
216 _ecx: &'cx mut ExtCtxt,
220 // FIXME setup implicit context in TLS before calling self.
225 pub trait AttrProcMacro {
226 fn expand<'cx>(&self,
227 ecx: &'cx mut ExtCtxt,
229 annotation: TokenStream,
230 annotated: TokenStream)
234 impl<F> AttrProcMacro for F
235 where F: Fn(TokenStream, TokenStream) -> TokenStream
237 fn expand<'cx>(&self,
238 _ecx: &'cx mut ExtCtxt,
240 annotation: TokenStream,
241 annotated: TokenStream)
243 // FIXME setup implicit context in TLS before calling self.
244 (*self)(annotation, annotated)
248 /// Represents a thing that maps token trees to Macro Results
249 pub trait TTMacroExpander {
250 fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream)
251 -> Box<dyn MacResult+'cx>;
254 pub type MacroExpanderFn =
255 for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
256 -> Box<dyn MacResult+'cx>;
258 impl<F> TTMacroExpander for F
259 where F: for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
260 -> Box<dyn MacResult+'cx>
262 fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream)
263 -> Box<dyn MacResult+'cx> {
264 struct AvoidInterpolatedIdents;
266 impl Folder for AvoidInterpolatedIdents {
267 fn fold_tt(&mut self, tt: tokenstream::TokenTree) -> tokenstream::TokenTree {
268 if let tokenstream::TokenTree::Token(_, token::Interpolated(ref nt)) = tt {
269 if let token::NtIdent(ident, is_raw) = nt.0 {
270 return tokenstream::TokenTree::Token(ident.span,
271 token::Ident(ident, is_raw));
274 fold::noop_fold_tt(tt, self)
277 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
278 fold::noop_fold_mac(mac, self)
283 input.trees().map(|tt| AvoidInterpolatedIdents.fold_tt(tt)).collect();
284 (*self)(ecx, span, &input)
288 pub trait IdentMacroExpander {
289 fn expand<'cx>(&self,
290 cx: &'cx mut ExtCtxt,
293 token_tree: Vec<tokenstream::TokenTree>)
294 -> Box<dyn MacResult+'cx>;
297 pub type IdentMacroExpanderFn =
298 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<tokenstream::TokenTree>)
299 -> Box<dyn MacResult+'cx>;
301 impl<F> IdentMacroExpander for F
302 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
303 Vec<tokenstream::TokenTree>) -> Box<dyn MacResult+'cx>
305 fn expand<'cx>(&self,
306 cx: &'cx mut ExtCtxt,
309 token_tree: Vec<tokenstream::TokenTree>)
310 -> Box<dyn MacResult+'cx>
312 (*self)(cx, sp, ident, token_tree)
316 // Use a macro because forwarding to a simple function has type system issues
317 macro_rules! make_stmts_default {
319 $me.make_expr().map(|e| smallvec![ast::Stmt {
320 id: ast::DUMMY_NODE_ID,
322 node: ast::StmtKind::Expr(e),
327 /// The result of a macro expansion. The return values of the various
328 /// methods are spliced into the AST at the callsite of the macro.
329 pub trait MacResult {
330 /// Create an expression.
331 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
334 /// Create zero or more items.
335 fn make_items(self: Box<Self>) -> Option<OneVector<P<ast::Item>>> {
339 /// Create zero or more impl items.
340 fn make_impl_items(self: Box<Self>) -> Option<OneVector<ast::ImplItem>> {
344 /// Create zero or more trait items.
345 fn make_trait_items(self: Box<Self>) -> Option<OneVector<ast::TraitItem>> {
349 /// Create zero or more items in an `extern {}` block
350 fn make_foreign_items(self: Box<Self>) -> Option<OneVector<ast::ForeignItem>> { None }
352 /// Create a pattern.
353 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
357 /// Create zero or more statements.
359 /// By default this attempts to create an expression statement,
360 /// returning None if that fails.
361 fn make_stmts(self: Box<Self>) -> Option<OneVector<ast::Stmt>> {
362 make_stmts_default!(self)
365 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
370 macro_rules! make_MacEager {
371 ( $( $fld:ident: $t:ty, )* ) => {
372 /// `MacResult` implementation for the common case where you've already
373 /// built each form of AST that you might return.
375 pub struct MacEager {
377 pub $fld: Option<$t>,
383 pub fn $fld(v: $t) -> Box<dyn MacResult> {
397 items: OneVector<P<ast::Item>>,
398 impl_items: OneVector<ast::ImplItem>,
399 trait_items: OneVector<ast::TraitItem>,
400 foreign_items: OneVector<ast::ForeignItem>,
401 stmts: OneVector<ast::Stmt>,
405 impl MacResult for MacEager {
406 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
410 fn make_items(self: Box<Self>) -> Option<OneVector<P<ast::Item>>> {
414 fn make_impl_items(self: Box<Self>) -> Option<OneVector<ast::ImplItem>> {
418 fn make_trait_items(self: Box<Self>) -> Option<OneVector<ast::TraitItem>> {
422 fn make_foreign_items(self: Box<Self>) -> Option<OneVector<ast::ForeignItem>> {
426 fn make_stmts(self: Box<Self>) -> Option<OneVector<ast::Stmt>> {
427 match self.stmts.as_ref().map_or(0, |s| s.len()) {
428 0 => make_stmts_default!(self),
433 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
434 if let Some(p) = self.pat {
437 if let Some(e) = self.expr {
438 if let ast::ExprKind::Lit(_) = e.node {
439 return Some(P(ast::Pat {
440 id: ast::DUMMY_NODE_ID,
442 node: PatKind::Lit(e),
449 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
454 /// Fill-in macro expansion result, to allow compilation to continue
455 /// after hitting errors.
456 #[derive(Copy, Clone)]
457 pub struct DummyResult {
463 /// Create a default MacResult that can be anything.
465 /// Use this as a return value after hitting any errors and
466 /// calling `span_err`.
467 pub fn any(sp: Span) -> Box<dyn MacResult+'static> {
468 Box::new(DummyResult { expr_only: false, span: sp })
471 /// Create a default MacResult that can only be an expression.
473 /// Use this for macros that must expand to an expression, so even
474 /// if an error is encountered internally, the user will receive
475 /// an error that they also used it in the wrong place.
476 pub fn expr(sp: Span) -> Box<dyn MacResult+'static> {
477 Box::new(DummyResult { expr_only: true, span: sp })
480 /// A plain dummy expression.
481 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
483 id: ast::DUMMY_NODE_ID,
484 node: ast::ExprKind::Lit(P(source_map::respan(sp, ast::LitKind::Bool(false)))),
486 attrs: ThinVec::new(),
490 /// A plain dummy pattern.
491 pub fn raw_pat(sp: Span) -> ast::Pat {
493 id: ast::DUMMY_NODE_ID,
499 pub fn raw_ty(sp: Span) -> P<ast::Ty> {
501 id: ast::DUMMY_NODE_ID,
502 node: ast::TyKind::Infer,
508 impl MacResult for DummyResult {
509 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
510 Some(DummyResult::raw_expr(self.span))
513 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
514 Some(P(DummyResult::raw_pat(self.span)))
517 fn make_items(self: Box<DummyResult>) -> Option<OneVector<P<ast::Item>>> {
518 // this code needs a comment... why not always just return the Some() ?
522 Some(OneVector::new())
526 fn make_impl_items(self: Box<DummyResult>) -> Option<OneVector<ast::ImplItem>> {
530 Some(OneVector::new())
534 fn make_trait_items(self: Box<DummyResult>) -> Option<OneVector<ast::TraitItem>> {
538 Some(OneVector::new())
542 fn make_foreign_items(self: Box<Self>) -> Option<OneVector<ast::ForeignItem>> {
546 Some(OneVector::new())
550 fn make_stmts(self: Box<DummyResult>) -> Option<OneVector<ast::Stmt>> {
551 Some(smallvec![ast::Stmt {
552 id: ast::DUMMY_NODE_ID,
553 node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span)),
558 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
559 Some(DummyResult::raw_ty(self.span))
563 pub type BuiltinDeriveFn =
564 for<'cx> fn(&'cx mut ExtCtxt, Span, &MetaItem, &Annotatable, &mut dyn FnMut(Annotatable));
566 /// Represents different kinds of macro invocations that can be resolved.
567 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
569 /// A bang macro - foo!()
571 /// An attribute macro - #[foo]
573 /// A derive attribute macro - #[derive(Foo)]
575 /// A view of a procedural macro from the same crate that defines it.
580 pub fn descr(self) -> &'static str {
582 MacroKind::Bang => "macro",
583 MacroKind::Attr => "attribute macro",
584 MacroKind::Derive => "derive macro",
585 MacroKind::ProcMacroStub => "crate-local procedural macro",
590 /// An enum representing the different kinds of syntax extensions.
591 pub enum SyntaxExtension {
592 /// A trivial "extension" that does nothing, only keeps the attribute and marks it as known.
593 NonMacroAttr { mark_used: bool },
595 /// A syntax extension that is attached to an item and creates new items
598 /// `#[derive(...)]` is a `MultiItemDecorator`.
600 /// Prefer ProcMacro or MultiModifier since they are more flexible.
601 MultiDecorator(Box<dyn MultiItemDecorator + sync::Sync + sync::Send>),
603 /// A syntax extension that is attached to an item and modifies it
604 /// in-place. Also allows decoration, i.e., creating new items.
605 MultiModifier(Box<dyn MultiItemModifier + sync::Sync + sync::Send>),
607 /// A function-like procedural macro. TokenStream -> TokenStream.
609 expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
610 allow_internal_unstable: bool,
614 /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
615 /// The first TokenSteam is the attribute, the second is the annotated item.
616 /// Allows modification of the input items and adding new items, similar to
617 /// MultiModifier, but uses TokenStreams, rather than AST nodes.
618 AttrProcMacro(Box<dyn AttrProcMacro + sync::Sync + sync::Send>, Edition),
620 /// A normal, function-like syntax extension.
622 /// `bytes!` is a `NormalTT`.
624 expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
625 def_info: Option<(ast::NodeId, Span)>,
626 /// Whether the contents of the macro can
627 /// directly use `#[unstable]` things (true == yes).
628 allow_internal_unstable: bool,
629 /// Whether the contents of the macro can use `unsafe`
630 /// without triggering the `unsafe_code` lint.
631 allow_internal_unsafe: bool,
632 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
633 /// for a given macro.
634 local_inner_macros: bool,
635 /// The macro's feature name if it is unstable, and the stability feature
636 unstable_feature: Option<(Symbol, u32)>,
637 /// Edition of the crate in which the macro is defined
641 /// A function-like syntax extension that has an extra ident before
644 IdentTT(Box<dyn IdentMacroExpander + sync::Sync + sync::Send>, Option<Span>, bool),
646 /// An attribute-like procedural macro. TokenStream -> TokenStream.
647 /// The input is the annotated item.
648 /// Allows generating code to implement a Trait for a given struct
650 ProcMacroDerive(Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
651 Vec<Symbol> /* inert attribute names */, Edition),
653 /// An attribute-like procedural macro that derives a builtin trait.
654 BuiltinDerive(BuiltinDeriveFn),
656 /// A declarative macro, e.g. `macro m() {}`.
658 expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
659 def_info: Option<(ast::NodeId, Span)>,
660 is_transparent: bool,
665 impl SyntaxExtension {
666 /// Return which kind of macro calls this syntax extension.
667 pub fn kind(&self) -> MacroKind {
669 SyntaxExtension::DeclMacro { .. } |
670 SyntaxExtension::NormalTT { .. } |
671 SyntaxExtension::IdentTT(..) |
672 SyntaxExtension::ProcMacro { .. } =>
674 SyntaxExtension::NonMacroAttr { .. } |
675 SyntaxExtension::MultiDecorator(..) |
676 SyntaxExtension::MultiModifier(..) |
677 SyntaxExtension::AttrProcMacro(..) =>
679 SyntaxExtension::ProcMacroDerive(..) |
680 SyntaxExtension::BuiltinDerive(..) =>
685 pub fn default_transparency(&self) -> Transparency {
687 SyntaxExtension::ProcMacro { .. } |
688 SyntaxExtension::AttrProcMacro(..) |
689 SyntaxExtension::ProcMacroDerive(..) |
690 SyntaxExtension::DeclMacro { is_transparent: false, .. } => Transparency::Opaque,
691 SyntaxExtension::DeclMacro { is_transparent: true, .. } => Transparency::Transparent,
692 _ => Transparency::SemiTransparent,
696 pub fn edition(&self) -> Edition {
698 SyntaxExtension::NormalTT { edition, .. } |
699 SyntaxExtension::DeclMacro { edition, .. } |
700 SyntaxExtension::ProcMacro { edition, .. } |
701 SyntaxExtension::AttrProcMacro(.., edition) |
702 SyntaxExtension::ProcMacroDerive(.., edition) => edition,
703 // Unstable legacy stuff
704 SyntaxExtension::NonMacroAttr { .. } |
705 SyntaxExtension::IdentTT(..) |
706 SyntaxExtension::MultiDecorator(..) |
707 SyntaxExtension::MultiModifier(..) |
708 SyntaxExtension::BuiltinDerive(..) => hygiene::default_edition(),
713 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
716 fn next_node_id(&mut self) -> ast::NodeId;
717 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
718 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item>;
719 fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool;
721 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
723 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
725 fn resolve_imports(&mut self);
726 // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
727 fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<Attribute>, allow_derive: bool)
728 -> Option<Attribute>;
730 fn resolve_macro_invocation(&mut self, invoc: &Invocation, scope: Mark, force: bool)
731 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
732 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, scope: Mark,
733 derives_in_scope: &[ast::Path], force: bool)
734 -> Result<Lrc<SyntaxExtension>, Determinacy>;
736 fn check_unused_macros(&self);
739 #[derive(Copy, Clone, PartialEq, Debug)]
740 pub enum Determinacy {
746 pub fn determined(determined: bool) -> Determinacy {
747 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
751 pub struct DummyResolver;
753 impl Resolver for DummyResolver {
754 fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
755 fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
756 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item }
757 fn is_whitelisted_legacy_custom_derive(&self, _name: Name) -> bool { false }
759 fn visit_ast_fragment_with_placeholders(&mut self, _invoc: Mark, _fragment: &AstFragment,
760 _derives: &[Mark]) {}
761 fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc<SyntaxExtension>) {}
763 fn resolve_imports(&mut self) {}
764 fn find_legacy_attr_invoc(&mut self, _attrs: &mut Vec<Attribute>, _allow_derive: bool)
765 -> Option<Attribute> { None }
766 fn resolve_macro_invocation(&mut self, _invoc: &Invocation, _scope: Mark, _force: bool)
767 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
768 Err(Determinacy::Determined)
770 fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _scope: Mark,
771 _derives_in_scope: &[ast::Path], _force: bool)
772 -> Result<Lrc<SyntaxExtension>, Determinacy> {
773 Err(Determinacy::Determined)
775 fn check_unused_macros(&self) {}
779 pub struct ModuleData {
780 pub mod_path: Vec<ast::Ident>,
781 pub directory: PathBuf,
785 pub struct ExpansionData {
788 pub module: Rc<ModuleData>,
789 pub directory_ownership: DirectoryOwnership,
790 pub crate_span: Option<Span>,
793 /// One of these is made during expansion and incrementally updated as we go;
794 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
795 /// -> expn_info` of their expansion context stored into their span.
796 pub struct ExtCtxt<'a> {
797 pub parse_sess: &'a parse::ParseSess,
798 pub ecfg: expand::ExpansionConfig<'a>,
799 pub root_path: PathBuf,
800 pub resolver: &'a mut dyn Resolver,
801 pub resolve_err_count: usize,
802 pub current_expansion: ExpansionData,
803 pub expansions: HashMap<Span, Vec<String>>,
806 impl<'a> ExtCtxt<'a> {
807 pub fn new(parse_sess: &'a parse::ParseSess,
808 ecfg: expand::ExpansionConfig<'a>,
809 resolver: &'a mut dyn Resolver)
814 root_path: PathBuf::new(),
816 resolve_err_count: 0,
817 current_expansion: ExpansionData {
820 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
821 directory_ownership: DirectoryOwnership::Owned { relative: None },
824 expansions: HashMap::new(),
828 /// Returns a `Folder` for deeply expanding all macros in an AST node.
829 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
830 expand::MacroExpander::new(self, false)
833 /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
834 /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
835 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
836 expand::MacroExpander::new(self, true)
839 pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
840 parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
842 pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
843 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
844 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
845 pub fn call_site(&self) -> Span {
846 match self.current_expansion.mark.expn_info() {
847 Some(expn_info) => expn_info.call_site,
851 pub fn backtrace(&self) -> SyntaxContext {
852 SyntaxContext::empty().apply_mark(self.current_expansion.mark)
855 /// Returns span for the macro which originally caused the current expansion to happen.
857 /// Stops backtracing at include! boundary.
858 pub fn expansion_cause(&self) -> Option<Span> {
859 let mut ctxt = self.backtrace();
860 let mut last_macro = None;
862 if ctxt.outer().expn_info().map_or(None, |info| {
863 if info.format.name() == "include" {
864 // Stop going up the backtrace once include! is encountered
867 ctxt = info.call_site.ctxt();
868 last_macro = Some(info.call_site);
877 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
880 -> DiagnosticBuilder<'a> {
881 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
883 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
886 -> DiagnosticBuilder<'a> {
887 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
889 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
892 -> DiagnosticBuilder<'a> {
893 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
896 /// Emit `msg` attached to `sp`, and stop compilation immediately.
898 /// `span_err` should be strongly preferred where-ever possible:
899 /// this should *only* be used when:
901 /// - continuing has a high risk of flow-on errors (e.g. errors in
902 /// declaring a macro would cause all uses of that macro to
903 /// complain about "undefined macro"), or
904 /// - there is literally nothing else that can be done (however,
905 /// in most cases one can construct a dummy expression/item to
906 /// substitute; we never hit resolve/type-checking so the dummy
907 /// value doesn't have to match anything)
908 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
909 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
912 /// Emit `msg` attached to `sp`, without immediately stopping
915 /// Compilation will be stopped in the near future (at the end of
916 /// the macro expansion phase).
917 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
918 self.parse_sess.span_diagnostic.span_err(sp, msg);
920 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
921 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
923 pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
924 -> DiagnosticBuilder<'a> {
925 self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
927 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
928 self.parse_sess.span_diagnostic.span_warn(sp, msg);
930 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
931 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
933 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
934 self.parse_sess.span_diagnostic.span_bug(sp, msg);
936 pub fn trace_macros_diag(&mut self) {
937 for (sp, notes) in self.expansions.iter() {
938 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
944 // Fixme: does this result in errors?
945 self.expansions.clear();
947 pub fn bug(&self, msg: &str) -> ! {
948 self.parse_sess.span_diagnostic.bug(msg);
950 pub fn trace_macros(&self) -> bool {
953 pub fn set_trace_macros(&mut self, x: bool) {
954 self.ecfg.trace_mac = x
956 pub fn ident_of(&self, st: &str) -> ast::Ident {
957 ast::Ident::from_str(st)
959 pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
960 let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
961 iter::once(Ident::new(keywords::DollarCrate.name(), def_site))
962 .chain(components.iter().map(|s| self.ident_of(s)))
965 pub fn name_of(&self, st: &str) -> ast::Name {
969 pub fn check_unused_macros(&self) {
970 self.resolver.check_unused_macros();
974 /// Extract a string literal from the macro expanded version of `expr`,
975 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
976 /// compilation on error, merely emits a non-fatal error and returns None.
977 pub fn expr_to_spanned_string<'a>(
981 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, DiagnosticBuilder<'a>> {
982 // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
983 let expr = expr.map(|mut expr| {
984 expr.span = expr.span.apply_mark(cx.current_expansion.mark);
988 // we want to be able to handle e.g. `concat!("foo", "bar")`
989 let expr = cx.expander().fold_expr(expr);
990 Err(match expr.node {
991 ast::ExprKind::Lit(ref l) => match l.node {
992 ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
993 _ => cx.struct_span_err(l.span, err_msg)
995 _ => cx.struct_span_err(expr.span, err_msg)
999 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
1000 -> Option<(Symbol, ast::StrStyle)> {
1001 expr_to_spanned_string(cx, expr, err_msg)
1002 .map_err(|mut err| err.emit())
1007 /// Non-fatally assert that `tts` is empty. Note that this function
1008 /// returns even when `tts` is non-empty, macros that *need* to stop
1009 /// compilation should call
1010 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1011 /// done as rarely as possible).
1012 pub fn check_zero_tts(cx: &ExtCtxt,
1014 tts: &[tokenstream::TokenTree],
1016 if !tts.is_empty() {
1017 cx.span_err(sp, &format!("{} takes no arguments", name));
1021 /// Interpreting `tts` as a comma-separated sequence of expressions,
1022 /// expect exactly one string literal, or emit an error and return None.
1023 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
1025 tts: &[tokenstream::TokenTree],
1028 let mut p = cx.new_parser_from_tts(tts);
1029 if p.token == token::Eof {
1030 cx.span_err(sp, &format!("{} takes 1 argument", name));
1033 let ret = panictry!(p.parse_expr());
1034 let _ = p.eat(&token::Comma);
1036 if p.token != token::Eof {
1037 cx.span_err(sp, &format!("{} takes 1 argument", name));
1039 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1044 /// Extract comma-separated expressions from `tts`. If there is a
1045 /// parsing error, emit a non-fatal error and return None.
1046 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
1048 tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
1049 let mut p = cx.new_parser_from_tts(tts);
1050 let mut es = Vec::new();
1051 while p.token != token::Eof {
1052 es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
1053 if p.eat(&token::Comma) {
1056 if p.token != token::Eof {
1057 cx.span_err(sp, "expected token: `,`");