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: &mut FnMut(P<ast::Item>));
41 impl<F> ItemDecorator for F
42 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &ast::Item, &mut FnMut(P<ast::Item>))
47 meta_item: &ast::MetaItem,
49 push: &mut 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)
76 #[derive(Debug,Clone)]
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<'feat>(ecfg: &expand::ExpansionConfig<'feat>)
444 // utility function to simplify creating NormalTT syntax extensions
445 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
446 NormalTT(box f, None)
449 let mut syntax_expanders = SyntaxEnv::new();
450 syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
451 syntax_expanders.insert(intern("format_args"),
452 builtin_normal_expander(
453 ext::format::expand_format_args));
454 syntax_expanders.insert(intern("env"),
455 builtin_normal_expander(
456 ext::env::expand_env));
457 syntax_expanders.insert(intern("option_env"),
458 builtin_normal_expander(
459 ext::env::expand_option_env));
460 syntax_expanders.insert(intern("concat_idents"),
461 builtin_normal_expander(
462 ext::concat_idents::expand_syntax_ext));
463 syntax_expanders.insert(intern("concat"),
464 builtin_normal_expander(
465 ext::concat::expand_syntax_ext));
466 syntax_expanders.insert(intern("log_syntax"),
467 builtin_normal_expander(
468 ext::log_syntax::expand_syntax_ext));
469 syntax_expanders.insert(intern("derive"),
470 Decorator(box ext::deriving::expand_meta_derive));
471 syntax_expanders.insert(intern("deriving"),
472 Decorator(box ext::deriving::expand_deprecated_deriving));
474 if ecfg.enable_quotes() {
475 // Quasi-quoting expanders
476 syntax_expanders.insert(intern("quote_tokens"),
477 builtin_normal_expander(
478 ext::quote::expand_quote_tokens));
479 syntax_expanders.insert(intern("quote_expr"),
480 builtin_normal_expander(
481 ext::quote::expand_quote_expr));
482 syntax_expanders.insert(intern("quote_ty"),
483 builtin_normal_expander(
484 ext::quote::expand_quote_ty));
485 syntax_expanders.insert(intern("quote_method"),
486 builtin_normal_expander(
487 ext::quote::expand_quote_method));
488 syntax_expanders.insert(intern("quote_item"),
489 builtin_normal_expander(
490 ext::quote::expand_quote_item));
491 syntax_expanders.insert(intern("quote_pat"),
492 builtin_normal_expander(
493 ext::quote::expand_quote_pat));
494 syntax_expanders.insert(intern("quote_arm"),
495 builtin_normal_expander(
496 ext::quote::expand_quote_arm));
497 syntax_expanders.insert(intern("quote_stmt"),
498 builtin_normal_expander(
499 ext::quote::expand_quote_stmt));
502 syntax_expanders.insert(intern("line"),
503 builtin_normal_expander(
504 ext::source_util::expand_line));
505 syntax_expanders.insert(intern("column"),
506 builtin_normal_expander(
507 ext::source_util::expand_column));
508 syntax_expanders.insert(intern("file"),
509 builtin_normal_expander(
510 ext::source_util::expand_file));
511 syntax_expanders.insert(intern("stringify"),
512 builtin_normal_expander(
513 ext::source_util::expand_stringify));
514 syntax_expanders.insert(intern("include"),
515 builtin_normal_expander(
516 ext::source_util::expand_include));
517 syntax_expanders.insert(intern("include_str"),
518 builtin_normal_expander(
519 ext::source_util::expand_include_str));
520 syntax_expanders.insert(intern("include_bytes"),
521 builtin_normal_expander(
522 ext::source_util::expand_include_bytes));
523 syntax_expanders.insert(intern("module_path"),
524 builtin_normal_expander(
525 ext::source_util::expand_mod));
526 syntax_expanders.insert(intern("asm"),
527 builtin_normal_expander(
528 ext::asm::expand_asm));
529 syntax_expanders.insert(intern("cfg"),
530 builtin_normal_expander(
531 ext::cfg::expand_cfg));
532 syntax_expanders.insert(intern("trace_macros"),
533 builtin_normal_expander(
534 ext::trace_macros::expand_trace_macros));
538 /// One of these is made during expansion and incrementally updated as we go;
539 /// when a macro expansion occurs, the resulting nodes have the backtrace()
540 /// -> expn_info of their expansion context stored into their span.
541 pub struct ExtCtxt<'a> {
542 pub parse_sess: &'a parse::ParseSess,
543 pub cfg: ast::CrateConfig,
544 pub backtrace: ExpnId,
545 pub ecfg: expand::ExpansionConfig<'a>,
548 pub mod_path: Vec<ast::Ident> ,
550 pub exported_macros: Vec<ast::MacroDef>,
552 pub syntax_env: SyntaxEnv,
553 pub recursion_count: usize,
556 impl<'a> ExtCtxt<'a> {
557 pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
558 ecfg: expand::ExpansionConfig<'a>) -> ExtCtxt<'a> {
559 let env = initial_syntax_expander_table(&ecfg);
561 parse_sess: parse_sess,
563 backtrace: NO_EXPANSION,
564 mod_path: Vec::new(),
568 exported_macros: Vec::new(),
574 #[unstable(feature = "rustc_private")]
575 #[deprecated(since = "1.0.0",
576 reason = "Replaced with `expander().fold_expr()`")]
577 pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
578 self.expander().fold_expr(e)
581 /// Returns a `Folder` for deeply expanding all macros in a AST node.
582 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
583 expand::MacroExpander::new(self)
586 pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
587 -> parser::Parser<'a> {
588 parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
591 pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
592 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
593 pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
594 pub fn call_site(&self) -> Span {
595 self.codemap().with_expn_info(self.backtrace, |ei| match ei {
596 Some(expn_info) => expn_info.call_site,
597 None => self.bug("missing top span")
600 pub fn print_backtrace(&self) { }
601 pub fn backtrace(&self) -> ExpnId { self.backtrace }
602 pub fn original_span(&self) -> Span {
603 let mut expn_id = self.backtrace;
604 let mut call_site = None;
606 match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
609 call_site = Some(cs);
610 expn_id = cs.expn_id;
614 call_site.expect("missing expansion backtrace")
616 pub fn original_span_in_file(&self) -> Span {
617 let mut expn_id = self.backtrace;
618 let mut call_site = None;
620 let expn_info = self.codemap().with_expn_info(expn_id, |ei| {
621 ei.map(|ei| (ei.call_site, ei.callee.name == "include"))
625 Some((cs, is_include)) => {
627 // Don't recurse into file using "include!".
630 call_site = Some(cs);
631 expn_id = cs.expn_id;
635 call_site.expect("missing expansion backtrace")
638 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
639 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
640 pub fn mod_path(&self) -> Vec<ast::Ident> {
641 let mut v = Vec::new();
642 v.push(token::str_to_ident(&self.ecfg.crate_name[]));
643 v.extend(self.mod_path.iter().cloned());
646 pub fn bt_push(&mut self, ei: ExpnInfo) {
647 self.recursion_count += 1;
648 if self.recursion_count > self.ecfg.recursion_limit {
649 self.span_fatal(ei.call_site,
650 &format!("recursion limit reached while expanding the macro `{}`",
654 let mut call_site = ei.call_site;
655 call_site.expn_id = self.backtrace;
656 self.backtrace = self.codemap().record_expansion(ExpnInfo {
657 call_site: call_site,
661 pub fn bt_pop(&mut self) {
662 match self.backtrace {
663 NO_EXPANSION => self.bug("tried to pop without a push"),
665 self.recursion_count -= 1;
666 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
667 expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
673 pub fn insert_macro(&mut self, def: ast::MacroDef) {
675 self.exported_macros.push(def.clone());
678 let ext = macro_rules::compile(self, &def);
679 self.syntax_env.insert(def.ident.name, ext);
683 /// Emit `msg` attached to `sp`, and stop compilation immediately.
685 /// `span_err` should be strongly preferred where-ever possible:
686 /// this should *only* be used when
687 /// - continuing has a high risk of flow-on errors (e.g. errors in
688 /// declaring a macro would cause all uses of that macro to
689 /// complain about "undefined macro"), or
690 /// - there is literally nothing else that can be done (however,
691 /// in most cases one can construct a dummy expression/item to
692 /// substitute; we never hit resolve/type-checking so the dummy
693 /// value doesn't have to match anything)
694 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
695 self.print_backtrace();
696 self.parse_sess.span_diagnostic.span_fatal(sp, msg);
699 /// Emit `msg` attached to `sp`, without immediately stopping
702 /// Compilation will be stopped in the near future (at the end of
703 /// the macro expansion phase).
704 pub fn span_err(&self, sp: Span, msg: &str) {
705 self.print_backtrace();
706 self.parse_sess.span_diagnostic.span_err(sp, msg);
708 pub fn span_warn(&self, sp: Span, msg: &str) {
709 self.print_backtrace();
710 self.parse_sess.span_diagnostic.span_warn(sp, msg);
712 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
713 self.print_backtrace();
714 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
716 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
717 self.print_backtrace();
718 self.parse_sess.span_diagnostic.span_bug(sp, msg);
720 pub fn span_note(&self, sp: Span, msg: &str) {
721 self.print_backtrace();
722 self.parse_sess.span_diagnostic.span_note(sp, msg);
724 pub fn span_help(&self, sp: Span, msg: &str) {
725 self.print_backtrace();
726 self.parse_sess.span_diagnostic.span_help(sp, msg);
728 pub fn bug(&self, msg: &str) -> ! {
729 self.print_backtrace();
730 self.parse_sess.span_diagnostic.handler().bug(msg);
732 pub fn trace_macros(&self) -> bool {
735 pub fn set_trace_macros(&mut self, x: bool) {
738 pub fn ident_of(&self, st: &str) -> ast::Ident {
741 pub fn ident_of_std(&self, st: &str) -> ast::Ident {
742 self.ident_of(if self.use_std { "std" } else { st })
744 pub fn name_of(&self, st: &str) -> ast::Name {
749 /// Extract a string literal from the macro expanded version of `expr`,
750 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
751 /// compilation on error, merely emits a non-fatal error and returns None.
752 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
753 -> Option<(InternedString, ast::StrStyle)> {
754 // we want to be able to handle e.g. concat("foo", "bar")
755 let expr = cx.expander().fold_expr(expr);
757 ast::ExprLit(ref l) => match l.node {
758 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
759 _ => cx.span_err(l.span, err_msg)
761 _ => cx.span_err(expr.span, err_msg)
766 /// Non-fatally assert that `tts` is empty. Note that this function
767 /// returns even when `tts` is non-empty, macros that *need* to stop
768 /// compilation should call
769 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
770 /// done as rarely as possible).
771 pub fn check_zero_tts(cx: &ExtCtxt,
773 tts: &[ast::TokenTree],
776 cx.span_err(sp, &format!("{} takes no arguments", name)[]);
780 /// Extract the string literal from the first token of `tts`. If this
781 /// is not a string literal, emit an error and return None.
782 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
784 tts: &[ast::TokenTree],
787 let mut p = cx.new_parser_from_tts(tts);
788 if p.token == token::Eof {
789 cx.span_err(sp, &format!("{} takes 1 argument", name)[]);
792 let ret = cx.expander().fold_expr(p.parse_expr());
793 if p.token != token::Eof {
794 cx.span_err(sp, &format!("{} takes 1 argument", name)[]);
796 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
801 /// Extract comma-separated expressions from `tts`. If there is a
802 /// parsing error, emit a non-fatal error and return None.
803 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
805 tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
806 let mut p = cx.new_parser_from_tts(tts);
807 let mut es = Vec::new();
808 while p.token != token::Eof {
809 es.push(cx.expander().fold_expr(p.parse_expr()));
810 if p.eat(&token::Comma) {
813 if p.token != token::Eof {
814 cx.span_err(sp, "expected token: `,`");
821 /// In order to have some notion of scoping for macros,
822 /// we want to implement the notion of a transformation
825 /// This environment maps Names to SyntaxExtensions.
826 pub struct SyntaxEnv {
827 chain: Vec<MapChainFrame> ,
830 // impl question: how to implement it? Initially, the
831 // env will contain only macros, so it might be painful
832 // to add an empty frame for every context. Let's just
833 // get it working, first....
835 // NB! the mutability of the underlying maps means that
836 // if expansion is out-of-order, a deeper scope may be
837 // able to refer to a macro that was added to an enclosing
838 // scope lexically later than the deeper scope.
840 struct MapChainFrame {
842 map: HashMap<Name, Rc<SyntaxExtension>>,
846 fn new() -> SyntaxEnv {
847 let mut map = SyntaxEnv { chain: Vec::new() };
852 pub fn push_frame(&mut self) {
853 self.chain.push(MapChainFrame {
854 info: BlockInfo::new(),
859 pub fn pop_frame(&mut self) {
860 assert!(self.chain.len() > 1, "too many pops on MapChain!");
864 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
865 for (i, frame) in self.chain.iter_mut().enumerate().rev() {
866 if !frame.info.macros_escape || i == 0 {
873 pub fn find(&self, k: &Name) -> Option<Rc<SyntaxExtension>> {
874 for frame in self.chain.iter().rev() {
875 match frame.map.get(k) {
876 Some(v) => return Some(v.clone()),
883 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
884 self.find_escape_frame().map.insert(k, Rc::new(v));
887 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
888 let last_chain_index = self.chain.len() - 1;
889 &mut self.chain[last_chain_index].info