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;
735 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item>;
737 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
739 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
741 fn resolve_imports(&mut self);
743 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
744 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
745 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
746 derives_in_scope: Vec<ast::Path>, force: bool)
747 -> Result<Lrc<SyntaxExtension>, Determinacy>;
749 fn check_unused_macros(&self);
752 #[derive(Copy, Clone, PartialEq, Debug)]
753 pub enum Determinacy {
759 pub fn determined(determined: bool) -> Determinacy {
760 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
764 pub struct DummyResolver;
766 impl Resolver for DummyResolver {
767 fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
768 fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
769 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item }
771 fn visit_ast_fragment_with_placeholders(&mut self, _invoc: Mark, _fragment: &AstFragment,
772 _derives: &[Mark]) {}
773 fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc<SyntaxExtension>) {}
775 fn resolve_imports(&mut self) {}
776 fn resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
777 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
778 Err(Determinacy::Determined)
780 fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
781 _derives_in_scope: Vec<ast::Path>, _force: bool)
782 -> Result<Lrc<SyntaxExtension>, Determinacy> {
783 Err(Determinacy::Determined)
785 fn check_unused_macros(&self) {}
789 pub struct ModuleData {
790 pub mod_path: Vec<ast::Ident>,
791 pub directory: PathBuf,
795 pub struct ExpansionData {
798 pub module: Rc<ModuleData>,
799 pub directory_ownership: DirectoryOwnership,
800 pub crate_span: Option<Span>,
803 /// One of these is made during expansion and incrementally updated as we go;
804 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
805 /// -> expn_info` of their expansion context stored into their span.
806 pub struct ExtCtxt<'a> {
807 pub parse_sess: &'a parse::ParseSess,
808 pub ecfg: expand::ExpansionConfig<'a>,
809 pub root_path: PathBuf,
810 pub resolver: &'a mut dyn Resolver,
811 pub resolve_err_count: usize,
812 pub current_expansion: ExpansionData,
813 pub expansions: FxHashMap<Span, Vec<String>>,
816 impl<'a> ExtCtxt<'a> {
817 pub fn new(parse_sess: &'a parse::ParseSess,
818 ecfg: expand::ExpansionConfig<'a>,
819 resolver: &'a mut dyn Resolver)
824 root_path: PathBuf::new(),
826 resolve_err_count: 0,
827 current_expansion: ExpansionData {
830 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
831 directory_ownership: DirectoryOwnership::Owned { relative: None },
834 expansions: FxHashMap::default(),
838 /// Returns a `Folder` for deeply expanding all macros in an AST node.
839 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
840 expand::MacroExpander::new(self, false)
843 /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
844 /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
845 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
846 expand::MacroExpander::new(self, true)
849 pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
850 parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
852 pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
853 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
854 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
855 pub fn call_site(&self) -> Span {
856 match self.current_expansion.mark.expn_info() {
857 Some(expn_info) => expn_info.call_site,
861 pub fn backtrace(&self) -> SyntaxContext {
862 SyntaxContext::empty().apply_mark(self.current_expansion.mark)
865 /// Returns span for the macro which originally caused the current expansion to happen.
867 /// Stops backtracing at include! boundary.
868 pub fn expansion_cause(&self) -> Option<Span> {
869 let mut ctxt = self.backtrace();
870 let mut last_macro = None;
872 if ctxt.outer().expn_info().map_or(None, |info| {
873 if info.format.name() == "include" {
874 // Stop going up the backtrace once include! is encountered
877 ctxt = info.call_site.ctxt();
878 last_macro = Some(info.call_site);
887 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
890 -> DiagnosticBuilder<'a> {
891 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
893 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
896 -> DiagnosticBuilder<'a> {
897 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
899 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
902 -> DiagnosticBuilder<'a> {
903 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
906 /// Emit `msg` attached to `sp`, and stop compilation immediately.
908 /// `span_err` should be strongly preferred where-ever possible:
909 /// this should *only* be used when:
911 /// - continuing has a high risk of flow-on errors (e.g. errors in
912 /// declaring a macro would cause all uses of that macro to
913 /// complain about "undefined macro"), or
914 /// - there is literally nothing else that can be done (however,
915 /// in most cases one can construct a dummy expression/item to
916 /// substitute; we never hit resolve/type-checking so the dummy
917 /// value doesn't have to match anything)
918 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
919 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
922 /// Emit `msg` attached to `sp`, without immediately stopping
925 /// Compilation will be stopped in the near future (at the end of
926 /// the macro expansion phase).
927 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
928 self.parse_sess.span_diagnostic.span_err(sp, msg);
930 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
931 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
933 pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
934 -> DiagnosticBuilder<'a> {
935 self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
937 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
938 self.parse_sess.span_diagnostic.span_warn(sp, msg);
940 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
941 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
943 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
944 self.parse_sess.span_diagnostic.span_bug(sp, msg);
946 pub fn trace_macros_diag(&mut self) {
947 for (sp, notes) in self.expansions.iter() {
948 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
954 // Fixme: does this result in errors?
955 self.expansions.clear();
957 pub fn bug(&self, msg: &str) -> ! {
958 self.parse_sess.span_diagnostic.bug(msg);
960 pub fn trace_macros(&self) -> bool {
963 pub fn set_trace_macros(&mut self, x: bool) {
964 self.ecfg.trace_mac = x
966 pub fn ident_of(&self, st: &str) -> ast::Ident {
967 ast::Ident::from_str(st)
969 pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
970 let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
971 iter::once(Ident::new(keywords::DollarCrate.name(), def_site))
972 .chain(components.iter().map(|s| self.ident_of(s)))
975 pub fn name_of(&self, st: &str) -> ast::Name {
979 pub fn check_unused_macros(&self) {
980 self.resolver.check_unused_macros();
984 /// Extract a string literal from the macro expanded version of `expr`,
985 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
986 /// compilation on error, merely emits a non-fatal error and returns None.
987 pub fn expr_to_spanned_string<'a>(
991 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, DiagnosticBuilder<'a>> {
992 // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
993 let expr = expr.map(|mut expr| {
994 expr.span = expr.span.apply_mark(cx.current_expansion.mark);
998 // we want to be able to handle e.g. `concat!("foo", "bar")`
999 let expr = cx.expander().fold_expr(expr);
1000 Err(match expr.node {
1001 ast::ExprKind::Lit(ref l) => match l.node {
1002 ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
1003 _ => cx.struct_span_err(l.span, err_msg)
1005 _ => cx.struct_span_err(expr.span, err_msg)
1009 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
1010 -> Option<(Symbol, ast::StrStyle)> {
1011 expr_to_spanned_string(cx, expr, err_msg)
1012 .map_err(|mut err| err.emit())
1017 /// Non-fatally assert that `tts` is empty. Note that this function
1018 /// returns even when `tts` is non-empty, macros that *need* to stop
1019 /// compilation should call
1020 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1021 /// done as rarely as possible).
1022 pub fn check_zero_tts(cx: &ExtCtxt,
1024 tts: &[tokenstream::TokenTree],
1026 if !tts.is_empty() {
1027 cx.span_err(sp, &format!("{} takes no arguments", name));
1031 /// Interpreting `tts` as a comma-separated sequence of expressions,
1032 /// expect exactly one string literal, or emit an error and return None.
1033 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
1035 tts: &[tokenstream::TokenTree],
1038 let mut p = cx.new_parser_from_tts(tts);
1039 if p.token == token::Eof {
1040 cx.span_err(sp, &format!("{} takes 1 argument", name));
1043 let ret = panictry!(p.parse_expr());
1044 let _ = p.eat(&token::Comma);
1046 if p.token != token::Eof {
1047 cx.span_err(sp, &format!("{} takes 1 argument", name));
1049 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1054 /// Extract comma-separated expressions from `tts`. If there is a
1055 /// parsing error, emit a non-fatal error and return None.
1056 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
1058 tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
1059 let mut p = cx.new_parser_from_tts(tts);
1060 let mut es = Vec::new();
1061 while p.token != token::Eof {
1062 es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
1063 if p.eat(&token::Comma) {
1066 if p.token != token::Eof {
1067 cx.span_err(sp, "expected token: `,`");