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};
25 use smallvec::SmallVec;
26 use symbol::{keywords, Ident, Symbol};
29 use rustc_data_structures::fx::FxHashMap;
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 {
252 ecx: &'cx mut ExtCtxt,
255 def_span: Option<Span>,
256 ) -> Box<dyn MacResult+'cx>;
259 pub type MacroExpanderFn =
260 for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
261 -> Box<dyn MacResult+'cx>;
263 impl<F> TTMacroExpander for F
264 where F: for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
265 -> Box<dyn MacResult+'cx>
269 ecx: &'cx mut ExtCtxt,
272 _def_span: Option<Span>,
273 ) -> Box<dyn MacResult+'cx> {
274 struct AvoidInterpolatedIdents;
276 impl Folder for AvoidInterpolatedIdents {
277 fn fold_tt(&mut self, tt: tokenstream::TokenTree) -> tokenstream::TokenTree {
278 if let tokenstream::TokenTree::Token(_, token::Interpolated(ref nt)) = tt {
279 if let token::NtIdent(ident, is_raw) = nt.0 {
280 return tokenstream::TokenTree::Token(ident.span,
281 token::Ident(ident, is_raw));
284 fold::noop_fold_tt(tt, self)
287 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
288 fold::noop_fold_mac(mac, self)
293 input.trees().map(|tt| AvoidInterpolatedIdents.fold_tt(tt)).collect();
294 (*self)(ecx, span, &input)
298 pub trait IdentMacroExpander {
299 fn expand<'cx>(&self,
300 cx: &'cx mut ExtCtxt,
303 token_tree: Vec<tokenstream::TokenTree>)
304 -> Box<dyn MacResult+'cx>;
307 pub type IdentMacroExpanderFn =
308 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<tokenstream::TokenTree>)
309 -> Box<dyn MacResult+'cx>;
311 impl<F> IdentMacroExpander for F
312 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
313 Vec<tokenstream::TokenTree>) -> Box<dyn MacResult+'cx>
315 fn expand<'cx>(&self,
316 cx: &'cx mut ExtCtxt,
319 token_tree: Vec<tokenstream::TokenTree>)
320 -> Box<dyn MacResult+'cx>
322 (*self)(cx, sp, ident, token_tree)
326 // Use a macro because forwarding to a simple function has type system issues
327 macro_rules! make_stmts_default {
329 $me.make_expr().map(|e| smallvec![ast::Stmt {
330 id: ast::DUMMY_NODE_ID,
332 node: ast::StmtKind::Expr(e),
337 /// The result of a macro expansion. The return values of the various
338 /// methods are spliced into the AST at the callsite of the macro.
339 pub trait MacResult {
340 /// Create an expression.
341 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
344 /// Create zero or more items.
345 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
349 /// Create zero or more impl items.
350 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
354 /// Create zero or more trait items.
355 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
359 /// Create zero or more items in an `extern {}` block
360 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None }
362 /// Create a pattern.
363 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
367 /// Create zero or more statements.
369 /// By default this attempts to create an expression statement,
370 /// returning None if that fails.
371 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
372 make_stmts_default!(self)
375 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
380 macro_rules! make_MacEager {
381 ( $( $fld:ident: $t:ty, )* ) => {
382 /// `MacResult` implementation for the common case where you've already
383 /// built each form of AST that you might return.
385 pub struct MacEager {
387 pub $fld: Option<$t>,
393 pub fn $fld(v: $t) -> Box<dyn MacResult> {
407 items: SmallVec<[P<ast::Item>; 1]>,
408 impl_items: SmallVec<[ast::ImplItem; 1]>,
409 trait_items: SmallVec<[ast::TraitItem; 1]>,
410 foreign_items: SmallVec<[ast::ForeignItem; 1]>,
411 stmts: SmallVec<[ast::Stmt; 1]>,
415 impl MacResult for MacEager {
416 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
420 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
424 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
428 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
432 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
436 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
437 match self.stmts.as_ref().map_or(0, |s| s.len()) {
438 0 => make_stmts_default!(self),
443 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
444 if let Some(p) = self.pat {
447 if let Some(e) = self.expr {
448 if let ast::ExprKind::Lit(_) = e.node {
449 return Some(P(ast::Pat {
450 id: ast::DUMMY_NODE_ID,
452 node: PatKind::Lit(e),
459 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
464 /// Fill-in macro expansion result, to allow compilation to continue
465 /// after hitting errors.
466 #[derive(Copy, Clone)]
467 pub struct DummyResult {
473 /// Create a default MacResult that can be anything.
475 /// Use this as a return value after hitting any errors and
476 /// calling `span_err`.
477 pub fn any(sp: Span) -> Box<dyn MacResult+'static> {
478 Box::new(DummyResult { expr_only: false, span: sp })
481 /// Create a default MacResult that can only be an expression.
483 /// Use this for macros that must expand to an expression, so even
484 /// if an error is encountered internally, the user will receive
485 /// an error that they also used it in the wrong place.
486 pub fn expr(sp: Span) -> Box<dyn MacResult+'static> {
487 Box::new(DummyResult { expr_only: true, span: sp })
490 /// A plain dummy expression.
491 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
493 id: ast::DUMMY_NODE_ID,
494 node: ast::ExprKind::Lit(source_map::respan(sp, ast::LitKind::Bool(false))),
496 attrs: ThinVec::new(),
500 /// A plain dummy pattern.
501 pub fn raw_pat(sp: Span) -> ast::Pat {
503 id: ast::DUMMY_NODE_ID,
509 pub fn raw_ty(sp: Span) -> P<ast::Ty> {
511 id: ast::DUMMY_NODE_ID,
512 node: ast::TyKind::Infer,
518 impl MacResult for DummyResult {
519 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
520 Some(DummyResult::raw_expr(self.span))
523 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
524 Some(P(DummyResult::raw_pat(self.span)))
527 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
528 // this code needs a comment... why not always just return the Some() ?
532 Some(SmallVec::new())
536 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
540 Some(SmallVec::new())
544 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
548 Some(SmallVec::new())
552 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
556 Some(SmallVec::new())
560 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
561 Some(smallvec![ast::Stmt {
562 id: ast::DUMMY_NODE_ID,
563 node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span)),
568 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
569 Some(DummyResult::raw_ty(self.span))
573 pub type BuiltinDeriveFn =
574 for<'cx> fn(&'cx mut ExtCtxt, Span, &MetaItem, &Annotatable, &mut dyn FnMut(Annotatable));
576 /// Represents different kinds of macro invocations that can be resolved.
577 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
579 /// A bang macro - foo!()
581 /// An attribute macro - #[foo]
583 /// A derive attribute macro - #[derive(Foo)]
585 /// A view of a procedural macro from the same crate that defines it.
590 pub fn descr(self) -> &'static str {
592 MacroKind::Bang => "macro",
593 MacroKind::Attr => "attribute macro",
594 MacroKind::Derive => "derive macro",
595 MacroKind::ProcMacroStub => "crate-local procedural macro",
599 pub fn article(self) -> &'static str {
601 MacroKind::Attr => "an",
607 /// An enum representing the different kinds of syntax extensions.
608 pub enum SyntaxExtension {
609 /// A trivial "extension" that does nothing, only keeps the attribute and marks it as known.
610 NonMacroAttr { mark_used: bool },
612 /// A syntax extension that is attached to an item and creates new items
615 /// `#[derive(...)]` is a `MultiItemDecorator`.
617 /// Prefer ProcMacro or MultiModifier since they are more flexible.
618 MultiDecorator(Box<dyn MultiItemDecorator + sync::Sync + sync::Send>),
620 /// A syntax extension that is attached to an item and modifies it
621 /// in-place. Also allows decoration, i.e., creating new items.
622 MultiModifier(Box<dyn MultiItemModifier + sync::Sync + sync::Send>),
624 /// A function-like procedural macro. TokenStream -> TokenStream.
626 expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
627 allow_internal_unstable: bool,
631 /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
632 /// The first TokenSteam is the attribute, the second is the annotated item.
633 /// Allows modification of the input items and adding new items, similar to
634 /// MultiModifier, but uses TokenStreams, rather than AST nodes.
635 AttrProcMacro(Box<dyn AttrProcMacro + sync::Sync + sync::Send>, Edition),
637 /// A normal, function-like syntax extension.
639 /// `bytes!` is a `NormalTT`.
641 expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
642 def_info: Option<(ast::NodeId, Span)>,
643 /// Whether the contents of the macro can
644 /// directly use `#[unstable]` things (true == yes).
645 allow_internal_unstable: bool,
646 /// Whether the contents of the macro can use `unsafe`
647 /// without triggering the `unsafe_code` lint.
648 allow_internal_unsafe: bool,
649 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
650 /// for a given macro.
651 local_inner_macros: bool,
652 /// The macro's feature name if it is unstable, and the stability feature
653 unstable_feature: Option<(Symbol, u32)>,
654 /// Edition of the crate in which the macro is defined
658 /// A function-like syntax extension that has an extra ident before
661 IdentTT(Box<dyn IdentMacroExpander + sync::Sync + sync::Send>, Option<Span>, bool),
663 /// An attribute-like procedural macro. TokenStream -> TokenStream.
664 /// The input is the annotated item.
665 /// Allows generating code to implement a Trait for a given struct
667 ProcMacroDerive(Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
668 Vec<Symbol> /* inert attribute names */, Edition),
670 /// An attribute-like procedural macro that derives a builtin trait.
671 BuiltinDerive(BuiltinDeriveFn),
673 /// A declarative macro, e.g., `macro m() {}`.
675 expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
676 def_info: Option<(ast::NodeId, Span)>,
677 is_transparent: bool,
682 impl SyntaxExtension {
683 /// Return which kind of macro calls this syntax extension.
684 pub fn kind(&self) -> MacroKind {
686 SyntaxExtension::DeclMacro { .. } |
687 SyntaxExtension::NormalTT { .. } |
688 SyntaxExtension::IdentTT(..) |
689 SyntaxExtension::ProcMacro { .. } =>
691 SyntaxExtension::NonMacroAttr { .. } |
692 SyntaxExtension::MultiDecorator(..) |
693 SyntaxExtension::MultiModifier(..) |
694 SyntaxExtension::AttrProcMacro(..) =>
696 SyntaxExtension::ProcMacroDerive(..) |
697 SyntaxExtension::BuiltinDerive(..) =>
702 pub fn default_transparency(&self) -> Transparency {
704 SyntaxExtension::ProcMacro { .. } |
705 SyntaxExtension::AttrProcMacro(..) |
706 SyntaxExtension::ProcMacroDerive(..) |
707 SyntaxExtension::DeclMacro { is_transparent: false, .. } => Transparency::Opaque,
708 SyntaxExtension::DeclMacro { is_transparent: true, .. } => Transparency::Transparent,
709 _ => Transparency::SemiTransparent,
713 pub fn edition(&self) -> Edition {
715 SyntaxExtension::NormalTT { edition, .. } |
716 SyntaxExtension::DeclMacro { edition, .. } |
717 SyntaxExtension::ProcMacro { edition, .. } |
718 SyntaxExtension::AttrProcMacro(.., edition) |
719 SyntaxExtension::ProcMacroDerive(.., edition) => edition,
720 // Unstable legacy stuff
721 SyntaxExtension::NonMacroAttr { .. } |
722 SyntaxExtension::IdentTT(..) |
723 SyntaxExtension::MultiDecorator(..) |
724 SyntaxExtension::MultiModifier(..) |
725 SyntaxExtension::BuiltinDerive(..) => hygiene::default_edition(),
730 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
733 fn next_node_id(&mut self) -> ast::NodeId;
734 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
736 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
738 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
740 fn resolve_imports(&mut self);
742 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
743 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
744 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
745 derives_in_scope: Vec<ast::Path>, force: bool)
746 -> Result<Lrc<SyntaxExtension>, Determinacy>;
748 fn check_unused_macros(&self);
751 #[derive(Copy, Clone, PartialEq, Debug)]
752 pub enum Determinacy {
758 pub fn determined(determined: bool) -> Determinacy {
759 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
763 pub struct DummyResolver;
765 impl Resolver for DummyResolver {
766 fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
767 fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
769 fn visit_ast_fragment_with_placeholders(&mut self, _invoc: Mark, _fragment: &AstFragment,
770 _derives: &[Mark]) {}
771 fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc<SyntaxExtension>) {}
773 fn resolve_imports(&mut self) {}
774 fn resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
775 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
776 Err(Determinacy::Determined)
778 fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
779 _derives_in_scope: Vec<ast::Path>, _force: bool)
780 -> Result<Lrc<SyntaxExtension>, Determinacy> {
781 Err(Determinacy::Determined)
783 fn check_unused_macros(&self) {}
787 pub struct ModuleData {
788 pub mod_path: Vec<ast::Ident>,
789 pub directory: PathBuf,
793 pub struct ExpansionData {
796 pub module: Rc<ModuleData>,
797 pub directory_ownership: DirectoryOwnership,
798 pub crate_span: Option<Span>,
801 /// One of these is made during expansion and incrementally updated as we go;
802 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
803 /// -> expn_info` of their expansion context stored into their span.
804 pub struct ExtCtxt<'a> {
805 pub parse_sess: &'a parse::ParseSess,
806 pub ecfg: expand::ExpansionConfig<'a>,
807 pub root_path: PathBuf,
808 pub resolver: &'a mut dyn Resolver,
809 pub resolve_err_count: usize,
810 pub current_expansion: ExpansionData,
811 pub expansions: FxHashMap<Span, Vec<String>>,
814 impl<'a> ExtCtxt<'a> {
815 pub fn new(parse_sess: &'a parse::ParseSess,
816 ecfg: expand::ExpansionConfig<'a>,
817 resolver: &'a mut dyn Resolver)
822 root_path: PathBuf::new(),
824 resolve_err_count: 0,
825 current_expansion: ExpansionData {
828 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
829 directory_ownership: DirectoryOwnership::Owned { relative: None },
832 expansions: FxHashMap::default(),
836 /// Returns a `Folder` for deeply expanding all macros in an AST node.
837 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
838 expand::MacroExpander::new(self, false)
841 /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
842 /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
843 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
844 expand::MacroExpander::new(self, true)
847 pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
848 parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
850 pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
851 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
852 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
853 pub fn call_site(&self) -> Span {
854 match self.current_expansion.mark.expn_info() {
855 Some(expn_info) => expn_info.call_site,
859 pub fn backtrace(&self) -> SyntaxContext {
860 SyntaxContext::empty().apply_mark(self.current_expansion.mark)
863 /// Returns span for the macro which originally caused the current expansion to happen.
865 /// Stops backtracing at include! boundary.
866 pub fn expansion_cause(&self) -> Option<Span> {
867 let mut ctxt = self.backtrace();
868 let mut last_macro = None;
870 if ctxt.outer().expn_info().map_or(None, |info| {
871 if info.format.name() == "include" {
872 // Stop going up the backtrace once include! is encountered
875 ctxt = info.call_site.ctxt();
876 last_macro = Some(info.call_site);
885 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
888 -> DiagnosticBuilder<'a> {
889 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
891 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
894 -> DiagnosticBuilder<'a> {
895 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
897 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
900 -> DiagnosticBuilder<'a> {
901 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
904 /// Emit `msg` attached to `sp`, and stop compilation immediately.
906 /// `span_err` should be strongly preferred where-ever possible:
907 /// this should *only* be used when:
909 /// - continuing has a high risk of flow-on errors (e.g., errors in
910 /// declaring a macro would cause all uses of that macro to
911 /// complain about "undefined macro"), or
912 /// - there is literally nothing else that can be done (however,
913 /// in most cases one can construct a dummy expression/item to
914 /// substitute; we never hit resolve/type-checking so the dummy
915 /// value doesn't have to match anything)
916 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
917 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
920 /// Emit `msg` attached to `sp`, without immediately stopping
923 /// Compilation will be stopped in the near future (at the end of
924 /// the macro expansion phase).
925 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
926 self.parse_sess.span_diagnostic.span_err(sp, msg);
928 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
929 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
931 pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
932 -> DiagnosticBuilder<'a> {
933 self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
935 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
936 self.parse_sess.span_diagnostic.span_warn(sp, msg);
938 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
939 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
941 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
942 self.parse_sess.span_diagnostic.span_bug(sp, msg);
944 pub fn trace_macros_diag(&mut self) {
945 for (sp, notes) in self.expansions.iter() {
946 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
952 // Fixme: does this result in errors?
953 self.expansions.clear();
955 pub fn bug(&self, msg: &str) -> ! {
956 self.parse_sess.span_diagnostic.bug(msg);
958 pub fn trace_macros(&self) -> bool {
961 pub fn set_trace_macros(&mut self, x: bool) {
962 self.ecfg.trace_mac = x
964 pub fn ident_of(&self, st: &str) -> ast::Ident {
965 ast::Ident::from_str(st)
967 pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
968 let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
969 iter::once(Ident::new(keywords::DollarCrate.name(), def_site))
970 .chain(components.iter().map(|s| self.ident_of(s)))
973 pub fn name_of(&self, st: &str) -> ast::Name {
977 pub fn check_unused_macros(&self) {
978 self.resolver.check_unused_macros();
982 /// Extract a string literal from the macro expanded version of `expr`,
983 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
984 /// compilation on error, merely emits a non-fatal error and returns None.
985 pub fn expr_to_spanned_string<'a>(
989 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, DiagnosticBuilder<'a>> {
990 // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
991 let expr = expr.map(|mut expr| {
992 expr.span = expr.span.apply_mark(cx.current_expansion.mark);
996 // we want to be able to handle e.g., `concat!("foo", "bar")`
997 let expr = cx.expander().fold_expr(expr);
998 Err(match expr.node {
999 ast::ExprKind::Lit(ref l) => match l.node {
1000 ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
1001 _ => cx.struct_span_err(l.span, err_msg)
1003 _ => cx.struct_span_err(expr.span, err_msg)
1007 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
1008 -> Option<(Symbol, ast::StrStyle)> {
1009 expr_to_spanned_string(cx, expr, err_msg)
1010 .map_err(|mut err| err.emit())
1015 /// Non-fatally assert that `tts` is empty. Note that this function
1016 /// returns even when `tts` is non-empty, macros that *need* to stop
1017 /// compilation should call
1018 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1019 /// done as rarely as possible).
1020 pub fn check_zero_tts(cx: &ExtCtxt,
1022 tts: &[tokenstream::TokenTree],
1024 if !tts.is_empty() {
1025 cx.span_err(sp, &format!("{} takes no arguments", name));
1029 /// Interpreting `tts` as a comma-separated sequence of expressions,
1030 /// expect exactly one string literal, or emit an error and return None.
1031 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
1033 tts: &[tokenstream::TokenTree],
1036 let mut p = cx.new_parser_from_tts(tts);
1037 if p.token == token::Eof {
1038 cx.span_err(sp, &format!("{} takes 1 argument", name));
1041 let ret = panictry!(p.parse_expr());
1042 let _ = p.eat(&token::Comma);
1044 if p.token != token::Eof {
1045 cx.span_err(sp, &format!("{} takes 1 argument", name));
1047 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1052 /// Extract comma-separated expressions from `tts`. If there is a
1053 /// parsing error, emit a non-fatal error and return None.
1054 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
1056 tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
1057 let mut p = cx.new_parser_from_tts(tts);
1058 let mut es = Vec::new();
1059 while p.token != token::Eof {
1060 es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
1061 if p.eat(&token::Comma) {
1064 if p.token != token::Eof {
1065 cx.span_err(sp, "expected token: `,`");