1 use crate::ast::{self, Attribute, Name, PatKind};
2 use crate::attr::{HasAttrs, Stability, Deprecation};
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::{ExpnId, 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, TokenTree};
15 use errors::{DiagnosticBuilder, DiagnosticId};
16 use smallvec::{smallvec, SmallVec};
17 use syntax_pos::{FileName, Span, MultiSpan, DUMMY_SP};
18 use syntax_pos::hygiene::{ExpnInfo, ExpnKind};
20 use rustc_data_structures::fx::FxHashMap;
21 use rustc_data_structures::sync::{self, Lrc};
23 use std::path::PathBuf;
25 use std::default::Default;
27 pub use syntax_pos::hygiene::MacroKind;
29 #[derive(Debug,Clone)]
30 pub enum Annotatable {
32 TraitItem(P<ast::TraitItem>),
33 ImplItem(P<ast::ImplItem>),
34 ForeignItem(P<ast::ForeignItem>),
39 impl HasAttrs for Annotatable {
40 fn attrs(&self) -> &[Attribute] {
42 Annotatable::Item(ref item) => &item.attrs,
43 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
44 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
45 Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
46 Annotatable::Stmt(ref stmt) => stmt.attrs(),
47 Annotatable::Expr(ref expr) => &expr.attrs,
51 fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
53 Annotatable::Item(item) => item.visit_attrs(f),
54 Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
55 Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
56 Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
57 Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
58 Annotatable::Expr(expr) => expr.visit_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 // `meta_item` is the annotation, and `item` is the item being modified.
141 // FIXME Decorators should follow the same pattern too.
142 pub trait MultiItemModifier {
144 ecx: &mut ExtCtxt<'_>,
146 meta_item: &ast::MetaItem,
151 impl<F, T> MultiItemModifier for F
152 where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
153 T: Into<Vec<Annotatable>>,
156 ecx: &mut ExtCtxt<'_>,
158 meta_item: &ast::MetaItem,
160 -> Vec<Annotatable> {
161 (*self)(ecx, span, meta_item, item).into()
165 impl Into<Vec<Annotatable>> for Annotatable {
166 fn into(self) -> Vec<Annotatable> {
171 pub trait ProcMacro {
172 fn expand<'cx>(&self,
173 ecx: &'cx mut ExtCtxt<'_>,
179 impl<F> ProcMacro for F
180 where F: Fn(TokenStream) -> TokenStream
182 fn expand<'cx>(&self,
183 _ecx: &'cx mut ExtCtxt<'_>,
187 // FIXME setup implicit context in TLS before calling self.
192 pub trait AttrProcMacro {
193 fn expand<'cx>(&self,
194 ecx: &'cx mut ExtCtxt<'_>,
196 annotation: TokenStream,
197 annotated: TokenStream)
201 impl<F> AttrProcMacro for F
202 where F: Fn(TokenStream, TokenStream) -> TokenStream
204 fn expand<'cx>(&self,
205 _ecx: &'cx mut ExtCtxt<'_>,
207 annotation: TokenStream,
208 annotated: TokenStream)
210 // FIXME setup implicit context in TLS before calling self.
211 (*self)(annotation, annotated)
215 /// Represents a thing that maps token trees to Macro Results
216 pub trait TTMacroExpander {
219 ecx: &'cx mut ExtCtxt<'_>,
222 ) -> Box<dyn MacResult+'cx>;
225 pub type MacroExpanderFn =
226 for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
227 -> Box<dyn MacResult+'cx>;
229 impl<F> TTMacroExpander for F
230 where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
231 -> Box<dyn MacResult+'cx>
235 ecx: &'cx mut ExtCtxt<'_>,
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 /// A syntax extension kind.
521 pub enum SyntaxExtensionKind {
522 /// A token-based function-like macro.
524 /// An expander with signature TokenStream -> TokenStream.
525 Box<dyn ProcMacro + sync::Sync + sync::Send>,
528 /// An AST-based function-like macro.
530 /// An expander with signature TokenStream -> AST.
531 Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
534 /// A token-based attribute macro.
536 /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
537 /// The first TokenSteam is the attribute itself, the second is the annotated item.
538 /// The produced TokenSteam replaces the input TokenSteam.
539 Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
542 /// An AST-based attribute macro.
544 /// An expander with signature (AST, AST) -> AST.
545 /// The first AST fragment is the attribute itself, the second is the annotated item.
546 /// The produced AST fragment replaces the input AST fragment.
547 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
550 /// A trivial attribute "macro" that does nothing,
551 /// only keeps the attribute and marks it as inert,
552 /// thus making it ineligible for further expansion.
554 /// Suppresses the `unused_attributes` lint for this attribute.
558 /// A token-based derive macro.
560 /// An expander with signature TokenStream -> TokenStream (not yet).
561 /// The produced TokenSteam is appended to the input TokenSteam.
562 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
565 /// An AST-based derive macro.
567 /// An expander with signature AST -> AST.
568 /// The produced AST fragment is appended to the input AST fragment.
569 Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
573 /// A struct representing a macro definition in "lowered" form ready for expansion.
574 pub struct SyntaxExtension {
575 /// A syntax extension kind.
576 pub kind: SyntaxExtensionKind,
577 /// Span of the macro definition.
579 /// Hygienic properties of spans produced by this macro by default.
580 pub default_transparency: Transparency,
581 /// Whitelist of unstable features that are treated as stable inside this macro.
582 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
583 /// Suppresses the `unsafe_code` lint for code produced by this macro.
584 pub allow_internal_unsafe: bool,
585 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
586 pub local_inner_macros: bool,
587 /// The macro's stability info.
588 pub stability: Option<Stability>,
589 /// The macro's deprecation info.
590 pub deprecation: Option<Deprecation>,
591 /// Names of helper attributes registered by this macro.
592 pub helper_attrs: Vec<Symbol>,
593 /// Edition of the crate in which this macro is defined.
594 pub edition: Edition,
595 /// Built-in macros have a couple of special properties (meaning of `$crate`,
596 /// availability in `#[no_implicit_prelude]` modules), so we have to keep this flag.
597 pub is_builtin: bool,
600 impl SyntaxExtensionKind {
601 /// When a syntax extension is constructed,
602 /// its transparency can often be inferred from its kind.
603 fn default_transparency(&self) -> Transparency {
605 SyntaxExtensionKind::Bang(..) |
606 SyntaxExtensionKind::Attr(..) |
607 SyntaxExtensionKind::Derive(..) |
608 SyntaxExtensionKind::NonMacroAttr { .. } => Transparency::Opaque,
609 SyntaxExtensionKind::LegacyBang(..) |
610 SyntaxExtensionKind::LegacyAttr(..) |
611 SyntaxExtensionKind::LegacyDerive(..) => Transparency::SemiTransparent,
616 impl SyntaxExtension {
617 /// Returns which kind of macro calls this syntax extension.
618 pub fn macro_kind(&self) -> MacroKind {
620 SyntaxExtensionKind::Bang(..) |
621 SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
622 SyntaxExtensionKind::Attr(..) |
623 SyntaxExtensionKind::LegacyAttr(..) |
624 SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
625 SyntaxExtensionKind::Derive(..) |
626 SyntaxExtensionKind::LegacyDerive(..) => MacroKind::Derive,
630 /// Constructs a syntax extension with default properties.
631 pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
634 default_transparency: kind.default_transparency(),
635 allow_internal_unstable: None,
636 allow_internal_unsafe: false,
637 local_inner_macros: false,
640 helper_attrs: Vec::new(),
647 pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
648 fn expander<'cx>(_: &'cx mut ExtCtxt<'_>, span: Span, _: &[TokenTree])
649 -> Box<dyn MacResult + 'cx> {
650 DummyResult::any(span)
652 SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
655 pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
656 fn expander(_: &mut ExtCtxt<'_>, _: Span, _: &ast::MetaItem, _: Annotatable)
657 -> Vec<Annotatable> {
660 SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
663 pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
664 SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
667 pub fn expn_info(&self, call_site: Span, descr: Symbol) -> ExpnInfo {
670 kind: ExpnKind::Macro(self.macro_kind(), descr),
672 default_transparency: self.default_transparency,
673 allow_internal_unstable: self.allow_internal_unstable.clone(),
674 allow_internal_unsafe: self.allow_internal_unsafe,
675 local_inner_macros: self.local_inner_macros,
676 edition: self.edition,
681 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
683 /// Error type that denotes indeterminacy.
684 pub struct Indeterminate;
687 fn next_node_id(&mut self) -> ast::NodeId;
689 fn get_module_scope(&mut self, id: ast::NodeId) -> ExpnId;
691 fn resolve_dollar_crates(&mut self);
692 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment,
694 fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension);
696 fn resolve_imports(&mut self);
698 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: ExpnId, force: bool)
699 -> Result<Option<Lrc<SyntaxExtension>>, Indeterminate>;
701 fn check_unused_macros(&self);
705 pub struct ModuleData {
706 pub mod_path: Vec<ast::Ident>,
707 pub directory: PathBuf,
711 pub struct ExpansionData {
714 pub module: Rc<ModuleData>,
715 pub directory_ownership: DirectoryOwnership,
718 /// One of these is made during expansion and incrementally updated as we go;
719 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
720 /// -> expn_info` of their expansion context stored into their span.
721 pub struct ExtCtxt<'a> {
722 pub parse_sess: &'a parse::ParseSess,
723 pub ecfg: expand::ExpansionConfig<'a>,
724 pub root_path: PathBuf,
725 pub resolver: &'a mut dyn Resolver,
726 pub current_expansion: ExpansionData,
727 pub expansions: FxHashMap<Span, Vec<String>>,
728 pub allow_derive_markers: Lrc<[Symbol]>,
731 impl<'a> ExtCtxt<'a> {
732 pub fn new(parse_sess: &'a parse::ParseSess,
733 ecfg: expand::ExpansionConfig<'a>,
734 resolver: &'a mut dyn Resolver)
739 root_path: PathBuf::new(),
741 current_expansion: ExpansionData {
744 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
745 directory_ownership: DirectoryOwnership::Owned { relative: None },
747 expansions: FxHashMap::default(),
748 allow_derive_markers: [sym::rustc_attrs, sym::structural_match][..].into(),
752 /// Returns a `Folder` for deeply expanding all macros in an AST node.
753 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
754 expand::MacroExpander::new(self, false)
757 /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
758 /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
759 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
760 expand::MacroExpander::new(self, true)
763 pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
764 parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect(), MACRO_ARGUMENTS)
766 pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
767 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
768 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
769 pub fn call_site(&self) -> Span {
770 match self.current_expansion.id.expn_info() {
771 Some(expn_info) => expn_info.call_site,
775 pub fn backtrace(&self) -> SyntaxContext {
776 SyntaxContext::empty().apply_mark(self.current_expansion.id)
779 /// Returns span for the macro which originally caused the current expansion to happen.
781 /// Stops backtracing at include! boundary.
782 pub fn expansion_cause(&self) -> Option<Span> {
783 let mut ctxt = self.backtrace();
784 let mut last_macro = None;
786 if ctxt.outer_expn_info().map_or(None, |info| {
787 if info.kind.descr() == sym::include {
788 // Stop going up the backtrace once include! is encountered
791 ctxt = info.call_site.ctxt();
792 last_macro = Some(info.call_site);
801 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
804 -> DiagnosticBuilder<'a> {
805 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
807 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
810 -> DiagnosticBuilder<'a> {
811 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
813 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
816 -> DiagnosticBuilder<'a> {
817 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
820 /// Emit `msg` attached to `sp`, and stop compilation immediately.
822 /// `span_err` should be strongly preferred where-ever possible:
823 /// this should *only* be used when:
825 /// - continuing has a high risk of flow-on errors (e.g., errors in
826 /// declaring a macro would cause all uses of that macro to
827 /// complain about "undefined macro"), or
828 /// - there is literally nothing else that can be done (however,
829 /// in most cases one can construct a dummy expression/item to
830 /// substitute; we never hit resolve/type-checking so the dummy
831 /// value doesn't have to match anything)
832 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
833 self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
836 /// Emit `msg` attached to `sp`, without immediately stopping
839 /// Compilation will be stopped in the near future (at the end of
840 /// the macro expansion phase).
841 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
842 self.parse_sess.span_diagnostic.span_err(sp, msg);
844 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
845 self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
847 pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
848 -> DiagnosticBuilder<'a> {
849 self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
851 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
852 self.parse_sess.span_diagnostic.span_warn(sp, msg);
854 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
855 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
857 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
858 self.parse_sess.span_diagnostic.span_bug(sp, msg);
860 pub fn trace_macros_diag(&mut self) {
861 for (sp, notes) in self.expansions.iter() {
862 let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
868 // Fixme: does this result in errors?
869 self.expansions.clear();
871 pub fn bug(&self, msg: &str) -> ! {
872 self.parse_sess.span_diagnostic.bug(msg);
874 pub fn trace_macros(&self) -> bool {
877 pub fn set_trace_macros(&mut self, x: bool) {
878 self.ecfg.trace_mac = x
880 pub fn ident_of(&self, st: &str) -> ast::Ident {
881 ast::Ident::from_str(st)
883 pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
884 let def_site = DUMMY_SP.apply_mark(self.current_expansion.id);
885 iter::once(Ident::new(kw::DollarCrate, def_site))
886 .chain(components.iter().map(|&s| Ident::with_empty_ctxt(s)))
889 pub fn name_of(&self, st: &str) -> ast::Name {
893 pub fn check_unused_macros(&self) {
894 self.resolver.check_unused_macros();
897 /// Resolve a path mentioned inside Rust code.
899 /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
901 /// Returns an absolute path to the file that `path` refers to.
902 pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PathBuf {
903 let path = path.into();
905 // Relative paths are resolved relative to the file in which they are found
906 // after macro expansion (that is, they are unhygienic).
907 if !path.is_absolute() {
908 let callsite = span.source_callsite();
909 let mut result = match self.source_map().span_to_unmapped_path(callsite) {
910 FileName::Real(path) => path,
911 FileName::DocTest(path, _) => path,
912 other => panic!("cannot resolve relative path in non-file source `{}`", other),
923 /// Extracts a string literal from the macro expanded version of `expr`,
924 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
925 /// compilation on error, merely emits a non-fatal error and returns `None`.
926 pub fn expr_to_spanned_string<'a>(
927 cx: &'a mut ExtCtxt<'_>,
928 mut expr: P<ast::Expr>,
930 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, Option<DiagnosticBuilder<'a>>> {
931 // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
932 expr.span = expr.span.apply_mark(cx.current_expansion.id);
934 // we want to be able to handle e.g., `concat!("foo", "bar")`
935 cx.expander().visit_expr(&mut expr);
936 Err(match expr.node {
937 ast::ExprKind::Lit(ref l) => match l.node {
938 ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
939 ast::LitKind::Err(_) => None,
940 _ => Some(cx.struct_span_err(l.span, err_msg))
942 ast::ExprKind::Err => None,
943 _ => Some(cx.struct_span_err(expr.span, err_msg))
947 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
948 -> Option<(Symbol, ast::StrStyle)> {
949 expr_to_spanned_string(cx, expr, err_msg)
950 .map_err(|err| err.map(|mut err| err.emit()))
955 /// Non-fatally assert that `tts` is empty. Note that this function
956 /// returns even when `tts` is non-empty, macros that *need* to stop
957 /// compilation should call
958 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
959 /// done as rarely as possible).
960 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
962 tts: &[tokenstream::TokenTree],
965 cx.span_err(sp, &format!("{} takes no arguments", name));
969 /// Interpreting `tts` as a comma-separated sequence of expressions,
970 /// expect exactly one string literal, or emit an error and return `None`.
971 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
973 tts: &[tokenstream::TokenTree],
976 let mut p = cx.new_parser_from_tts(tts);
977 if p.token == token::Eof {
978 cx.span_err(sp, &format!("{} takes 1 argument", name));
981 let ret = panictry!(p.parse_expr());
982 let _ = p.eat(&token::Comma);
984 if p.token != token::Eof {
985 cx.span_err(sp, &format!("{} takes 1 argument", name));
987 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
992 /// Extracts comma-separated expressions from `tts`. If there is a
993 /// parsing error, emit a non-fatal error and return `None`.
994 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
996 tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
997 let mut p = cx.new_parser_from_tts(tts);
998 let mut es = Vec::new();
999 while p.token != token::Eof {
1000 let mut expr = panictry!(p.parse_expr());
1001 cx.expander().visit_expr(&mut expr);
1003 if p.eat(&token::Comma) {
1006 if p.token != token::Eof {
1007 cx.span_err(sp, "expected token: `,`");