1 // Copyright 2012-2014 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::*;
16 use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION};
19 use ext::tt::macro_rules;
23 use parse::token::{InternedString, intern, str_to_ident};
25 use util::small_vector::SmallVector;
29 use std::collections::HashMap;
32 pub trait ItemDecorator {
36 meta_item: &ast::MetaItem,
38 push: Box<FnMut(P<ast::Item>)>);
41 impl<F> ItemDecorator for F
42 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &ast::Item, Box<FnMut(P<ast::Item>)>)
47 meta_item: &ast::MetaItem,
49 push: Box<FnMut(P<ast::Item>)>) {
50 (*self)(ecx, sp, meta_item, item, push)
54 pub trait ItemModifier {
58 meta_item: &ast::MetaItem,
63 impl<F> ItemModifier for F
64 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, P<ast::Item>) -> P<ast::Item>
69 meta_item: &ast::MetaItem,
72 (*self)(ecx, span, meta_item, item)
77 pub enum Annotatable {
79 TraitItem(ast::TraitItem),
80 ImplItem(ast::ImplItem),
84 pub fn attrs(&self) -> &[ast::Attribute] {
86 Annotatable::Item(ref i) => &i.attrs[],
87 Annotatable::TraitItem(ref i) => match *i {
88 ast::TraitItem::RequiredMethod(ref tm) => &tm.attrs[],
89 ast::TraitItem::ProvidedMethod(ref m) => &m.attrs[],
90 ast::TraitItem::TypeTraitItem(ref at) => &at.attrs[],
92 Annotatable::ImplItem(ref i) => match *i {
93 ast::ImplItem::MethodImplItem(ref m) => &m.attrs[],
94 ast::ImplItem::TypeImplItem(ref t) => &t.attrs[],
99 pub fn fold_attrs(self, attrs: Vec<ast::Attribute>) -> Annotatable {
101 Annotatable::Item(i) => Annotatable::Item(P(ast::Item {
105 Annotatable::TraitItem(i) => match i {
106 ast::TraitItem::RequiredMethod(tm) => Annotatable::TraitItem(
107 ast::TraitItem::RequiredMethod(
108 ast::TypeMethod { attrs: attrs, ..tm })),
109 ast::TraitItem::ProvidedMethod(m) => Annotatable::TraitItem(
110 ast::TraitItem::ProvidedMethod(P(
111 ast::Method { attrs: attrs, ..(*m).clone() }))),
112 ast::TraitItem::TypeTraitItem(at) => Annotatable::TraitItem(
113 ast::TraitItem::TypeTraitItem(P(
114 ast::AssociatedType { attrs: attrs, ..(*at).clone() }))),
116 Annotatable::ImplItem(i) => match i {
117 ast::ImplItem::MethodImplItem(m) => Annotatable::ImplItem(
118 ast::ImplItem::MethodImplItem(P(
119 ast::Method { attrs: attrs, ..(*m).clone() }))),
120 ast::ImplItem::TypeImplItem(t) => Annotatable::ImplItem(
121 ast::ImplItem::TypeImplItem(P(
122 ast::Typedef { attrs: attrs, ..(*t).clone() }))),
127 pub fn expect_item(self) -> P<ast::Item> {
129 Annotatable::Item(i) => i,
130 _ => panic!("expected Item")
134 pub fn expect_trait_item(self) -> ast::TraitItem {
136 Annotatable::TraitItem(i) => i,
137 _ => panic!("expected Item")
141 pub fn expect_impl_item(self) -> ast::ImplItem {
143 Annotatable::ImplItem(i) => i,
144 _ => panic!("expected Item")
149 // A more flexible ItemModifier (ItemModifier should go away, eventually, FIXME).
150 // meta_item is the annotation, item is the item being modified, parent_item
151 // is the impl or trait item is declared in if item is part of such a thing.
152 // FIXME Decorators should follow the same pattern too.
153 pub trait MultiItemModifier {
157 meta_item: &ast::MetaItem,
162 impl<F> MultiItemModifier for F
163 where F: Fn(&mut ExtCtxt,
166 Annotatable) -> Annotatable
171 meta_item: &ast::MetaItem,
174 (*self)(ecx, span, meta_item, item)
178 /// Represents a thing that maps token trees to Macro Results
179 pub trait TTMacroExpander {
180 fn expand<'cx>(&self,
181 ecx: &'cx mut ExtCtxt,
183 token_tree: &[ast::TokenTree])
184 -> Box<MacResult+'cx>;
187 pub type MacroExpanderFn =
188 for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
190 impl<F> TTMacroExpander for F
191 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>
193 fn expand<'cx>(&self,
194 ecx: &'cx mut ExtCtxt,
196 token_tree: &[ast::TokenTree])
197 -> Box<MacResult+'cx> {
198 (*self)(ecx, span, token_tree)
202 pub trait IdentMacroExpander {
203 fn expand<'cx>(&self,
204 cx: &'cx mut ExtCtxt,
207 token_tree: Vec<ast::TokenTree> )
208 -> Box<MacResult+'cx>;
211 pub type IdentMacroExpanderFn =
212 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
214 impl<F> IdentMacroExpander for F
215 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
216 Vec<ast::TokenTree>) -> Box<MacResult+'cx>
218 fn expand<'cx>(&self,
219 cx: &'cx mut ExtCtxt,
222 token_tree: Vec<ast::TokenTree> )
223 -> Box<MacResult+'cx>
225 (*self)(cx, sp, ident, token_tree)
229 /// The result of a macro expansion. The return values of the various
230 /// methods are spliced into the AST at the callsite of the macro (or
231 /// just into the compiler's internal macro table, for `make_def`).
232 pub trait MacResult {
233 /// Create an expression.
234 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
237 /// Create zero or more items.
238 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
242 /// Create zero or more methods.
243 fn make_methods(self: Box<Self>) -> Option<SmallVector<P<ast::Method>>> {
247 /// Create a pattern.
248 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
252 /// Create a statement.
254 /// By default this attempts to create an expression statement,
255 /// returning None if that fails.
256 fn make_stmt(self: Box<Self>) -> Option<P<ast::Stmt>> {
258 .map(|e| P(codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
262 /// A convenience type for macros that return a single expression.
267 pub fn new(e: P<ast::Expr>) -> Box<MacResult+'static> {
268 box MacExpr { e: e } as Box<MacResult+'static>
271 impl MacResult for MacExpr {
272 fn make_expr(self: Box<MacExpr>) -> Option<P<ast::Expr>> {
275 fn make_pat(self: Box<MacExpr>) -> Option<P<ast::Pat>> {
277 ast::ExprLit(_) => Some(P(ast::Pat {
278 id: ast::DUMMY_NODE_ID,
280 node: ast::PatLit(self.e)
286 /// A convenience type for macros that return a single pattern.
291 pub fn new(p: P<ast::Pat>) -> Box<MacResult+'static> {
292 box MacPat { p: p } as Box<MacResult+'static>
295 impl MacResult for MacPat {
296 fn make_pat(self: Box<MacPat>) -> Option<P<ast::Pat>> {
300 /// A type for macros that return multiple items.
301 pub struct MacItems {
302 items: SmallVector<P<ast::Item>>
306 pub fn new<I: Iterator<Item=P<ast::Item>>>(it: I) -> Box<MacResult+'static> {
307 box MacItems { items: it.collect() } as Box<MacResult+'static>
311 impl MacResult for MacItems {
312 fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> {
317 /// Fill-in macro expansion result, to allow compilation to continue
318 /// after hitting errors.
320 pub struct DummyResult {
326 /// Create a default MacResult that can be anything.
328 /// Use this as a return value after hitting any errors and
329 /// calling `span_err`.
330 pub fn any(sp: Span) -> Box<MacResult+'static> {
331 box DummyResult { expr_only: false, span: sp } as Box<MacResult+'static>
334 /// Create a default MacResult that can only be an expression.
336 /// Use this for macros that must expand to an expression, so even
337 /// if an error is encountered internally, the user will receive
338 /// an error that they also used it in the wrong place.
339 pub fn expr(sp: Span) -> Box<MacResult+'static> {
340 box DummyResult { expr_only: true, span: sp } as Box<MacResult+'static>
343 /// A plain dummy expression.
344 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
346 id: ast::DUMMY_NODE_ID,
347 node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
352 /// A plain dummy pattern.
353 pub fn raw_pat(sp: Span) -> ast::Pat {
355 id: ast::DUMMY_NODE_ID,
356 node: ast::PatWild(ast::PatWildSingle),
363 impl MacResult for DummyResult {
364 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
365 Some(DummyResult::raw_expr(self.span))
367 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
368 Some(P(DummyResult::raw_pat(self.span)))
370 fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
371 // this code needs a comment... why not always just return the Some() ?
375 Some(SmallVector::zero())
378 fn make_methods(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Method>>> {
382 Some(SmallVector::zero())
385 fn make_stmt(self: Box<DummyResult>) -> Option<P<ast::Stmt>> {
386 Some(P(codemap::respan(self.span,
387 ast::StmtExpr(DummyResult::raw_expr(self.span),
388 ast::DUMMY_NODE_ID))))
392 /// An enum representing the different kinds of syntax extensions.
393 pub enum SyntaxExtension {
394 /// A syntax extension that is attached to an item and creates new items
397 /// `#[derive(...)]` is an `ItemDecorator`.
398 Decorator(Box<ItemDecorator + 'static>),
400 /// A syntax extension that is attached to an item and modifies it
402 Modifier(Box<ItemModifier + 'static>),
404 /// A syntax extension that is attached to an item and modifies it
405 /// in-place. More flexible version than Modifier.
406 MultiModifier(Box<MultiItemModifier + 'static>),
408 /// A normal, function-like syntax extension.
410 /// `bytes!` is a `NormalTT`.
411 NormalTT(Box<TTMacroExpander + 'static>, Option<Span>),
413 /// A function-like syntax extension that has an extra ident before
416 IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>),
418 /// Represents `macro_rules!` itself.
422 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
424 pub struct BlockInfo {
425 /// Should macros escape from this scope?
426 pub macros_escape: bool,
427 /// What are the pending renames?
428 pub pending_renames: mtwt::RenameList,
432 pub fn new() -> BlockInfo {
434 macros_escape: false,
435 pending_renames: Vec::new(),
440 /// The base map of methods for expanding syntax extension
441 /// AST nodes into full ASTs
442 fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv {
443 // utility function to simplify creating NormalTT syntax extensions
444 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
445 NormalTT(box f, None)
448 let mut syntax_expanders = SyntaxEnv::new();
449 syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
450 syntax_expanders.insert(intern("format_args"),
451 builtin_normal_expander(
452 ext::format::expand_format_args));
453 syntax_expanders.insert(intern("env"),
454 builtin_normal_expander(
455 ext::env::expand_env));
456 syntax_expanders.insert(intern("option_env"),
457 builtin_normal_expander(
458 ext::env::expand_option_env));
459 syntax_expanders.insert(intern("concat_idents"),
460 builtin_normal_expander(
461 ext::concat_idents::expand_syntax_ext));
462 syntax_expanders.insert(intern("concat"),
463 builtin_normal_expander(
464 ext::concat::expand_syntax_ext));
465 syntax_expanders.insert(intern("log_syntax"),
466 builtin_normal_expander(
467 ext::log_syntax::expand_syntax_ext));
468 syntax_expanders.insert(intern("derive"),
469 Decorator(box ext::deriving::expand_meta_derive));
471 if ecfg.enable_quotes {
472 // Quasi-quoting expanders
473 syntax_expanders.insert(intern("quote_tokens"),
474 builtin_normal_expander(
475 ext::quote::expand_quote_tokens));
476 syntax_expanders.insert(intern("quote_expr"),
477 builtin_normal_expander(
478 ext::quote::expand_quote_expr));
479 syntax_expanders.insert(intern("quote_ty"),
480 builtin_normal_expander(
481 ext::quote::expand_quote_ty));
482 syntax_expanders.insert(intern("quote_method"),
483 builtin_normal_expander(
484 ext::quote::expand_quote_method));
485 syntax_expanders.insert(intern("quote_item"),
486 builtin_normal_expander(
487 ext::quote::expand_quote_item));
488 syntax_expanders.insert(intern("quote_pat"),
489 builtin_normal_expander(
490 ext::quote::expand_quote_pat));
491 syntax_expanders.insert(intern("quote_arm"),
492 builtin_normal_expander(
493 ext::quote::expand_quote_arm));
494 syntax_expanders.insert(intern("quote_stmt"),
495 builtin_normal_expander(
496 ext::quote::expand_quote_stmt));
499 syntax_expanders.insert(intern("line"),
500 builtin_normal_expander(
501 ext::source_util::expand_line));
502 syntax_expanders.insert(intern("column"),
503 builtin_normal_expander(
504 ext::source_util::expand_column));
505 syntax_expanders.insert(intern("file"),
506 builtin_normal_expander(
507 ext::source_util::expand_file));
508 syntax_expanders.insert(intern("stringify"),
509 builtin_normal_expander(
510 ext::source_util::expand_stringify));
511 syntax_expanders.insert(intern("include"),
512 builtin_normal_expander(
513 ext::source_util::expand_include));
514 syntax_expanders.insert(intern("include_str"),
515 builtin_normal_expander(
516 ext::source_util::expand_include_str));
517 syntax_expanders.insert(intern("include_bytes"),
518 builtin_normal_expander(
519 ext::source_util::expand_include_bytes));
520 syntax_expanders.insert(intern("module_path"),
521 builtin_normal_expander(
522 ext::source_util::expand_mod));
523 syntax_expanders.insert(intern("asm"),
524 builtin_normal_expander(
525 ext::asm::expand_asm));
526 syntax_expanders.insert(intern("cfg"),
527 builtin_normal_expander(
528 ext::cfg::expand_cfg));
529 syntax_expanders.insert(intern("cfg_attr"),
530 Modifier(box ext::cfg_attr::expand));
531 syntax_expanders.insert(intern("trace_macros"),
532 builtin_normal_expander(
533 ext::trace_macros::expand_trace_macros));
537 /// One of these is made during expansion and incrementally updated as we go;
538 /// when a macro expansion occurs, the resulting nodes have the backtrace()
539 /// -> expn_info of their expansion context stored into their span.
540 pub struct ExtCtxt<'a> {
541 pub parse_sess: &'a parse::ParseSess,
542 pub cfg: ast::CrateConfig,
543 pub backtrace: ExpnId,
544 pub ecfg: expand::ExpansionConfig,
546 pub mod_path: Vec<ast::Ident> ,
548 pub exported_macros: Vec<ast::MacroDef>,
550 pub syntax_env: SyntaxEnv,
551 pub recursion_count: usize,
554 impl<'a> ExtCtxt<'a> {
555 pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
556 ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
557 let env = initial_syntax_expander_table(&ecfg);
559 parse_sess: parse_sess,
561 backtrace: NO_EXPANSION,
562 mod_path: Vec::new(),
565 exported_macros: Vec::new(),
571 #[deprecated = "Replaced with `expander().fold_expr()`"]
572 pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
573 self.expander().fold_expr(e)
576 /// Returns a `Folder` for deeply expanding all macros in a AST node.
577 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
578 expand::MacroExpander::new(self)
581 pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
582 -> parser::Parser<'a> {
583 parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
586 pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
587 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
588 pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
589 pub fn call_site(&self) -> Span {
590 self.codemap().with_expn_info(self.backtrace, |ei| match ei {
591 Some(expn_info) => expn_info.call_site,
592 None => self.bug("missing top span")
595 pub fn print_backtrace(&self) { }
596 pub fn backtrace(&self) -> ExpnId { self.backtrace }
597 pub fn original_span(&self) -> Span {
598 let mut expn_id = self.backtrace;
599 let mut call_site = None;
601 match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
604 call_site = Some(cs);
605 expn_id = cs.expn_id;
609 call_site.expect("missing expansion backtrace")
611 pub fn original_span_in_file(&self) -> Span {
612 let mut expn_id = self.backtrace;
613 let mut call_site = None;
615 let expn_info = self.codemap().with_expn_info(expn_id, |ei| {
616 ei.map(|ei| (ei.call_site, ei.callee.name == "include"))
620 Some((cs, is_include)) => {
622 // Don't recurse into file using "include!".
625 call_site = Some(cs);
626 expn_id = cs.expn_id;
630 call_site.expect("missing expansion backtrace")
633 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
634 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
635 pub fn mod_path(&self) -> Vec<ast::Ident> {
636 let mut v = Vec::new();
637 v.push(token::str_to_ident(&self.ecfg.crate_name[]));
638 v.extend(self.mod_path.iter().map(|a| *a));
641 pub fn bt_push(&mut self, ei: ExpnInfo) {
642 self.recursion_count += 1;
643 if self.recursion_count > self.ecfg.recursion_limit {
644 self.span_fatal(ei.call_site,
645 &format!("recursion limit reached while expanding the macro `{}`",
649 let mut call_site = ei.call_site;
650 call_site.expn_id = self.backtrace;
651 self.backtrace = self.codemap().record_expansion(ExpnInfo {
652 call_site: call_site,
656 pub fn bt_pop(&mut self) {
657 match self.backtrace {
658 NO_EXPANSION => self.bug("tried to pop without a push"),
660 self.recursion_count -= 1;
661 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
662 expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
668 pub fn insert_macro(&mut self, def: ast::MacroDef) {
670 self.exported_macros.push(def.clone());
673 let ext = macro_rules::compile(self, &def);
674 self.syntax_env.insert(def.ident.name, ext);
678 /// Emit `msg` attached to `sp`, and stop compilation immediately.
680 /// `span_err` should be strongly preferred where-ever possible:
681 /// this should *only* be used when
682 /// - continuing has a high risk of flow-on errors (e.g. errors in
683 /// declaring a macro would cause all uses of that macro to
684 /// complain about "undefined macro"), or
685 /// - there is literally nothing else that can be done (however,
686 /// in most cases one can construct a dummy expression/item to
687 /// substitute; we never hit resolve/type-checking so the dummy
688 /// value doesn't have to match anything)
689 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
690 self.print_backtrace();
691 self.parse_sess.span_diagnostic.span_fatal(sp, msg);
694 /// Emit `msg` attached to `sp`, without immediately stopping
697 /// Compilation will be stopped in the near future (at the end of
698 /// the macro expansion phase).
699 pub fn span_err(&self, sp: Span, msg: &str) {
700 self.print_backtrace();
701 self.parse_sess.span_diagnostic.span_err(sp, msg);
703 pub fn span_warn(&self, sp: Span, msg: &str) {
704 self.print_backtrace();
705 self.parse_sess.span_diagnostic.span_warn(sp, msg);
707 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
708 self.print_backtrace();
709 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
711 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
712 self.print_backtrace();
713 self.parse_sess.span_diagnostic.span_bug(sp, msg);
715 pub fn span_note(&self, sp: Span, msg: &str) {
716 self.print_backtrace();
717 self.parse_sess.span_diagnostic.span_note(sp, msg);
719 pub fn span_help(&self, sp: Span, msg: &str) {
720 self.print_backtrace();
721 self.parse_sess.span_diagnostic.span_help(sp, msg);
723 pub fn bug(&self, msg: &str) -> ! {
724 self.print_backtrace();
725 self.parse_sess.span_diagnostic.handler().bug(msg);
727 pub fn trace_macros(&self) -> bool {
730 pub fn set_trace_macros(&mut self, x: bool) {
733 pub fn ident_of(&self, st: &str) -> ast::Ident {
736 pub fn name_of(&self, st: &str) -> ast::Name {
741 /// Extract a string literal from the macro expanded version of `expr`,
742 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
743 /// compilation on error, merely emits a non-fatal error and returns None.
744 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
745 -> Option<(InternedString, ast::StrStyle)> {
746 // we want to be able to handle e.g. concat("foo", "bar")
747 let expr = cx.expander().fold_expr(expr);
749 ast::ExprLit(ref l) => match l.node {
750 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
751 _ => cx.span_err(l.span, err_msg)
753 _ => cx.span_err(expr.span, err_msg)
758 /// Non-fatally assert that `tts` is empty. Note that this function
759 /// returns even when `tts` is non-empty, macros that *need* to stop
760 /// compilation should call
761 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
762 /// done as rarely as possible).
763 pub fn check_zero_tts(cx: &ExtCtxt,
765 tts: &[ast::TokenTree],
768 cx.span_err(sp, &format!("{} takes no arguments", name)[]);
772 /// Extract the string literal from the first token of `tts`. If this
773 /// is not a string literal, emit an error and return None.
774 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
776 tts: &[ast::TokenTree],
779 let mut p = cx.new_parser_from_tts(tts);
780 if p.token == token::Eof {
781 cx.span_err(sp, &format!("{} takes 1 argument", name)[]);
784 let ret = cx.expander().fold_expr(p.parse_expr());
785 if p.token != token::Eof {
786 cx.span_err(sp, &format!("{} takes 1 argument", name)[]);
788 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
793 /// Extract comma-separated expressions from `tts`. If there is a
794 /// parsing error, emit a non-fatal error and return None.
795 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
797 tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
798 let mut p = cx.new_parser_from_tts(tts);
799 let mut es = Vec::new();
800 while p.token != token::Eof {
801 es.push(cx.expander().fold_expr(p.parse_expr()));
802 if p.eat(&token::Comma) {
805 if p.token != token::Eof {
806 cx.span_err(sp, "expected token: `,`");
813 /// In order to have some notion of scoping for macros,
814 /// we want to implement the notion of a transformation
817 /// This environment maps Names to SyntaxExtensions.
818 pub struct SyntaxEnv {
819 chain: Vec<MapChainFrame> ,
822 // impl question: how to implement it? Initially, the
823 // env will contain only macros, so it might be painful
824 // to add an empty frame for every context. Let's just
825 // get it working, first....
827 // NB! the mutability of the underlying maps means that
828 // if expansion is out-of-order, a deeper scope may be
829 // able to refer to a macro that was added to an enclosing
830 // scope lexically later than the deeper scope.
832 struct MapChainFrame {
834 map: HashMap<Name, Rc<SyntaxExtension>>,
838 fn new() -> SyntaxEnv {
839 let mut map = SyntaxEnv { chain: Vec::new() };
844 pub fn push_frame(&mut self) {
845 self.chain.push(MapChainFrame {
846 info: BlockInfo::new(),
851 pub fn pop_frame(&mut self) {
852 assert!(self.chain.len() > 1, "too many pops on MapChain!");
856 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
857 for (i, frame) in self.chain.iter_mut().enumerate().rev() {
858 if !frame.info.macros_escape || i == 0 {
865 pub fn find(&self, k: &Name) -> Option<Rc<SyntaxExtension>> {
866 for frame in self.chain.iter().rev() {
867 match frame.map.get(k) {
868 Some(v) => return Some(v.clone()),
875 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
876 self.find_escape_frame().map.insert(k, Rc::new(v));
879 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
880 let last_chain_index = self.chain.len() - 1;
881 &mut self.chain[last_chain_index].info