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, ExpnInfo, Spanned, respan};
16 use syntax_pos::{Span, ExpnId, NO_EXPANSION};
17 use errors::{DiagnosticBuilder, FatalError};
18 use ext::expand::{self, Expansion, Invocation};
19 use ext::hygiene::Mark;
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 expect_item(self) -> P<ast::Item> {
61 Annotatable::Item(i) => i,
62 _ => panic!("expected Item")
66 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
67 where F: FnMut(P<ast::Item>) -> P<ast::Item>,
68 G: FnMut(Annotatable) -> Annotatable
71 Annotatable::Item(i) => Annotatable::Item(f(i)),
76 pub fn expect_trait_item(self) -> ast::TraitItem {
78 Annotatable::TraitItem(i) => i.unwrap(),
79 _ => panic!("expected Item")
83 pub fn expect_impl_item(self) -> ast::ImplItem {
85 Annotatable::ImplItem(i) => i.unwrap(),
86 _ => panic!("expected Item")
91 // A more flexible ItemDecorator.
92 pub trait MultiItemDecorator {
96 meta_item: &ast::MetaItem,
98 push: &mut FnMut(Annotatable));
101 impl<F> MultiItemDecorator for F
102 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
107 meta_item: &ast::MetaItem,
109 push: &mut FnMut(Annotatable)) {
110 (*self)(ecx, sp, meta_item, item, push)
114 // `meta_item` is the annotation, and `item` is the item being modified.
115 // FIXME Decorators should follow the same pattern too.
116 pub trait MultiItemModifier {
120 meta_item: &ast::MetaItem,
125 impl<F, T> MultiItemModifier for F
126 where F: Fn(&mut ExtCtxt, Span, &ast::MetaItem, Annotatable) -> T,
127 T: Into<Vec<Annotatable>>,
132 meta_item: &ast::MetaItem,
134 -> Vec<Annotatable> {
135 (*self)(ecx, span, meta_item, item).into()
139 impl Into<Vec<Annotatable>> for Annotatable {
140 fn into(self) -> Vec<Annotatable> {
145 pub trait ProcMacro {
146 fn expand<'cx>(&self,
147 ecx: &'cx mut ExtCtxt,
153 impl<F> ProcMacro for F
154 where F: Fn(TokenStream) -> TokenStream
156 fn expand<'cx>(&self,
157 _ecx: &'cx mut ExtCtxt,
161 // FIXME setup implicit context in TLS before calling self.
166 pub trait AttrProcMacro {
167 fn expand<'cx>(&self,
168 ecx: &'cx mut ExtCtxt,
170 annotation: TokenStream,
171 annotated: TokenStream)
175 impl<F> AttrProcMacro for F
176 where F: Fn(TokenStream, TokenStream) -> TokenStream
178 fn expand<'cx>(&self,
179 _ecx: &'cx mut ExtCtxt,
181 annotation: TokenStream,
182 annotated: TokenStream)
184 // FIXME setup implicit context in TLS before calling self.
185 (*self)(annotation, annotated)
189 /// Represents a thing that maps token trees to Macro Results
190 pub trait TTMacroExpander {
191 fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream)
192 -> Box<MacResult+'cx>;
195 pub type MacroExpanderFn =
196 for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
197 -> Box<MacResult+'cx>;
199 impl<F> TTMacroExpander for F
200 where F: for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree]) -> Box<MacResult+'cx>
202 fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream)
203 -> Box<MacResult+'cx> {
204 (*self)(ecx, span, &input.trees().collect::<Vec<_>>())
208 pub trait IdentMacroExpander {
209 fn expand<'cx>(&self,
210 cx: &'cx mut ExtCtxt,
213 token_tree: Vec<tokenstream::TokenTree>)
214 -> Box<MacResult+'cx>;
217 pub type IdentMacroExpanderFn =
218 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<tokenstream::TokenTree>)
219 -> Box<MacResult+'cx>;
221 impl<F> IdentMacroExpander for F
222 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
223 Vec<tokenstream::TokenTree>) -> Box<MacResult+'cx>
225 fn expand<'cx>(&self,
226 cx: &'cx mut ExtCtxt,
229 token_tree: Vec<tokenstream::TokenTree>)
230 -> Box<MacResult+'cx>
232 (*self)(cx, sp, ident, token_tree)
236 // Use a macro because forwarding to a simple function has type system issues
237 macro_rules! make_stmts_default {
239 $me.make_expr().map(|e| SmallVector::one(ast::Stmt {
240 id: ast::DUMMY_NODE_ID,
242 node: ast::StmtKind::Expr(e),
247 /// The result of a macro expansion. The return values of the various
248 /// methods are spliced into the AST at the callsite of the macro.
249 pub trait MacResult {
250 /// Create an expression.
251 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
254 /// Create zero or more items.
255 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
259 /// Create zero or more impl items.
260 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> {
264 /// Create zero or more trait items.
265 fn make_trait_items(self: Box<Self>) -> Option<SmallVector<ast::TraitItem>> {
269 /// Create a pattern.
270 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
274 /// Create zero or more statements.
276 /// By default this attempts to create an expression statement,
277 /// returning None if that fails.
278 fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> {
279 make_stmts_default!(self)
282 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
287 macro_rules! make_MacEager {
288 ( $( $fld:ident: $t:ty, )* ) => {
289 /// `MacResult` implementation for the common case where you've already
290 /// built each form of AST that you might return.
292 pub struct MacEager {
294 pub $fld: Option<$t>,
300 pub fn $fld(v: $t) -> Box<MacResult> {
314 items: SmallVector<P<ast::Item>>,
315 impl_items: SmallVector<ast::ImplItem>,
316 trait_items: SmallVector<ast::TraitItem>,
317 stmts: SmallVector<ast::Stmt>,
321 impl MacResult for MacEager {
322 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
326 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
330 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> {
334 fn make_trait_items(self: Box<Self>) -> Option<SmallVector<ast::TraitItem>> {
338 fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> {
339 match self.stmts.as_ref().map_or(0, |s| s.len()) {
340 0 => make_stmts_default!(self),
345 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
346 if let Some(p) = self.pat {
349 if let Some(e) = self.expr {
350 if let ast::ExprKind::Lit(_) = e.node {
351 return Some(P(ast::Pat {
352 id: ast::DUMMY_NODE_ID,
354 node: PatKind::Lit(e),
361 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
366 /// Fill-in macro expansion result, to allow compilation to continue
367 /// after hitting errors.
368 #[derive(Copy, Clone)]
369 pub struct DummyResult {
375 /// Create a default MacResult that can be anything.
377 /// Use this as a return value after hitting any errors and
378 /// calling `span_err`.
379 pub fn any(sp: Span) -> Box<MacResult+'static> {
380 Box::new(DummyResult { expr_only: false, span: sp })
383 /// Create a default MacResult that can only be an expression.
385 /// Use this for macros that must expand to an expression, so even
386 /// if an error is encountered internally, the user will receive
387 /// an error that they also used it in the wrong place.
388 pub fn expr(sp: Span) -> Box<MacResult+'static> {
389 Box::new(DummyResult { expr_only: true, span: sp })
392 /// A plain dummy expression.
393 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
395 id: ast::DUMMY_NODE_ID,
396 node: ast::ExprKind::Lit(P(codemap::respan(sp, ast::LitKind::Bool(false)))),
398 attrs: ast::ThinVec::new(),
402 /// A plain dummy pattern.
403 pub fn raw_pat(sp: Span) -> ast::Pat {
405 id: ast::DUMMY_NODE_ID,
411 pub fn raw_ty(sp: Span) -> P<ast::Ty> {
413 id: ast::DUMMY_NODE_ID,
414 node: ast::TyKind::Infer,
420 impl MacResult for DummyResult {
421 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
422 Some(DummyResult::raw_expr(self.span))
425 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
426 Some(P(DummyResult::raw_pat(self.span)))
429 fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
430 // this code needs a comment... why not always just return the Some() ?
434 Some(SmallVector::new())
438 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<ast::ImplItem>> {
442 Some(SmallVector::new())
446 fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVector<ast::TraitItem>> {
450 Some(SmallVector::new())
454 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<ast::Stmt>> {
455 Some(SmallVector::one(ast::Stmt {
456 id: ast::DUMMY_NODE_ID,
457 node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span)),
462 fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
463 Some(DummyResult::raw_ty(self.span))
467 pub type BuiltinDeriveFn =
468 for<'cx> fn(&'cx mut ExtCtxt, Span, &MetaItem, &Annotatable, &mut FnMut(Annotatable));
470 /// Represents different kinds of macro invocations that can be resolved.
471 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
473 /// A bang macro - foo!()
475 /// An attribute macro - #[foo]
477 /// A derive attribute macro - #[derive(Foo)]
481 /// An enum representing the different kinds of syntax extensions.
482 pub enum SyntaxExtension {
483 /// A syntax extension that is attached to an item and creates new items
486 /// `#[derive(...)]` is a `MultiItemDecorator`.
488 /// Prefer ProcMacro or MultiModifier since they are more flexible.
489 MultiDecorator(Box<MultiItemDecorator>),
491 /// A syntax extension that is attached to an item and modifies it
492 /// in-place. Also allows decoration, i.e., creating new items.
493 MultiModifier(Box<MultiItemModifier>),
495 /// A function-like procedural macro. TokenStream -> TokenStream.
496 ProcMacro(Box<ProcMacro>),
498 /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
499 /// The first TokenSteam is the attribute, the second is the annotated item.
500 /// Allows modification of the input items and adding new items, similar to
501 /// MultiModifier, but uses TokenStreams, rather than AST nodes.
502 AttrProcMacro(Box<AttrProcMacro>),
504 /// A normal, function-like syntax extension.
506 /// `bytes!` is a `NormalTT`.
508 /// The `bool` dictates whether the contents of the macro can
509 /// directly use `#[unstable]` things (true == yes).
510 NormalTT(Box<TTMacroExpander>, Option<Span>, bool),
512 /// A function-like syntax extension that has an extra ident before
515 IdentTT(Box<IdentMacroExpander>, Option<Span>, bool),
517 /// An attribute-like procedural macro. TokenStream -> TokenStream.
518 /// The input is the annotated item.
519 /// Allows generating code to implement a Trait for a given struct
521 ProcMacroDerive(Box<MultiItemModifier>, Vec<Symbol> /* inert attribute names */),
523 /// An attribute-like procedural macro that derives a builtin trait.
524 BuiltinDerive(BuiltinDeriveFn),
527 impl SyntaxExtension {
528 /// Return which kind of macro calls this syntax extension.
529 pub fn kind(&self) -> MacroKind {
531 SyntaxExtension::NormalTT(..) |
532 SyntaxExtension::IdentTT(..) |
533 SyntaxExtension::ProcMacro(..) =>
535 SyntaxExtension::MultiDecorator(..) |
536 SyntaxExtension::MultiModifier(..) |
537 SyntaxExtension::AttrProcMacro(..) =>
539 SyntaxExtension::ProcMacroDerive(..) |
540 SyntaxExtension::BuiltinDerive(..) =>
546 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
549 fn next_node_id(&mut self) -> ast::NodeId;
550 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
551 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item>;
552 fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool;
554 fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion, derives: &[Mark]);
555 fn add_builtin(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>);
557 fn resolve_imports(&mut self);
558 // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
559 fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<Attribute>) -> Option<Attribute>;
560 fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
561 -> Result<Option<Rc<SyntaxExtension>>, Determinacy>;
562 fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
563 -> Result<Rc<SyntaxExtension>, Determinacy>;
566 #[derive(Copy, Clone, Debug)]
567 pub enum Determinacy {
572 pub struct DummyResolver;
574 impl Resolver for DummyResolver {
575 fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
576 fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
577 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> { item }
578 fn is_whitelisted_legacy_custom_derive(&self, _name: Name) -> bool { false }
580 fn visit_expansion(&mut self, _invoc: Mark, _expansion: &Expansion, _derives: &[Mark]) {}
581 fn add_builtin(&mut self, _ident: ast::Ident, _ext: Rc<SyntaxExtension>) {}
583 fn resolve_imports(&mut self) {}
584 fn find_legacy_attr_invoc(&mut self, _attrs: &mut Vec<Attribute>) -> Option<Attribute> { None }
585 fn resolve_invoc(&mut self, _invoc: &mut Invocation, _scope: Mark, _force: bool)
586 -> Result<Option<Rc<SyntaxExtension>>, Determinacy> {
587 Err(Determinacy::Determined)
589 fn resolve_macro(&mut self, _scope: Mark, _path: &ast::Path, _kind: MacroKind,
590 _force: bool) -> Result<Rc<SyntaxExtension>, Determinacy> {
591 Err(Determinacy::Determined)
596 pub struct ModuleData {
597 pub mod_path: Vec<ast::Ident>,
598 pub directory: PathBuf,
602 pub struct ExpansionData {
605 pub backtrace: ExpnId,
606 pub module: Rc<ModuleData>,
607 pub directory_ownership: DirectoryOwnership,
610 /// One of these is made during expansion and incrementally updated as we go;
611 /// when a macro expansion occurs, the resulting nodes have the backtrace()
612 /// -> expn_info of their expansion context stored into their span.
613 pub struct ExtCtxt<'a> {
614 pub parse_sess: &'a parse::ParseSess,
615 pub ecfg: expand::ExpansionConfig<'a>,
616 pub crate_root: Option<&'static str>,
617 pub resolver: &'a mut Resolver,
618 pub resolve_err_count: usize,
619 pub current_expansion: ExpansionData,
622 impl<'a> ExtCtxt<'a> {
623 pub fn new(parse_sess: &'a parse::ParseSess,
624 ecfg: expand::ExpansionConfig<'a>,
625 resolver: &'a mut Resolver)
628 parse_sess: parse_sess,
632 resolve_err_count: 0,
633 current_expansion: ExpansionData {
636 backtrace: NO_EXPANSION,
637 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
638 directory_ownership: DirectoryOwnership::Owned,
643 /// Returns a `Folder` for deeply expanding all macros in an AST node.
644 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
645 expand::MacroExpander::new(self, false)
648 /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
649 /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
650 pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
651 expand::MacroExpander::new(self, true)
654 pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
655 parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
657 pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() }
658 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
659 pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
660 pub fn call_site(&self) -> Span {
661 self.codemap().with_expn_info(self.backtrace(), |ei| match ei {
662 Some(expn_info) => expn_info.call_site,
663 None => self.bug("missing top span")
666 pub fn backtrace(&self) -> ExpnId { self.current_expansion.backtrace }
668 /// Returns span for the macro which originally caused the current expansion to happen.
670 /// Stops backtracing at include! boundary.
671 pub fn expansion_cause(&self) -> Span {
672 let mut expn_id = self.backtrace();
673 let mut last_macro = None;
675 if self.codemap().with_expn_info(expn_id, |info| {
676 info.map_or(None, |i| {
677 if i.callee.name() == "include" {
678 // Stop going up the backtrace once include! is encountered
681 expn_id = i.call_site.expn_id;
682 last_macro = Some(i.call_site);
689 last_macro.expect("missing expansion backtrace")
692 pub fn bt_push(&mut self, ei: ExpnInfo) {
693 if self.current_expansion.depth > self.ecfg.recursion_limit {
694 let suggested_limit = self.ecfg.recursion_limit * 2;
695 let mut err = self.struct_span_fatal(ei.call_site,
696 &format!("recursion limit reached while expanding the macro `{}`",
699 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
705 let mut call_site = ei.call_site;
706 call_site.expn_id = self.backtrace();
707 self.current_expansion.backtrace = self.codemap().record_expansion(ExpnInfo {
708 call_site: call_site,
712 pub fn bt_pop(&mut self) {}
714 pub fn struct_span_warn(&self,
717 -> DiagnosticBuilder<'a> {
718 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
720 pub fn struct_span_err(&self,
723 -> DiagnosticBuilder<'a> {
724 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
726 pub fn struct_span_fatal(&self,
729 -> DiagnosticBuilder<'a> {
730 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
733 /// Emit `msg` attached to `sp`, and stop compilation immediately.
735 /// `span_err` should be strongly preferred where-ever possible:
736 /// this should *only* be used when
737 /// - continuing has a high risk of flow-on errors (e.g. errors in
738 /// declaring a macro would cause all uses of that macro to
739 /// complain about "undefined macro"), or
740 /// - there is literally nothing else that can be done (however,
741 /// in most cases one can construct a dummy expression/item to
742 /// substitute; we never hit resolve/type-checking so the dummy
743 /// value doesn't have to match anything)
744 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
745 panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
748 /// Emit `msg` attached to `sp`, without immediately stopping
751 /// Compilation will be stopped in the near future (at the end of
752 /// the macro expansion phase).
753 pub fn span_err(&self, sp: Span, msg: &str) {
754 self.parse_sess.span_diagnostic.span_err(sp, msg);
756 pub fn span_warn(&self, sp: Span, msg: &str) {
757 self.parse_sess.span_diagnostic.span_warn(sp, msg);
759 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
760 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
762 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
763 self.parse_sess.span_diagnostic.span_bug(sp, msg);
765 pub fn bug(&self, msg: &str) -> ! {
766 self.parse_sess.span_diagnostic.bug(msg);
768 pub fn trace_macros(&self) -> bool {
771 pub fn set_trace_macros(&mut self, x: bool) {
772 self.ecfg.trace_mac = x
774 pub fn ident_of(&self, st: &str) -> ast::Ident {
775 ast::Ident::from_str(st)
777 pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
778 let mut v = Vec::new();
779 if let Some(s) = self.crate_root {
780 v.push(self.ident_of(s));
782 v.extend(components.iter().map(|s| self.ident_of(s)));
785 pub fn name_of(&self, st: &str) -> ast::Name {
790 /// Extract a string literal from the macro expanded version of `expr`,
791 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
792 /// compilation on error, merely emits a non-fatal error and returns None.
793 pub fn expr_to_spanned_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
794 -> Option<Spanned<(Symbol, ast::StrStyle)>> {
795 // Update `expr.span`'s expn_id now in case expr is an `include!` macro invocation.
796 let expr = expr.map(|mut expr| {
797 expr.span.expn_id = cx.backtrace();
801 // we want to be able to handle e.g. concat("foo", "bar")
802 let expr = cx.expander().fold_expr(expr);
804 ast::ExprKind::Lit(ref l) => match l.node {
805 ast::LitKind::Str(s, style) => return Some(respan(expr.span, (s, style))),
806 _ => cx.span_err(l.span, err_msg)
808 _ => cx.span_err(expr.span, err_msg)
813 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
814 -> Option<(Symbol, ast::StrStyle)> {
815 expr_to_spanned_string(cx, expr, err_msg).map(|s| s.node)
818 /// Non-fatally assert that `tts` is empty. Note that this function
819 /// returns even when `tts` is non-empty, macros that *need* to stop
820 /// compilation should call
821 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
822 /// done as rarely as possible).
823 pub fn check_zero_tts(cx: &ExtCtxt,
825 tts: &[tokenstream::TokenTree],
828 cx.span_err(sp, &format!("{} takes no arguments", name));
832 /// Extract the string literal from the first token of `tts`. If this
833 /// is not a string literal, emit an error and return None.
834 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
836 tts: &[tokenstream::TokenTree],
839 let mut p = cx.new_parser_from_tts(tts);
840 if p.token == token::Eof {
841 cx.span_err(sp, &format!("{} takes 1 argument", name));
844 let ret = panictry!(p.parse_expr());
845 if p.token != token::Eof {
846 cx.span_err(sp, &format!("{} takes 1 argument", name));
848 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
853 /// Extract comma-separated expressions from `tts`. If there is a
854 /// parsing error, emit a non-fatal error and return None.
855 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
857 tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
858 let mut p = cx.new_parser_from_tts(tts);
859 let mut es = Vec::new();
860 while p.token != token::Eof {
861 es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
862 if p.eat(&token::Comma) {
865 if p.token != token::Eof {
866 cx.span_err(sp, "expected token: `,`");
873 pub struct ChangeSpan {
877 impl Folder for ChangeSpan {
878 fn new_span(&mut self, _sp: Span) -> Span {
882 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
883 fold::noop_fold_mac(mac, self)