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::{MultiDecorator, MultiModifier, NormalTT, IdentTT};
13 use ast::{self, Attribute, Name, PatKind, MetaItem};
15 use codemap::{self, CodeMap, Spanned, respan};
16 use syntax_pos::{Span, DUMMY_SP};
17 use errors::DiagnosticBuilder;
18 use ext::expand::{self, Expansion, Invocation};
19 use ext::hygiene::{Mark, SyntaxContext};
20 use fold::{self, Folder};
21 use parse::{self, parser, DirectoryOwnership};
25 use util::small_vector::SmallVector;
27 use std::path::PathBuf;
29 use std::default::Default;
30 use tokenstream::{self, TokenStream};
33 #[derive(Debug,Clone)]
34 pub enum Annotatable {
36 TraitItem(P<ast::TraitItem>),
37 ImplItem(P<ast::ImplItem>),
40 impl HasAttrs for Annotatable {
41 fn attrs(&self) -> &[Attribute] {
43 Annotatable::Item(ref item) => &item.attrs,
44 Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
45 Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
49 fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
51 Annotatable::Item(item) => Annotatable::Item(item.map_attrs(f)),
52 Annotatable::TraitItem(trait_item) => Annotatable::TraitItem(trait_item.map_attrs(f)),
53 Annotatable::ImplItem(impl_item) => Annotatable::ImplItem(impl_item.map_attrs(f)),
59 pub fn span(&self) -> Span {
61 Annotatable::Item(ref item) => item.span,
62 Annotatable::TraitItem(ref trait_item) => trait_item.span,
63 Annotatable::ImplItem(ref impl_item) => impl_item.span,
67 pub fn expect_item(self) -> P<ast::Item> {
69 Annotatable::Item(i) => i,
70 _ => panic!("expected Item")
74 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
75 where F: FnMut(P<ast::Item>) -> P<ast::Item>,
76 G: FnMut(Annotatable) -> Annotatable
79 Annotatable::Item(i) => Annotatable::Item(f(i)),
84 pub fn expect_trait_item(self) -> ast::TraitItem {
86 Annotatable::TraitItem(i) => i.unwrap(),
87 _ => panic!("expected Item")
91 pub fn expect_impl_item(self) -> ast::ImplItem {
93 Annotatable::ImplItem(i) => i.unwrap(),
94 _ => panic!("expected Item")
99 // A more flexible ItemDecorator.
100 pub trait MultiItemDecorator {
104 meta_item: &ast::MetaItem,
106 push: &mut FnMut(Annotatable));
109 impl<F> MultiItemDecorator for F
110 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
115 meta_item: &ast::MetaItem,
117 push: &mut FnMut(Annotatable)) {
118 (*self)(ecx, sp, meta_item, item, push)
122 // `meta_item` is the annotation, and `item` is the item being modified.
123 // FIXME Decorators should follow the same pattern too.
124 pub trait MultiItemModifier {
128 meta_item: &ast::MetaItem,
133 impl<F, T> MultiItemModifier for F
134 where F: Fn(&mut ExtCtxt, Span, &ast::MetaItem, Annotatable) -> T,
135 T: Into<Vec<Annotatable>>,
140 meta_item: &ast::MetaItem,
142 -> Vec<Annotatable> {
143 (*self)(ecx, span, meta_item, item).into()
147 impl Into<Vec<Annotatable>> for Annotatable {
148 fn into(self) -> Vec<Annotatable> {
153 pub trait ProcMacro {
154 fn expand<'cx>(&self,
155 ecx: &'cx mut ExtCtxt,
161 impl<F> ProcMacro for F
162 where F: Fn(TokenStream) -> TokenStream
164 fn expand<'cx>(&self,
165 _ecx: &'cx mut ExtCtxt,
169 // FIXME setup implicit context in TLS before calling self.
174 pub trait AttrProcMacro {
175 fn expand<'cx>(&self,
176 ecx: &'cx mut ExtCtxt,
178 annotation: TokenStream,
179 annotated: TokenStream)
183 impl<F> AttrProcMacro for F
184 where F: Fn(TokenStream, TokenStream) -> TokenStream
186 fn expand<'cx>(&self,
187 _ecx: &'cx mut ExtCtxt,
189 annotation: TokenStream,
190 annotated: TokenStream)
192 // FIXME setup implicit context in TLS before calling self.
193 (*self)(annotation, annotated)
197 /// Represents a thing that maps token trees to Macro Results
198 pub trait TTMacroExpander {
199 fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream)
200 -> Box<MacResult+'cx>;
203 pub type MacroExpanderFn =
204 for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
205 -> Box<MacResult+'cx>;
207 impl<F> TTMacroExpander for F
208 where F: for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree]) -> Box<MacResult+'cx>
210 fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream)
211 -> Box<MacResult+'cx> {
212 struct AvoidInterpolatedIdents;
214 impl Folder for AvoidInterpolatedIdents {
215 fn fold_tt(&mut self, tt: tokenstream::TokenTree) -> tokenstream::TokenTree {
216 if let tokenstream::TokenTree::Token(_, token::Interpolated(ref nt)) = tt {
217 if let token::NtIdent(ident) = **nt {
218 return tokenstream::TokenTree::Token(ident.span, token::Ident(ident.node));
221 fold::noop_fold_tt(tt, self)
224 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
225 fold::noop_fold_mac(mac, self)
230 input.trees().map(|tt| AvoidInterpolatedIdents.fold_tt(tt)).collect();
231 (*self)(ecx, span, &input)
235 pub trait IdentMacroExpander {
236 fn expand<'cx>(&self,
237 cx: &'cx mut ExtCtxt,
240 token_tree: Vec<tokenstream::TokenTree>)
241 -> Box<MacResult+'cx>;
244 pub type IdentMacroExpanderFn =
245 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<tokenstream::TokenTree>)
246 -> Box<MacResult+'cx>;
248 impl<F> IdentMacroExpander for F
249 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
250 Vec<tokenstream::TokenTree>) -> Box<MacResult+'cx>
252 fn expand<'cx>(&self,
253 cx: &'cx mut ExtCtxt,
256 token_tree: Vec<tokenstream::TokenTree>)
257 -> Box<MacResult+'cx>
259 (*self)(cx, sp, ident, token_tree)
263 // Use a macro because forwarding to a simple function has type system issues
264 macro_rules! make_stmts_default {
266 $me.make_expr().map(|e| SmallVector::one(ast::Stmt {
267 id: ast::DUMMY_NODE_ID,
269 node: ast::StmtKind::Expr(e),
274 /// The result of a macro expansion. The return values of the various
275 /// methods are spliced into the AST at the callsite of the macro.
276 pub trait MacResult {
277 /// Create an expression.
278 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
281 /// Create zero or more items.
282 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
286 /// Create zero or more impl items.
287 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> {
291 /// Create zero or more trait items.
292 fn make_trait_items(self: Box<Self>) -> Option<SmallVector<ast::TraitItem>> {
296 /// Create a pattern.
297 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
301 /// Create zero or more statements.
303 /// By default this attempts to create an expression statement,
304 /// returning None if that fails.
305 fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> {
306 make_stmts_default!(self)
309 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
314 macro_rules! make_MacEager {
315 ( $( $fld:ident: $t:ty, )* ) => {
316 /// `MacResult` implementation for the common case where you've already
317 /// built each form of AST that you might return.
319 pub struct MacEager {
321 pub $fld: Option<$t>,
327 pub fn $fld(v: $t) -> Box<MacResult> {
341 items: SmallVector<P<ast::Item>>,
342 impl_items: SmallVector<ast::ImplItem>,
343 trait_items: SmallVector<ast::TraitItem>,
344 stmts: SmallVector<ast::Stmt>,
348 impl MacResult for MacEager {
349 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
353 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
357 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> {
361 fn make_trait_items(self: Box<Self>) -> Option<SmallVector<ast::TraitItem>> {
365 fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> {
366 match self.stmts.as_ref().map_or(0, |s| s.len()) {
367 0 => make_stmts_default!(self),
372 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
373 if let Some(p) = self.pat {
376 if let Some(e) = self.expr {
377 if let ast::ExprKind::Lit(_) = e.node {
378 return Some(P(ast::Pat {
379 id: ast::DUMMY_NODE_ID,
381 node: PatKind::Lit(e),
388 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
393 /// Fill-in macro expansion result, to allow compilation to continue
394 /// after hitting errors.
395 #[derive(Copy, Clone)]
396 pub struct DummyResult {
402 /// Create a default MacResult that can be anything.
404 /// Use this as a return value after hitting any errors and
405 /// calling `span_err`.
406 pub fn any(sp: Span) -> Box<MacResult+'static> {
407 Box::new(DummyResult { expr_only: false, span: sp })
410 /// Create a default MacResult that can only be an expression.
412 /// Use this for macros that must expand to an expression, so even
413 /// if an error is encountered internally, the user will receive
414 /// an error that they also used it in the wrong place.
415 pub fn expr(sp: Span) -> Box<MacResult+'static> {
416 Box::new(DummyResult { expr_only: true, span: sp })
419 /// A plain dummy expression.
420 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
422 id: ast::DUMMY_NODE_ID,
423 node: ast::ExprKind::Lit(P(codemap::respan(sp, ast::LitKind::Bool(false)))),
425 attrs: ast::ThinVec::new(),
429 /// A plain dummy pattern.
430 pub fn raw_pat(sp: Span) -> ast::Pat {
432 id: ast::DUMMY_NODE_ID,
438 pub fn raw_ty(sp: Span) -> P<ast::Ty> {
440 id: ast::DUMMY_NODE_ID,
441 node: ast::TyKind::Infer,
447 impl MacResult for DummyResult {
448 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
449 Some(DummyResult::raw_expr(self.span))
452 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
453 Some(P(DummyResult::raw_pat(self.span)))
456 fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
457 // this code needs a comment... why not always just return the Some() ?
461 Some(SmallVector::new())
465 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<ast::ImplItem>> {
469 Some(SmallVector::new())
473 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVector<ast::TraitItem>> {
477 Some(SmallVector::new())
481 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<ast::Stmt>> {
482 Some(SmallVector::one(ast::Stmt {
483 id: ast::DUMMY_NODE_ID,
484 node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span)),
489 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
490 Some(DummyResult::raw_ty(self.span))
494 pub type BuiltinDeriveFn =
495 for<'cx> fn(&'cx mut ExtCtxt, Span, &MetaItem, &Annotatable, &mut FnMut(Annotatable));
497 /// Represents different kinds of macro invocations that can be resolved.
498 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
500 /// A bang macro - foo!()
502 /// An attribute macro - #[foo]
504 /// A derive attribute macro - #[derive(Foo)]
508 /// An enum representing the different kinds of syntax extensions.
509 pub enum SyntaxExtension {
510 /// A syntax extension that is attached to an item and creates new items
513 /// `#[derive(...)]` is a `MultiItemDecorator`.
515 /// Prefer ProcMacro or MultiModifier since they are more flexible.
516 MultiDecorator(Box<MultiItemDecorator>),
518 /// A syntax extension that is attached to an item and modifies it
519 /// in-place. Also allows decoration, i.e., creating new items.
520 MultiModifier(Box<MultiItemModifier>),
522 /// A function-like procedural macro. TokenStream -> TokenStream.
523 ProcMacro(Box<ProcMacro>),
525 /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
526 /// The first TokenSteam is the attribute, the second is the annotated item.
527 /// Allows modification of the input items and adding new items, similar to
528 /// MultiModifier, but uses TokenStreams, rather than AST nodes.
529 AttrProcMacro(Box<AttrProcMacro>),
531 /// A normal, function-like syntax extension.
533 /// `bytes!` is a `NormalTT`.
535 /// The `bool` dictates whether the contents of the macro can
536 /// directly use `#[unstable]` things (true == yes).
537 NormalTT(Box<TTMacroExpander>, Option<Span>, bool),
539 /// A function-like syntax extension that has an extra ident before
542 IdentTT(Box<IdentMacroExpander>, Option<Span>, bool),
544 /// An attribute-like procedural macro. TokenStream -> TokenStream.
545 /// The input is the annotated item.
546 /// Allows generating code to implement a Trait for a given struct
548 ProcMacroDerive(Box<MultiItemModifier>, Vec<Symbol> /* inert attribute names */),
550 /// An attribute-like procedural macro that derives a builtin trait.
551 BuiltinDerive(BuiltinDeriveFn),
554 impl SyntaxExtension {
555 /// Return which kind of macro calls this syntax extension.
556 pub fn kind(&self) -> MacroKind {
558 SyntaxExtension::NormalTT(..) |
559 SyntaxExtension::IdentTT(..) |
560 SyntaxExtension::ProcMacro(..) =>
562 SyntaxExtension::MultiDecorator(..) |
563 SyntaxExtension::MultiModifier(..) |
564 SyntaxExtension::AttrProcMacro(..) =>
566 SyntaxExtension::ProcMacroDerive(..) |
567 SyntaxExtension::BuiltinDerive(..) =>
573 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
576 fn next_node_id(&mut self) -> ast::NodeId;
577 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
578 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item>;
579 fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool;
581 fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion, derives: &[Mark]);
582 fn add_builtin(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>);
584 fn resolve_imports(&mut self);
585 // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
586 fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<Attribute>) -> Option<Attribute>;
587 fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
588 -> Result<Option<Rc<SyntaxExtension>>, Determinacy>;
589 fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
590 -> Result<Rc<SyntaxExtension>, Determinacy>;
593 #[derive(Copy, Clone, Debug)]
594 pub enum Determinacy {
599 pub struct DummyResolver;
601 impl Resolver for DummyResolver {
602 fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
603 fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
604 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item }
605 fn is_whitelisted_legacy_custom_derive(&self, _name: Name) -> bool { false }
607 fn visit_expansion(&mut self, _invoc: Mark, _expansion: &Expansion, _derives: &[Mark]) {}
608 fn add_builtin(&mut self, _ident: ast::Ident, _ext: Rc<SyntaxExtension>) {}
610 fn resolve_imports(&mut self) {}
611 fn find_legacy_attr_invoc(&mut self, _attrs: &mut Vec<Attribute>) -> Option<Attribute> { None }
612 fn resolve_invoc(&mut self, _invoc: &mut Invocation, _scope: Mark, _force: bool)
613 -> Result<Option<Rc<SyntaxExtension>>, Determinacy> {
614 Err(Determinacy::Determined)
616 fn resolve_macro(&mut self, _scope: Mark, _path: &ast::Path, _kind: MacroKind,
617 _force: bool) -> Result<Rc<SyntaxExtension>, Determinacy> {
618 Err(Determinacy::Determined)
623 pub struct ModuleData {
624 pub mod_path: Vec<ast::Ident>,
625 pub directory: PathBuf,
629 pub struct ExpansionData {
632 pub module: Rc<ModuleData>,
633 pub directory_ownership: DirectoryOwnership,
636 /// One of these is made during expansion and incrementally updated as we go;
637 /// when a macro expansion occurs, the resulting nodes have the backtrace()
638 /// -> expn_info of their expansion context stored into their span.
639 pub struct ExtCtxt<'a> {
640 pub parse_sess: &'a parse::ParseSess,
641 pub ecfg: expand::ExpansionConfig<'a>,
642 pub crate_root: Option<&'static str>,
643 pub resolver: &'a mut Resolver,
644 pub resolve_err_count: usize,
645 pub current_expansion: ExpansionData,
648 impl<'a> ExtCtxt<'a> {
649 pub fn new(parse_sess: &'a parse::ParseSess,
650 ecfg: expand::ExpansionConfig<'a>,
651 resolver: &'a mut Resolver)
654 parse_sess: parse_sess,
658 resolve_err_count: 0,
659 current_expansion: ExpansionData {
662 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
663 directory_ownership: DirectoryOwnership::Owned,
668 /// Returns a `Folder` for deeply expanding all macros in an AST node.
669 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
670 expand::MacroExpander::new(self, false)
673 /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
674 /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
675 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
676 expand::MacroExpander::new(self, true)
679 pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
680 parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
682 pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() }
683 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
684 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
685 pub fn call_site(&self) -> Span {
686 match self.current_expansion.mark.expn_info() {
687 Some(expn_info) => expn_info.call_site,
691 pub fn backtrace(&self) -> SyntaxContext {
692 SyntaxContext::empty().apply_mark(self.current_expansion.mark)
695 /// Returns span for the macro which originally caused the current expansion to happen.
697 /// Stops backtracing at include! boundary.
698 pub fn expansion_cause(&self) -> Span {
699 let mut ctxt = self.backtrace();
700 let mut last_macro = None;
702 if ctxt.outer().expn_info().map_or(None, |info| {
703 if info.callee.name() == "include" {
704 // Stop going up the backtrace once include! is encountered
707 ctxt = info.call_site.ctxt;
708 last_macro = Some(info.call_site);
714 last_macro.expect("missing expansion backtrace")
717 pub fn struct_span_warn(&self,
720 -> DiagnosticBuilder<'a> {
721 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
723 pub fn struct_span_err(&self,
726 -> DiagnosticBuilder<'a> {
727 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
729 pub fn struct_span_fatal(&self,
732 -> DiagnosticBuilder<'a> {
733 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
736 /// Emit `msg` attached to `sp`, and stop compilation immediately.
738 /// `span_err` should be strongly preferred where-ever possible:
739 /// this should *only* be used when
740 /// - continuing has a high risk of flow-on errors (e.g. errors in
741 /// declaring a macro would cause all uses of that macro to
742 /// complain about "undefined macro"), or
743 /// - there is literally nothing else that can be done (however,
744 /// in most cases one can construct a dummy expression/item to
745 /// substitute; we never hit resolve/type-checking so the dummy
746 /// value doesn't have to match anything)
747 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
748 panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
751 /// Emit `msg` attached to `sp`, without immediately stopping
754 /// Compilation will be stopped in the near future (at the end of
755 /// the macro expansion phase).
756 pub fn span_err(&self, sp: Span, msg: &str) {
757 self.parse_sess.span_diagnostic.span_err(sp, msg);
759 pub fn span_warn(&self, sp: Span, msg: &str) {
760 self.parse_sess.span_diagnostic.span_warn(sp, msg);
762 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
763 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
765 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
766 self.parse_sess.span_diagnostic.span_bug(sp, msg);
768 pub fn span_label_without_error(&self, sp: Span, msg: &str, label: &str) {
769 self.parse_sess.span_diagnostic.span_label_without_error(sp, msg, label);
771 pub fn bug(&self, msg: &str) -> ! {
772 self.parse_sess.span_diagnostic.bug(msg);
774 pub fn trace_macros(&self) -> bool {
777 pub fn set_trace_macros(&mut self, x: bool) {
778 self.ecfg.trace_mac = x
780 pub fn ident_of(&self, st: &str) -> ast::Ident {
781 ast::Ident::from_str(st)
783 pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
784 let mut v = Vec::new();
785 if let Some(s) = self.crate_root {
786 v.push(self.ident_of(s));
788 v.extend(components.iter().map(|s| self.ident_of(s)));
791 pub fn name_of(&self, st: &str) -> ast::Name {
796 /// Extract a string literal from the macro expanded version of `expr`,
797 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
798 /// compilation on error, merely emits a non-fatal error and returns None.
799 pub fn expr_to_spanned_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
800 -> Option<Spanned<(Symbol, ast::StrStyle)>> {
801 // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
802 let expr = expr.map(|mut expr| {
803 expr.span.ctxt = expr.span.ctxt.apply_mark(cx.current_expansion.mark);
807 // we want to be able to handle e.g. concat("foo", "bar")
808 let expr = cx.expander().fold_expr(expr);
810 ast::ExprKind::Lit(ref l) => match l.node {
811 ast::LitKind::Str(s, style) => return Some(respan(expr.span, (s, style))),
812 _ => cx.span_err(l.span, err_msg)
814 _ => cx.span_err(expr.span, err_msg)
819 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
820 -> Option<(Symbol, ast::StrStyle)> {
821 expr_to_spanned_string(cx, expr, err_msg).map(|s| s.node)
824 /// Non-fatally assert that `tts` is empty. Note that this function
825 /// returns even when `tts` is non-empty, macros that *need* to stop
826 /// compilation should call
827 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
828 /// done as rarely as possible).
829 pub fn check_zero_tts(cx: &ExtCtxt,
831 tts: &[tokenstream::TokenTree],
834 cx.span_err(sp, &format!("{} takes no arguments", name));
838 /// Extract the string literal from the first token of `tts`. If this
839 /// is not a string literal, emit an error and return None.
840 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
842 tts: &[tokenstream::TokenTree],
845 let mut p = cx.new_parser_from_tts(tts);
846 if p.token == token::Eof {
847 cx.span_err(sp, &format!("{} takes 1 argument", name));
850 let ret = panictry!(p.parse_expr());
851 if p.token != token::Eof {
852 cx.span_err(sp, &format!("{} takes 1 argument", name));
854 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
859 /// Extract comma-separated expressions from `tts`. If there is a
860 /// parsing error, emit a non-fatal error and return None.
861 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
863 tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
864 let mut p = cx.new_parser_from_tts(tts);
865 let mut es = Vec::new();
866 while p.token != token::Eof {
867 es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
868 if p.eat(&token::Comma) {
871 if p.token != token::Eof {
872 cx.span_err(sp, "expected token: `,`");
879 pub struct ChangeSpan {
883 impl Folder for ChangeSpan {
884 fn new_span(&mut self, _sp: Span) -> Span {
888 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
889 fold::noop_fold_mac(mac, self)