1 use crate::ast::{self, Attribute, Name, PatKind};
2 use crate::attr::HasAttrs;
3 use crate::source_map::{SourceMap, Spanned, respan};
4 use crate::edition::Edition;
5 use crate::ext::expand::{self, AstFragment, Invocation};
6 use crate::ext::hygiene::{Mark, SyntaxContext, Transparency};
7 use crate::mut_visit::{self, MutVisitor};
8 use crate::parse::{self, parser, DirectoryOwnership};
9 use crate::parse::token;
11 use crate::symbol::{kw, sym, Ident, Symbol};
12 use crate::{ThinVec, MACRO_ARGUMENTS};
13 use crate::tokenstream::{self, TokenStream};
15 use errors::{DiagnosticBuilder, DiagnosticId};
16 use smallvec::{smallvec, SmallVec};
17 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
19 use rustc_data_structures::fx::FxHashMap;
20 use rustc_data_structures::sync::{self, Lrc};
22 use std::path::PathBuf;
24 use std::default::Default;
27 #[derive(Debug,Clone)]
28 pub enum Annotatable {
30 TraitItem(P<ast::TraitItem>),
31 ImplItem(P<ast::ImplItem>),
32 ForeignItem(P<ast::ForeignItem>),
37 impl HasAttrs for Annotatable {
38 fn attrs(&self) -> &[Attribute] {
40 Annotatable::Item(ref item) => &item.attrs,
41 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
42 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
43 Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
44 Annotatable::Stmt(ref stmt) => stmt.attrs(),
45 Annotatable::Expr(ref expr) => &expr.attrs,
49 fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
51 Annotatable::Item(item) => item.visit_attrs(f),
52 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
53 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
54 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
55 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
56 Annotatable::Expr(expr) => expr.visit_attrs(f),
62 pub fn span(&self) -> Span {
64 Annotatable::Item(ref item) => item.span,
65 Annotatable::TraitItem(ref trait_item) => trait_item.span,
66 Annotatable::ImplItem(ref impl_item) => impl_item.span,
67 Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
68 Annotatable::Stmt(ref stmt) => stmt.span,
69 Annotatable::Expr(ref expr) => expr.span,
73 pub fn expect_item(self) -> P<ast::Item> {
75 Annotatable::Item(i) => i,
76 _ => panic!("expected Item")
80 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
81 where F: FnMut(P<ast::Item>) -> P<ast::Item>,
82 G: FnMut(Annotatable) -> Annotatable
85 Annotatable::Item(i) => Annotatable::Item(f(i)),
90 pub fn expect_trait_item(self) -> ast::TraitItem {
92 Annotatable::TraitItem(i) => i.into_inner(),
93 _ => panic!("expected Item")
97 pub fn expect_impl_item(self) -> ast::ImplItem {
99 Annotatable::ImplItem(i) => i.into_inner(),
100 _ => panic!("expected Item")
104 pub fn expect_foreign_item(self) -> ast::ForeignItem {
106 Annotatable::ForeignItem(i) => i.into_inner(),
107 _ => panic!("expected foreign item")
111 pub fn expect_stmt(self) -> ast::Stmt {
113 Annotatable::Stmt(stmt) => stmt.into_inner(),
114 _ => panic!("expected statement"),
118 pub fn expect_expr(self) -> P<ast::Expr> {
120 Annotatable::Expr(expr) => expr,
121 _ => panic!("expected expression"),
125 pub fn derive_allowed(&self) -> bool {
127 Annotatable::Item(ref item) => match item.node {
128 ast::ItemKind::Struct(..) |
129 ast::ItemKind::Enum(..) |
130 ast::ItemKind::Union(..) => true,
138 // `meta_item` is the annotation, and `item` is the item being modified.
139 // FIXME Decorators should follow the same pattern too.
140 pub trait MultiItemModifier {
142 ecx: &mut ExtCtxt<'_>,
144 meta_item: &ast::MetaItem,
149 impl<F, T> MultiItemModifier for F
150 where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
151 T: Into<Vec<Annotatable>>,
154 ecx: &mut ExtCtxt<'_>,
156 meta_item: &ast::MetaItem,
158 -> Vec<Annotatable> {
159 (*self)(ecx, span, meta_item, item).into()
163 impl Into<Vec<Annotatable>> for Annotatable {
164 fn into(self) -> Vec<Annotatable> {
169 pub trait ProcMacro {
170 fn expand<'cx>(&self,
171 ecx: &'cx mut ExtCtxt<'_>,
177 impl<F> ProcMacro for F
178 where F: Fn(TokenStream) -> TokenStream
180 fn expand<'cx>(&self,
181 _ecx: &'cx mut ExtCtxt<'_>,
185 // FIXME setup implicit context in TLS before calling self.
190 pub trait AttrProcMacro {
191 fn expand<'cx>(&self,
192 ecx: &'cx mut ExtCtxt<'_>,
194 annotation: TokenStream,
195 annotated: TokenStream)
199 impl<F> AttrProcMacro for F
200 where F: Fn(TokenStream, TokenStream) -> TokenStream
202 fn expand<'cx>(&self,
203 _ecx: &'cx mut ExtCtxt<'_>,
205 annotation: TokenStream,
206 annotated: TokenStream)
208 // FIXME setup implicit context in TLS before calling self.
209 (*self)(annotation, annotated)
213 /// Represents a thing that maps token trees to Macro Results
214 pub trait TTMacroExpander {
217 ecx: &'cx mut ExtCtxt<'_>,
220 def_span: Option<Span>,
221 ) -> Box<dyn MacResult+'cx>;
224 pub type MacroExpanderFn =
225 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
226 -> Box<dyn MacResult+'cx>;
228 impl<F> TTMacroExpander for F
229 where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
230 -> Box<dyn MacResult+'cx>
234 ecx: &'cx mut ExtCtxt<'_>,
237 _def_span: Option<Span>,
238 ) -> Box<dyn MacResult+'cx> {
239 struct AvoidInterpolatedIdents;
241 impl MutVisitor for AvoidInterpolatedIdents {
242 fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
243 if let tokenstream::TokenTree::Token(token) = tt {
244 if let token::Interpolated(nt) = &token.kind {
245 if let token::NtIdent(ident, is_raw) = **nt {
246 *tt = tokenstream::TokenTree::token(
247 token::Ident(ident.name, is_raw), ident.span
252 mut_visit::noop_visit_tt(tt, self)
255 fn visit_mac(&mut self, mac: &mut ast::Mac) {
256 mut_visit::noop_visit_mac(mac, self)
261 input.trees().map(|mut tt| { AvoidInterpolatedIdents.visit_tt(&mut tt); tt }).collect();
262 (*self)(ecx, span, &input)
266 // Use a macro because forwarding to a simple function has type system issues
267 macro_rules! make_stmts_default {
269 $me.make_expr().map(|e| smallvec![ast::Stmt {
270 id: ast::DUMMY_NODE_ID,
272 node: ast::StmtKind::Expr(e),
277 /// The result of a macro expansion. The return values of the various
278 /// methods are spliced into the AST at the callsite of the macro.
279 pub trait MacResult {
280 /// Creates an expression.
281 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
284 /// Creates zero or more items.
285 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
289 /// Creates zero or more impl items.
290 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
294 /// Creates zero or more trait items.
295 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
299 /// Creates zero or more items in an `extern {}` block
300 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None }
302 /// Creates a pattern.
303 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
307 /// Creates zero or more statements.
309 /// By default this attempts to create an expression statement,
310 /// returning None if that fails.
311 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
312 make_stmts_default!(self)
315 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
320 macro_rules! make_MacEager {
321 ( $( $fld:ident: $t:ty, )* ) => {
322 /// `MacResult` implementation for the common case where you've already
323 /// built each form of AST that you might return.
325 pub struct MacEager {
327 pub $fld: Option<$t>,
333 pub fn $fld(v: $t) -> Box<dyn MacResult> {
347 items: SmallVec<[P<ast::Item>; 1]>,
348 impl_items: SmallVec<[ast::ImplItem; 1]>,
349 trait_items: SmallVec<[ast::TraitItem; 1]>,
350 foreign_items: SmallVec<[ast::ForeignItem; 1]>,
351 stmts: SmallVec<[ast::Stmt; 1]>,
355 impl MacResult for MacEager {
356 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
360 fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
364 fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
368 fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
372 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
376 fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
377 match self.stmts.as_ref().map_or(0, |s| s.len()) {
378 0 => make_stmts_default!(self),
383 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
384 if let Some(p) = self.pat {
387 if let Some(e) = self.expr {
388 if let ast::ExprKind::Lit(_) = e.node {
389 return Some(P(ast::Pat {
390 id: ast::DUMMY_NODE_ID,
392 node: PatKind::Lit(e),
399 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
404 /// Fill-in macro expansion result, to allow compilation to continue
405 /// after hitting errors.
406 #[derive(Copy, Clone)]
407 pub struct DummyResult {
414 /// Creates a default MacResult that can be anything.
416 /// Use this as a return value after hitting any errors and
417 /// calling `span_err`.
418 pub fn any(span: Span) -> Box<dyn MacResult+'static> {
419 Box::new(DummyResult { expr_only: false, is_error: true, span })
422 /// Same as `any`, but must be a valid fragment, not error.
423 pub fn any_valid(span: Span) -> Box<dyn MacResult+'static> {
424 Box::new(DummyResult { expr_only: false, is_error: false, span })
427 /// Creates a default MacResult that can only be an expression.
429 /// Use this for macros that must expand to an expression, so even
430 /// if an error is encountered internally, the user will receive
431 /// an error that they also used it in the wrong place.
432 pub fn expr(span: Span) -> Box<dyn MacResult+'static> {
433 Box::new(DummyResult { expr_only: true, is_error: true, span })
436 /// A plain dummy expression.
437 pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
439 id: ast::DUMMY_NODE_ID,
440 node: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
442 attrs: ThinVec::new(),
446 /// A plain dummy pattern.
447 pub fn raw_pat(sp: Span) -> ast::Pat {
449 id: ast::DUMMY_NODE_ID,
455 /// A plain dummy type.
456 pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
458 id: ast::DUMMY_NODE_ID,
459 node: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
465 impl MacResult for DummyResult {
466 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
467 Some(DummyResult::raw_expr(self.span, self.is_error))
470 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
471 Some(P(DummyResult::raw_pat(self.span)))
474 fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
475 // this code needs a comment... why not always just return the Some() ?
479 Some(SmallVec::new())
483 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
487 Some(SmallVec::new())
491 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
495 Some(SmallVec::new())
499 fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
503 Some(SmallVec::new())
507 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
508 Some(smallvec![ast::Stmt {
509 id: ast::DUMMY_NODE_ID,
510 node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
515 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
516 Some(DummyResult::raw_ty(self.span, self.is_error))
520 /// Represents different kinds of macro invocations that can be resolved.
521 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
523 /// A bang macro - foo!()
525 /// An attribute macro - #[foo]
527 /// A derive attribute macro - #[derive(Foo)]
529 /// A view of a procedural macro from the same crate that defines it.
534 pub fn descr(self) -> &'static str {
536 MacroKind::Bang => "macro",
537 MacroKind::Attr => "attribute macro",
538 MacroKind::Derive => "derive macro",
539 MacroKind::ProcMacroStub => "crate-local procedural macro",
543 pub fn article(self) -> &'static str {
545 MacroKind::Attr => "an",
551 /// An enum representing the different kinds of syntax extensions.
552 pub enum SyntaxExtension {
553 /// A token-based function-like macro.
555 /// An expander with signature TokenStream -> TokenStream.
556 expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
557 /// Whitelist of unstable features that are treated as stable inside this macro.
558 allow_internal_unstable: Option<Lrc<[Symbol]>>,
559 /// Edition of the crate in which this macro is defined.
563 /// An AST-based function-like macro.
565 /// An expander with signature TokenStream -> AST.
566 expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
567 /// Some info about the macro's definition point.
568 def_info: Option<(ast::NodeId, Span)>,
569 /// Hygienic properties of identifiers produced by this macro.
570 transparency: Transparency,
571 /// Whitelist of unstable features that are treated as stable inside this macro.
572 allow_internal_unstable: Option<Lrc<[Symbol]>>,
573 /// Suppresses the `unsafe_code` lint for code produced by this macro.
574 allow_internal_unsafe: bool,
575 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
576 local_inner_macros: bool,
577 /// The macro's feature name and tracking issue number if it is unstable.
578 unstable_feature: Option<(Symbol, u32)>,
579 /// Edition of the crate in which this macro is defined.
583 /// A token-based attribute macro.
585 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
586 /// The first TokenSteam is the attribute itself, the second is the annotated item.
587 /// The produced TokenSteam replaces the input TokenSteam.
588 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
589 /// Edition of the crate in which this macro is defined.
593 /// An AST-based attribute macro.
595 /// An expander with signature (AST, AST) -> AST.
596 /// The first AST fragment is the attribute itself, the second is the annotated item.
597 /// The produced AST fragment replaces the input AST fragment.
598 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
601 /// A trivial attribute "macro" that does nothing,
602 /// only keeps the attribute and marks it as known.
604 /// Suppresses the `unused_attributes` lint for this attribute.
608 /// A token-based derive macro.
610 /// An expander with signature TokenStream -> TokenStream (not yet).
611 /// The produced TokenSteam is appended to the input TokenSteam.
612 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
613 /// Names of helper attributes registered by this macro.
615 /// Edition of the crate in which this macro is defined.
619 /// An AST-based derive macro.
621 /// An expander with signature AST -> AST.
622 /// The produced AST fragment is appended to the input AST fragment.
623 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
627 impl SyntaxExtension {
628 /// Returns which kind of macro calls this syntax extension.
629 pub fn kind(&self) -> MacroKind {
631 SyntaxExtension::Bang { .. } |
632 SyntaxExtension::LegacyBang { .. } => MacroKind::Bang,
633 SyntaxExtension::Attr(..) |
634 SyntaxExtension::LegacyAttr(..) |
635 SyntaxExtension::NonMacroAttr { .. } => MacroKind::Attr,
636 SyntaxExtension::Derive(..) |
637 SyntaxExtension::LegacyDerive(..) => MacroKind::Derive,
641 pub fn default_transparency(&self) -> Transparency {
643 SyntaxExtension::LegacyBang { transparency, .. } => transparency,
644 SyntaxExtension::Bang { .. } |
645 SyntaxExtension::Attr(..) |
646 SyntaxExtension::Derive(..) |
647 SyntaxExtension::NonMacroAttr { .. } => Transparency::Opaque,
648 SyntaxExtension::LegacyAttr(..) |
649 SyntaxExtension::LegacyDerive(..) => Transparency::SemiTransparent,
653 pub fn edition(&self, default_edition: Edition) -> Edition {
655 SyntaxExtension::Bang { edition, .. } |
656 SyntaxExtension::LegacyBang { edition, .. } |
657 SyntaxExtension::Attr(.., edition) |
658 SyntaxExtension::Derive(.., edition) => edition,
659 // Unstable legacy stuff
660 SyntaxExtension::NonMacroAttr { .. } |
661 SyntaxExtension::LegacyAttr(..) |
662 SyntaxExtension::LegacyDerive(..) => default_edition,
667 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
670 fn next_node_id(&mut self) -> ast::NodeId;
672 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
674 fn resolve_dollar_crates(&mut self, fragment: &AstFragment);
675 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
677 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
679 fn resolve_imports(&mut self);
681 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
682 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
683 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
684 derives_in_scope: Vec<ast::Path>, force: bool)
685 -> Result<Lrc<SyntaxExtension>, Determinacy>;
687 fn check_unused_macros(&self);
690 #[derive(Copy, Clone, PartialEq, Debug)]
691 pub enum Determinacy {
697 pub fn determined(determined: bool) -> Determinacy {
698 if determined { Determinacy::Determined } else { Determinacy::Undetermined }
702 pub struct DummyResolver;
704 impl Resolver for DummyResolver {
705 fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
707 fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
709 fn resolve_dollar_crates(&mut self, _fragment: &AstFragment) {}
710 fn visit_ast_fragment_with_placeholders(&mut self, _invoc: Mark, _fragment: &AstFragment,
711 _derives: &[Mark]) {}
712 fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc<SyntaxExtension>) {}
714 fn resolve_imports(&mut self) {}
715 fn resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
716 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
717 Err(Determinacy::Determined)
719 fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
720 _derives_in_scope: Vec<ast::Path>, _force: bool)
721 -> Result<Lrc<SyntaxExtension>, Determinacy> {
722 Err(Determinacy::Determined)
724 fn check_unused_macros(&self) {}
728 pub struct ModuleData {
729 pub mod_path: Vec<ast::Ident>,
730 pub directory: PathBuf,
734 pub struct ExpansionData {
737 pub module: Rc<ModuleData>,
738 pub directory_ownership: DirectoryOwnership,
739 pub crate_span: Option<Span>,
742 /// One of these is made during expansion and incrementally updated as we go;
743 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
744 /// -> expn_info` of their expansion context stored into their span.
745 pub struct ExtCtxt<'a> {
746 pub parse_sess: &'a parse::ParseSess,
747 pub ecfg: expand::ExpansionConfig<'a>,
748 pub root_path: PathBuf,
749 pub resolver: &'a mut dyn Resolver,
750 pub current_expansion: ExpansionData,
751 pub expansions: FxHashMap<Span, Vec<String>>,
754 impl<'a> ExtCtxt<'a> {
755 pub fn new(parse_sess: &'a parse::ParseSess,
756 ecfg: expand::ExpansionConfig<'a>,
757 resolver: &'a mut dyn Resolver)
762 root_path: PathBuf::new(),
764 current_expansion: ExpansionData {
767 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
768 directory_ownership: DirectoryOwnership::Owned { relative: None },
771 expansions: FxHashMap::default(),
775 /// Returns a `Folder` for deeply expanding all macros in an AST node.
776 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
777 expand::MacroExpander::new(self, false)
780 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
781 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
782 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
783 expand::MacroExpander::new(self, true)
786 pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
787 parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect(), MACRO_ARGUMENTS)
789 pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
790 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
791 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
792 pub fn call_site(&self) -> Span {
793 match self.current_expansion.mark.expn_info() {
794 Some(expn_info) => expn_info.call_site,
798 pub fn backtrace(&self) -> SyntaxContext {
799 SyntaxContext::empty().apply_mark(self.current_expansion.mark)
802 /// Returns span for the macro which originally caused the current expansion to happen.
804 /// Stops backtracing at include! boundary.
805 pub fn expansion_cause(&self) -> Option<Span> {
806 let mut ctxt = self.backtrace();
807 let mut last_macro = None;
809 if ctxt.outer_expn_info().map_or(None, |info| {
810 if info.format.name() == sym::include {
811 // Stop going up the backtrace once include! is encountered
814 ctxt = info.call_site.ctxt();
815 last_macro = Some(info.call_site);
824 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
827 -> DiagnosticBuilder<'a> {
828 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
830 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
833 -> DiagnosticBuilder<'a> {
834 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
836 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
839 -> DiagnosticBuilder<'a> {
840 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
843 /// Emit `msg` attached to `sp`, and stop compilation immediately.
845 /// `span_err` should be strongly preferred where-ever possible:
846 /// this should *only* be used when:
848 /// - continuing has a high risk of flow-on errors (e.g., errors in
849 /// declaring a macro would cause all uses of that macro to
850 /// complain about "undefined macro"), or
851 /// - there is literally nothing else that can be done (however,
852 /// in most cases one can construct a dummy expression/item to
853 /// substitute; we never hit resolve/type-checking so the dummy
854 /// value doesn't have to match anything)
855 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
856 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
859 /// Emit `msg` attached to `sp`, without immediately stopping
862 /// Compilation will be stopped in the near future (at the end of
863 /// the macro expansion phase).
864 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
865 self.parse_sess.span_diagnostic.span_err(sp, msg);
867 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
868 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
870 pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
871 -> DiagnosticBuilder<'a> {
872 self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
874 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
875 self.parse_sess.span_diagnostic.span_warn(sp, msg);
877 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
878 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
880 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
881 self.parse_sess.span_diagnostic.span_bug(sp, msg);
883 pub fn trace_macros_diag(&mut self) {
884 for (sp, notes) in self.expansions.iter() {
885 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
891 // Fixme: does this result in errors?
892 self.expansions.clear();
894 pub fn bug(&self, msg: &str) -> ! {
895 self.parse_sess.span_diagnostic.bug(msg);
897 pub fn trace_macros(&self) -> bool {
900 pub fn set_trace_macros(&mut self, x: bool) {
901 self.ecfg.trace_mac = x
903 pub fn ident_of(&self, st: &str) -> ast::Ident {
904 ast::Ident::from_str(st)
906 pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
907 let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
908 iter::once(Ident::new(kw::DollarCrate, def_site))
909 .chain(components.iter().map(|&s| Ident::with_empty_ctxt(s)))
912 pub fn name_of(&self, st: &str) -> ast::Name {
916 pub fn check_unused_macros(&self) {
917 self.resolver.check_unused_macros();
921 /// Extracts a string literal from the macro expanded version of `expr`,
922 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
923 /// compilation on error, merely emits a non-fatal error and returns `None`.
924 pub fn expr_to_spanned_string<'a>(
925 cx: &'a mut ExtCtxt<'_>,
926 mut expr: P<ast::Expr>,
928 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, Option<DiagnosticBuilder<'a>>> {
929 // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
930 expr.span = expr.span.apply_mark(cx.current_expansion.mark);
932 // we want to be able to handle e.g., `concat!("foo", "bar")`
933 cx.expander().visit_expr(&mut expr);
934 Err(match expr.node {
935 ast::ExprKind::Lit(ref l) => match l.node {
936 ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
937 ast::LitKind::Err(_) => None,
938 _ => Some(cx.struct_span_err(l.span, err_msg))
940 ast::ExprKind::Err => None,
941 _ => Some(cx.struct_span_err(expr.span, err_msg))
945 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
946 -> Option<(Symbol, ast::StrStyle)> {
947 expr_to_spanned_string(cx, expr, err_msg)
948 .map_err(|err| err.map(|mut err| err.emit()))
953 /// Non-fatally assert that `tts` is empty. Note that this function
954 /// returns even when `tts` is non-empty, macros that *need* to stop
955 /// compilation should call
956 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
957 /// done as rarely as possible).
958 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
960 tts: &[tokenstream::TokenTree],
963 cx.span_err(sp, &format!("{} takes no arguments", name));
967 /// Interpreting `tts` as a comma-separated sequence of expressions,
968 /// expect exactly one string literal, or emit an error and return `None`.
969 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
971 tts: &[tokenstream::TokenTree],
974 let mut p = cx.new_parser_from_tts(tts);
975 if p.token == token::Eof {
976 cx.span_err(sp, &format!("{} takes 1 argument", name));
979 let ret = panictry!(p.parse_expr());
980 let _ = p.eat(&token::Comma);
982 if p.token != token::Eof {
983 cx.span_err(sp, &format!("{} takes 1 argument", name));
985 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
990 /// Extracts comma-separated expressions from `tts`. If there is a
991 /// parsing error, emit a non-fatal error and return `None`.
992 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
994 tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
995 let mut p = cx.new_parser_from_tts(tts);
996 let mut es = Vec::new();
997 while p.token != token::Eof {
998 let mut expr = panictry!(p.parse_expr());
999 cx.expander().visit_expr(&mut expr);
1001 if p.eat(&token::Comma) {
1004 if p.token != token::Eof {
1005 cx.span_err(sp, "expected token: `,`");