1 pub use self::SyntaxExtension::*;
3 use ast::{self, Attribute, Name, PatKind, MetaItem};
5 use source_map::{self, SourceMap, Spanned, respan};
6 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
8 use errors::{DiagnosticBuilder, DiagnosticId};
9 use ext::expand::{self, AstFragment, Invocation};
10 use ext::hygiene::{self, Mark, SyntaxContext, Transparency};
11 use fold::{self, Folder};
12 use parse::{self, parser, DirectoryOwnership};
15 use smallvec::SmallVec;
16 use symbol::{keywords, Ident, Symbol};
19 use rustc_data_structures::fx::FxHashMap;
21 use std::path::PathBuf;
23 use rustc_data_structures::sync::{self, Lrc};
24 use std::default::Default;
25 use tokenstream::{self, TokenStream};
28 #[derive(Debug,Clone)]
29 pub enum Annotatable {
31 TraitItem(P<ast::TraitItem>),
32 ImplItem(P<ast::ImplItem>),
33 ForeignItem(P<ast::ForeignItem>),
38 impl HasAttrs for Annotatable {
39 fn attrs(&self) -> &[Attribute] {
41 Annotatable::Item(ref item) => &item.attrs,
42 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
43 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
44 Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
45 Annotatable::Stmt(ref stmt) => stmt.attrs(),
46 Annotatable::Expr(ref expr) => &expr.attrs,
50 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
52 Annotatable::Item(item) => Annotatable::Item(item.map_attrs(f)),
53 Annotatable::TraitItem(trait_item) => Annotatable::TraitItem(trait_item.map_attrs(f)),
54 Annotatable::ImplItem(impl_item) => Annotatable::ImplItem(impl_item.map_attrs(f)),
55 Annotatable::ForeignItem(foreign_item) =>
56 Annotatable::ForeignItem(foreign_item.map_attrs(f)),
57 Annotatable::Stmt(stmt) => Annotatable::Stmt(stmt.map_attrs(f)),
58 Annotatable::Expr(expr) => Annotatable::Expr(expr.map_attrs(f)),
64 pub fn span(&self) -> Span {
66 Annotatable::Item(ref item) => item.span,
67 Annotatable::TraitItem(ref trait_item) => trait_item.span,
68 Annotatable::ImplItem(ref impl_item) => impl_item.span,
69 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
70 Annotatable::Stmt(ref stmt) => stmt.span,
71 Annotatable::Expr(ref expr) => expr.span,
75 pub fn expect_item(self) -> P<ast::Item> {
77 Annotatable::Item(i) => i,
78 _ => panic!("expected Item")
82 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
83 where F: FnMut(P<ast::Item>) -> P<ast::Item>,
84 G: FnMut(Annotatable) -> Annotatable
87 Annotatable::Item(i) => Annotatable::Item(f(i)),
92 pub fn expect_trait_item(self) -> ast::TraitItem {
94 Annotatable::TraitItem(i) => i.into_inner(),
95 _ => panic!("expected Item")
99 pub fn expect_impl_item(self) -> ast::ImplItem {
101 Annotatable::ImplItem(i) => i.into_inner(),
102 _ => panic!("expected Item")
106 pub fn expect_foreign_item(self) -> ast::ForeignItem {
108 Annotatable::ForeignItem(i) => i.into_inner(),
109 _ => panic!("expected foreign item")
113 pub fn expect_stmt(self) -> ast::Stmt {
115 Annotatable::Stmt(stmt) => stmt.into_inner(),
116 _ => panic!("expected statement"),
120 pub fn expect_expr(self) -> P<ast::Expr> {
122 Annotatable::Expr(expr) => expr,
123 _ => panic!("expected expression"),
127 pub fn derive_allowed(&self) -> bool {
129 Annotatable::Item(ref item) => match item.node {
130 ast::ItemKind::Struct(..) |
131 ast::ItemKind::Enum(..) |
132 ast::ItemKind::Union(..) => true,
140 // A more flexible ItemDecorator.
141 pub trait MultiItemDecorator {
145 meta_item: &ast::MetaItem,
147 push: &mut dyn FnMut(Annotatable));
150 impl<F> MultiItemDecorator for F
151 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut dyn FnMut(Annotatable))
156 meta_item: &ast::MetaItem,
158 push: &mut dyn FnMut(Annotatable)) {
159 (*self)(ecx, sp, meta_item, item, push)
163 // `meta_item` is the annotation, and `item` is the item being modified.
164 // FIXME Decorators should follow the same pattern too.
165 pub trait MultiItemModifier {
169 meta_item: &ast::MetaItem,
174 impl<F, T> MultiItemModifier for F
175 where F: Fn(&mut ExtCtxt, Span, &ast::MetaItem, Annotatable) -> T,
176 T: Into<Vec<Annotatable>>,
181 meta_item: &ast::MetaItem,
183 -> Vec<Annotatable> {
184 (*self)(ecx, span, meta_item, item).into()
188 impl Into<Vec<Annotatable>> for Annotatable {
189 fn into(self) -> Vec<Annotatable> {
194 pub trait ProcMacro {
195 fn expand<'cx>(&self,
196 ecx: &'cx mut ExtCtxt,
202 impl<F> ProcMacro for F
203 where F: Fn(TokenStream) -> TokenStream
205 fn expand<'cx>(&self,
206 _ecx: &'cx mut ExtCtxt,
210 // FIXME setup implicit context in TLS before calling self.
215 pub trait AttrProcMacro {
216 fn expand<'cx>(&self,
217 ecx: &'cx mut ExtCtxt,
219 annotation: TokenStream,
220 annotated: TokenStream)
224 impl<F> AttrProcMacro for F
225 where F: Fn(TokenStream, TokenStream) -> TokenStream
227 fn expand<'cx>(&self,
228 _ecx: &'cx mut ExtCtxt,
230 annotation: TokenStream,
231 annotated: TokenStream)
233 // FIXME setup implicit context in TLS before calling self.
234 (*self)(annotation, annotated)
238 /// Represents a thing that maps token trees to Macro Results
239 pub trait TTMacroExpander {
242 ecx: &'cx mut ExtCtxt,
245 def_span: Option<Span>,
246 ) -> Box<dyn MacResult+'cx>;
249 pub type MacroExpanderFn =
250 for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
251 -> Box<dyn MacResult+'cx>;
253 impl<F> TTMacroExpander for F
254 where F: for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
255 -> Box<dyn MacResult+'cx>
259 ecx: &'cx mut ExtCtxt,
262 _def_span: Option<Span>,
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<SmallVec<[P<ast::Item>; 1]>> {
339 /// Create zero or more impl items.
340 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
344 /// Create zero or more trait items.
345 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
349 /// Create zero or more items in an `extern {}` block
350 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { 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<SmallVec<[ast::Stmt; 1]>> {
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: SmallVec<[P<ast::Item>; 1]>,
398 impl_items: SmallVec<[ast::ImplItem; 1]>,
399 trait_items: SmallVec<[ast::TraitItem; 1]>,
400 foreign_items: SmallVec<[ast::ForeignItem; 1]>,
401 stmts: SmallVec<[ast::Stmt; 1]>,
405 impl MacResult for MacEager {
406 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
410 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
414 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
418 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
422 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
426 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
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(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<SmallVec<[P<ast::Item>; 1]>> {
518 // this code needs a comment... why not always just return the Some() ?
522 Some(SmallVec::new())
526 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
530 Some(SmallVec::new())
534 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
538 Some(SmallVec::new())
542 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
546 Some(SmallVec::new())
550 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
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",
589 pub fn article(self) -> &'static str {
591 MacroKind::Attr => "an",
597 /// An enum representing the different kinds of syntax extensions.
598 pub enum SyntaxExtension {
599 /// A trivial "extension" that does nothing, only keeps the attribute and marks it as known.
600 NonMacroAttr { mark_used: bool },
602 /// A syntax extension that is attached to an item and creates new items
605 /// `#[derive(...)]` is a `MultiItemDecorator`.
607 /// Prefer ProcMacro or MultiModifier since they are more flexible.
608 MultiDecorator(Box<dyn MultiItemDecorator + sync::Sync + sync::Send>),
610 /// A syntax extension that is attached to an item and modifies it
611 /// in-place. Also allows decoration, i.e., creating new items.
612 MultiModifier(Box<dyn MultiItemModifier + sync::Sync + sync::Send>),
614 /// A function-like procedural macro. TokenStream -> TokenStream.
616 expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
617 allow_internal_unstable: bool,
621 /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
622 /// The first TokenSteam is the attribute, the second is the annotated item.
623 /// Allows modification of the input items and adding new items, similar to
624 /// MultiModifier, but uses TokenStreams, rather than AST nodes.
625 AttrProcMacro(Box<dyn AttrProcMacro + sync::Sync + sync::Send>, Edition),
627 /// A normal, function-like syntax extension.
629 /// `bytes!` is a `NormalTT`.
631 expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
632 def_info: Option<(ast::NodeId, Span)>,
633 /// Whether the contents of the macro can
634 /// directly use `#[unstable]` things (true == yes).
635 allow_internal_unstable: bool,
636 /// Whether the contents of the macro can use `unsafe`
637 /// without triggering the `unsafe_code` lint.
638 allow_internal_unsafe: bool,
639 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
640 /// for a given macro.
641 local_inner_macros: bool,
642 /// The macro's feature name if it is unstable, and the stability feature
643 unstable_feature: Option<(Symbol, u32)>,
644 /// Edition of the crate in which the macro is defined
648 /// A function-like syntax extension that has an extra ident before
651 IdentTT(Box<dyn IdentMacroExpander + sync::Sync + sync::Send>, Option<Span>, bool),
653 /// An attribute-like procedural macro. TokenStream -> TokenStream.
654 /// The input is the annotated item.
655 /// Allows generating code to implement a Trait for a given struct
657 ProcMacroDerive(Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
658 Vec<Symbol> /* inert attribute names */, Edition),
660 /// An attribute-like procedural macro that derives a builtin trait.
661 BuiltinDerive(BuiltinDeriveFn),
663 /// A declarative macro, e.g., `macro m() {}`.
665 expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
666 def_info: Option<(ast::NodeId, Span)>,
667 is_transparent: bool,
672 impl SyntaxExtension {
673 /// Return which kind of macro calls this syntax extension.
674 pub fn kind(&self) -> MacroKind {
676 SyntaxExtension::DeclMacro { .. } |
677 SyntaxExtension::NormalTT { .. } |
678 SyntaxExtension::IdentTT(..) |
679 SyntaxExtension::ProcMacro { .. } =>
681 SyntaxExtension::NonMacroAttr { .. } |
682 SyntaxExtension::MultiDecorator(..) |
683 SyntaxExtension::MultiModifier(..) |
684 SyntaxExtension::AttrProcMacro(..) =>
686 SyntaxExtension::ProcMacroDerive(..) |
687 SyntaxExtension::BuiltinDerive(..) =>
692 pub fn default_transparency(&self) -> Transparency {
694 SyntaxExtension::ProcMacro { .. } |
695 SyntaxExtension::AttrProcMacro(..) |
696 SyntaxExtension::ProcMacroDerive(..) |
697 SyntaxExtension::DeclMacro { is_transparent: false, .. } => Transparency::Opaque,
698 SyntaxExtension::DeclMacro { is_transparent: true, .. } => Transparency::Transparent,
699 _ => Transparency::SemiTransparent,
703 pub fn edition(&self) -> Edition {
705 SyntaxExtension::NormalTT { edition, .. } |
706 SyntaxExtension::DeclMacro { edition, .. } |
707 SyntaxExtension::ProcMacro { edition, .. } |
708 SyntaxExtension::AttrProcMacro(.., edition) |
709 SyntaxExtension::ProcMacroDerive(.., edition) => edition,
710 // Unstable legacy stuff
711 SyntaxExtension::NonMacroAttr { .. } |
712 SyntaxExtension::IdentTT(..) |
713 SyntaxExtension::MultiDecorator(..) |
714 SyntaxExtension::MultiModifier(..) |
715 SyntaxExtension::BuiltinDerive(..) => hygiene::default_edition(),
720 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
723 fn next_node_id(&mut self) -> ast::NodeId;
724 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
726 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
728 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
730 fn resolve_imports(&mut self);
732 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
733 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
734 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
735 derives_in_scope: Vec<ast::Path>, force: bool)
736 -> Result<Lrc<SyntaxExtension>, Determinacy>;
738 fn check_unused_macros(&self);
741 #[derive(Copy, Clone, PartialEq, Debug)]
742 pub enum Determinacy {
748 pub fn determined(determined: bool) -> Determinacy {
749 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
753 pub struct DummyResolver;
755 impl Resolver for DummyResolver {
756 fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
757 fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
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 resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
765 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
766 Err(Determinacy::Determined)
768 fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
769 _derives_in_scope: Vec<ast::Path>, _force: bool)
770 -> Result<Lrc<SyntaxExtension>, Determinacy> {
771 Err(Determinacy::Determined)
773 fn check_unused_macros(&self) {}
777 pub struct ModuleData {
778 pub mod_path: Vec<ast::Ident>,
779 pub directory: PathBuf,
783 pub struct ExpansionData {
786 pub module: Rc<ModuleData>,
787 pub directory_ownership: DirectoryOwnership,
788 pub crate_span: Option<Span>,
791 /// One of these is made during expansion and incrementally updated as we go;
792 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
793 /// -> expn_info` of their expansion context stored into their span.
794 pub struct ExtCtxt<'a> {
795 pub parse_sess: &'a parse::ParseSess,
796 pub ecfg: expand::ExpansionConfig<'a>,
797 pub root_path: PathBuf,
798 pub resolver: &'a mut dyn Resolver,
799 pub resolve_err_count: usize,
800 pub current_expansion: ExpansionData,
801 pub expansions: FxHashMap<Span, Vec<String>>,
804 impl<'a> ExtCtxt<'a> {
805 pub fn new(parse_sess: &'a parse::ParseSess,
806 ecfg: expand::ExpansionConfig<'a>,
807 resolver: &'a mut dyn Resolver)
812 root_path: PathBuf::new(),
814 resolve_err_count: 0,
815 current_expansion: ExpansionData {
818 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
819 directory_ownership: DirectoryOwnership::Owned { relative: None },
822 expansions: FxHashMap::default(),
826 /// Returns a `Folder` for deeply expanding all macros in an AST node.
827 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
828 expand::MacroExpander::new(self, false)
831 /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
832 /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
833 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
834 expand::MacroExpander::new(self, true)
837 pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
838 parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
840 pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
841 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
842 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
843 pub fn call_site(&self) -> Span {
844 match self.current_expansion.mark.expn_info() {
845 Some(expn_info) => expn_info.call_site,
849 pub fn backtrace(&self) -> SyntaxContext {
850 SyntaxContext::empty().apply_mark(self.current_expansion.mark)
853 /// Returns span for the macro which originally caused the current expansion to happen.
855 /// Stops backtracing at include! boundary.
856 pub fn expansion_cause(&self) -> Option<Span> {
857 let mut ctxt = self.backtrace();
858 let mut last_macro = None;
860 if ctxt.outer().expn_info().map_or(None, |info| {
861 if info.format.name() == "include" {
862 // Stop going up the backtrace once include! is encountered
865 ctxt = info.call_site.ctxt();
866 last_macro = Some(info.call_site);
875 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
878 -> DiagnosticBuilder<'a> {
879 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
881 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
884 -> DiagnosticBuilder<'a> {
885 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
887 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
890 -> DiagnosticBuilder<'a> {
891 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
894 /// Emit `msg` attached to `sp`, and stop compilation immediately.
896 /// `span_err` should be strongly preferred where-ever possible:
897 /// this should *only* be used when:
899 /// - continuing has a high risk of flow-on errors (e.g., errors in
900 /// declaring a macro would cause all uses of that macro to
901 /// complain about "undefined macro"), or
902 /// - there is literally nothing else that can be done (however,
903 /// in most cases one can construct a dummy expression/item to
904 /// substitute; we never hit resolve/type-checking so the dummy
905 /// value doesn't have to match anything)
906 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
907 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
910 /// Emit `msg` attached to `sp`, without immediately stopping
913 /// Compilation will be stopped in the near future (at the end of
914 /// the macro expansion phase).
915 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
916 self.parse_sess.span_diagnostic.span_err(sp, msg);
918 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
919 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
921 pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
922 -> DiagnosticBuilder<'a> {
923 self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
925 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
926 self.parse_sess.span_diagnostic.span_warn(sp, msg);
928 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
929 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
931 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
932 self.parse_sess.span_diagnostic.span_bug(sp, msg);
934 pub fn trace_macros_diag(&mut self) {
935 for (sp, notes) in self.expansions.iter() {
936 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
942 // Fixme: does this result in errors?
943 self.expansions.clear();
945 pub fn bug(&self, msg: &str) -> ! {
946 self.parse_sess.span_diagnostic.bug(msg);
948 pub fn trace_macros(&self) -> bool {
951 pub fn set_trace_macros(&mut self, x: bool) {
952 self.ecfg.trace_mac = x
954 pub fn ident_of(&self, st: &str) -> ast::Ident {
955 ast::Ident::from_str(st)
957 pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
958 let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
959 iter::once(Ident::new(keywords::DollarCrate.name(), def_site))
960 .chain(components.iter().map(|s| self.ident_of(s)))
963 pub fn name_of(&self, st: &str) -> ast::Name {
967 pub fn check_unused_macros(&self) {
968 self.resolver.check_unused_macros();
972 /// Extract a string literal from the macro expanded version of `expr`,
973 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
974 /// compilation on error, merely emits a non-fatal error and returns None.
975 pub fn expr_to_spanned_string<'a>(
979 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, DiagnosticBuilder<'a>> {
980 // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
981 let expr = expr.map(|mut expr| {
982 expr.span = expr.span.apply_mark(cx.current_expansion.mark);
986 // we want to be able to handle e.g., `concat!("foo", "bar")`
987 let expr = cx.expander().fold_expr(expr);
988 Err(match expr.node {
989 ast::ExprKind::Lit(ref l) => match l.node {
990 ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
991 _ => cx.struct_span_err(l.span, err_msg)
993 _ => cx.struct_span_err(expr.span, err_msg)
997 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
998 -> Option<(Symbol, ast::StrStyle)> {
999 expr_to_spanned_string(cx, expr, err_msg)
1000 .map_err(|mut err| err.emit())
1005 /// Non-fatally assert that `tts` is empty. Note that this function
1006 /// returns even when `tts` is non-empty, macros that *need* to stop
1007 /// compilation should call
1008 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1009 /// done as rarely as possible).
1010 pub fn check_zero_tts(cx: &ExtCtxt,
1012 tts: &[tokenstream::TokenTree],
1014 if !tts.is_empty() {
1015 cx.span_err(sp, &format!("{} takes no arguments", name));
1019 /// Interpreting `tts` as a comma-separated sequence of expressions,
1020 /// expect exactly one string literal, or emit an error and return None.
1021 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
1023 tts: &[tokenstream::TokenTree],
1026 let mut p = cx.new_parser_from_tts(tts);
1027 if p.token == token::Eof {
1028 cx.span_err(sp, &format!("{} takes 1 argument", name));
1031 let ret = panictry!(p.parse_expr());
1032 let _ = p.eat(&token::Comma);
1034 if p.token != token::Eof {
1035 cx.span_err(sp, &format!("{} takes 1 argument", name));
1037 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1042 /// Extract comma-separated expressions from `tts`. If there is a
1043 /// parsing error, emit a non-fatal error and return None.
1044 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
1046 tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
1047 let mut p = cx.new_parser_from_tts(tts);
1048 let mut es = Vec::new();
1049 while p.token != token::Eof {
1050 es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
1051 if p.eat(&token::Comma) {
1054 if p.token != token::Eof {
1055 cx.span_err(sp, "expected token: `,`");