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::*;
16 use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION};
19 use ext::tt::macro_rules;
20 use feature_gate::GatedCfg;
24 use parse::token::{InternedString, intern, str_to_ident};
26 use util::small_vector::SmallVector;
30 use std::collections::HashMap;
32 use std::default::Default;
35 #[derive(Debug,Clone)]
36 pub enum Annotatable {
38 TraitItem(P<ast::TraitItem>),
39 ImplItem(P<ast::ImplItem>),
43 pub fn attrs(&self) -> &[ast::Attribute] {
45 Annotatable::Item(ref i) => &i.attrs,
46 Annotatable::TraitItem(ref ti) => &ti.attrs,
47 Annotatable::ImplItem(ref ii) => &ii.attrs,
51 pub fn fold_attrs(self, attrs: Vec<ast::Attribute>) -> Annotatable {
53 Annotatable::Item(i) => Annotatable::Item(i.map(|i| ast::Item {
57 Annotatable::TraitItem(i) => Annotatable::TraitItem(i.map(|ti| {
58 ast::TraitItem { attrs: attrs, ..ti }
60 Annotatable::ImplItem(i) => Annotatable::ImplItem(i.map(|ii| {
61 ast::ImplItem { attrs: attrs, ..ii }
66 pub fn expect_item(self) -> P<ast::Item> {
68 Annotatable::Item(i) => i,
69 _ => panic!("expected Item")
73 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
74 where F: FnMut(P<ast::Item>) -> P<ast::Item>,
75 G: FnMut(Annotatable) -> Annotatable
78 Annotatable::Item(i) => Annotatable::Item(f(i)),
83 pub fn expect_trait_item(self) -> P<ast::TraitItem> {
85 Annotatable::TraitItem(i) => i,
86 _ => panic!("expected Item")
90 pub fn expect_impl_item(self) -> P<ast::ImplItem> {
92 Annotatable::ImplItem(i) => i,
93 _ => panic!("expected Item")
98 // A more flexible ItemDecorator.
99 pub trait MultiItemDecorator {
103 meta_item: &ast::MetaItem,
105 push: &mut FnMut(Annotatable));
108 impl<F> MultiItemDecorator for F
109 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
114 meta_item: &ast::MetaItem,
116 push: &mut FnMut(Annotatable)) {
117 (*self)(ecx, sp, meta_item, item, push)
121 // A more flexible ItemModifier (ItemModifier should go away, eventually, FIXME).
122 // meta_item is the annotation, item is the item being modified, parent_item
123 // is the impl or trait item is declared in if item is part of such a thing.
124 // FIXME Decorators should follow the same pattern too.
125 pub trait MultiItemModifier {
129 meta_item: &ast::MetaItem,
134 impl<F> MultiItemModifier for F
135 where F: Fn(&mut ExtCtxt,
138 Annotatable) -> Annotatable
143 meta_item: &ast::MetaItem,
146 (*self)(ecx, span, meta_item, item)
150 /// Represents a thing that maps token trees to Macro Results
151 pub trait TTMacroExpander {
152 fn expand<'cx>(&self,
153 ecx: &'cx mut ExtCtxt,
155 token_tree: &[ast::TokenTree])
156 -> Box<MacResult+'cx>;
159 pub type MacroExpanderFn =
160 for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
162 impl<F> TTMacroExpander for F
163 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>
165 fn expand<'cx>(&self,
166 ecx: &'cx mut ExtCtxt,
168 token_tree: &[ast::TokenTree])
169 -> Box<MacResult+'cx> {
170 (*self)(ecx, span, token_tree)
174 pub trait IdentMacroExpander {
175 fn expand<'cx>(&self,
176 cx: &'cx mut ExtCtxt,
179 token_tree: Vec<ast::TokenTree> )
180 -> Box<MacResult+'cx>;
183 pub type IdentMacroExpanderFn =
184 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
186 impl<F> IdentMacroExpander for F
187 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
188 Vec<ast::TokenTree>) -> Box<MacResult+'cx>
190 fn expand<'cx>(&self,
191 cx: &'cx mut ExtCtxt,
194 token_tree: Vec<ast::TokenTree> )
195 -> Box<MacResult+'cx>
197 (*self)(cx, sp, ident, token_tree)
201 // Use a macro because forwarding to a simple function has type system issues
202 macro_rules! make_stmts_default {
204 $me.make_expr().map(|e| {
205 SmallVector::one(P(codemap::respan(
206 e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
211 /// The result of a macro expansion. The return values of the various
212 /// methods are spliced into the AST at the callsite of the macro.
213 pub trait MacResult {
214 /// Create an expression.
215 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
218 /// Create zero or more items.
219 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
223 /// Create zero or more impl items.
224 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
228 /// Create a pattern.
229 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
233 /// Create zero or more statements.
235 /// By default this attempts to create an expression statement,
236 /// returning None if that fails.
237 fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> {
238 make_stmts_default!(self)
241 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
246 macro_rules! make_MacEager {
247 ( $( $fld:ident: $t:ty, )* ) => {
248 /// `MacResult` implementation for the common case where you've already
249 /// built each form of AST that you might return.
251 pub struct MacEager {
253 pub $fld: Option<$t>,
259 pub fn $fld(v: $t) -> Box<MacResult> {
273 items: SmallVector<P<ast::Item>>,
274 impl_items: SmallVector<P<ast::ImplItem>>,
275 stmts: SmallVector<P<ast::Stmt>>,
279 impl MacResult for MacEager {
280 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
284 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
288 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
292 fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> {
293 match self.stmts.as_ref().map_or(0, |s| s.len()) {
294 0 => make_stmts_default!(self),
299 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
300 if let Some(p) = self.pat {
303 if let Some(e) = self.expr {
304 if let ast::ExprLit(_) = e.node {
305 return Some(P(ast::Pat {
306 id: ast::DUMMY_NODE_ID,
308 node: ast::PatLit(e),
315 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
320 /// Fill-in macro expansion result, to allow compilation to continue
321 /// after hitting errors.
322 #[derive(Copy, Clone)]
323 pub struct DummyResult {
329 /// Create a default MacResult that can be anything.
331 /// Use this as a return value after hitting any errors and
332 /// calling `span_err`.
333 pub fn any(sp: Span) -> Box<MacResult+'static> {
334 Box::new(DummyResult { expr_only: false, span: sp })
337 /// Create a default MacResult that can only be an expression.
339 /// Use this for macros that must expand to an expression, so even
340 /// if an error is encountered internally, the user will receive
341 /// an error that they also used it in the wrong place.
342 pub fn expr(sp: Span) -> Box<MacResult+'static> {
343 Box::new(DummyResult { expr_only: true, span: sp })
346 /// A plain dummy expression.
347 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
349 id: ast::DUMMY_NODE_ID,
350 node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
355 /// A plain dummy pattern.
356 pub fn raw_pat(sp: Span) -> ast::Pat {
358 id: ast::DUMMY_NODE_ID,
359 node: ast::PatWild(ast::PatWildSingle),
364 pub fn raw_ty(sp: Span) -> P<ast::Ty> {
366 id: ast::DUMMY_NODE_ID,
373 impl MacResult for DummyResult {
374 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
375 Some(DummyResult::raw_expr(self.span))
378 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
379 Some(P(DummyResult::raw_pat(self.span)))
382 fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
383 // this code needs a comment... why not always just return the Some() ?
387 Some(SmallVector::zero())
391 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::ImplItem>>> {
395 Some(SmallVector::zero())
399 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Stmt>>> {
400 Some(SmallVector::one(P(
401 codemap::respan(self.span,
402 ast::StmtExpr(DummyResult::raw_expr(self.span),
403 ast::DUMMY_NODE_ID)))))
407 /// An enum representing the different kinds of syntax extensions.
408 pub enum SyntaxExtension {
409 /// A syntax extension that is attached to an item and creates new items
412 /// `#[derive(...)]` is a `MultiItemDecorator`.
413 MultiDecorator(Box<MultiItemDecorator + 'static>),
415 /// A syntax extension that is attached to an item and modifies it
416 /// in-place. More flexible version than Modifier.
417 MultiModifier(Box<MultiItemModifier + 'static>),
419 /// A normal, function-like syntax extension.
421 /// `bytes!` is a `NormalTT`.
423 /// The `bool` dictates whether the contents of the macro can
424 /// directly use `#[unstable]` things (true == yes).
425 NormalTT(Box<TTMacroExpander + 'static>, Option<Span>, bool),
427 /// A function-like syntax extension that has an extra ident before
430 IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>, bool),
432 /// Represents `macro_rules!` itself.
436 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
438 pub struct BlockInfo {
439 /// Should macros escape from this scope?
440 pub macros_escape: bool,
441 /// What are the pending renames?
442 pub pending_renames: mtwt::RenameList,
446 pub fn new() -> BlockInfo {
448 macros_escape: false,
449 pending_renames: Vec::new(),
454 /// The base map of methods for expanding syntax extension
455 /// AST nodes into full ASTs
456 fn initial_syntax_expander_table<'feat>(ecfg: &expand::ExpansionConfig<'feat>)
458 // utility function to simplify creating NormalTT syntax extensions
459 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
460 NormalTT(Box::new(f), None, false)
463 let mut syntax_expanders = SyntaxEnv::new();
464 syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
465 syntax_expanders.insert(intern("format_args"),
466 // format_args uses `unstable` things internally.
467 NormalTT(Box::new(ext::format::expand_format_args), None, true));
468 syntax_expanders.insert(intern("env"),
469 builtin_normal_expander(
470 ext::env::expand_env));
471 syntax_expanders.insert(intern("option_env"),
472 builtin_normal_expander(
473 ext::env::expand_option_env));
474 syntax_expanders.insert(intern("concat_idents"),
475 builtin_normal_expander(
476 ext::concat_idents::expand_syntax_ext));
477 syntax_expanders.insert(intern("concat"),
478 builtin_normal_expander(
479 ext::concat::expand_syntax_ext));
480 syntax_expanders.insert(intern("log_syntax"),
481 builtin_normal_expander(
482 ext::log_syntax::expand_syntax_ext));
484 ext::deriving::register_all(&mut syntax_expanders);
486 if ecfg.enable_quotes() {
487 // Quasi-quoting expanders
488 syntax_expanders.insert(intern("quote_tokens"),
489 builtin_normal_expander(
490 ext::quote::expand_quote_tokens));
491 syntax_expanders.insert(intern("quote_expr"),
492 builtin_normal_expander(
493 ext::quote::expand_quote_expr));
494 syntax_expanders.insert(intern("quote_ty"),
495 builtin_normal_expander(
496 ext::quote::expand_quote_ty));
497 syntax_expanders.insert(intern("quote_item"),
498 builtin_normal_expander(
499 ext::quote::expand_quote_item));
500 syntax_expanders.insert(intern("quote_pat"),
501 builtin_normal_expander(
502 ext::quote::expand_quote_pat));
503 syntax_expanders.insert(intern("quote_arm"),
504 builtin_normal_expander(
505 ext::quote::expand_quote_arm));
506 syntax_expanders.insert(intern("quote_stmt"),
507 builtin_normal_expander(
508 ext::quote::expand_quote_stmt));
509 syntax_expanders.insert(intern("quote_matcher"),
510 builtin_normal_expander(
511 ext::quote::expand_quote_matcher));
512 syntax_expanders.insert(intern("quote_attr"),
513 builtin_normal_expander(
514 ext::quote::expand_quote_attr));
517 syntax_expanders.insert(intern("line"),
518 builtin_normal_expander(
519 ext::source_util::expand_line));
520 syntax_expanders.insert(intern("column"),
521 builtin_normal_expander(
522 ext::source_util::expand_column));
523 syntax_expanders.insert(intern("file"),
524 builtin_normal_expander(
525 ext::source_util::expand_file));
526 syntax_expanders.insert(intern("stringify"),
527 builtin_normal_expander(
528 ext::source_util::expand_stringify));
529 syntax_expanders.insert(intern("include"),
530 builtin_normal_expander(
531 ext::source_util::expand_include));
532 syntax_expanders.insert(intern("include_str"),
533 builtin_normal_expander(
534 ext::source_util::expand_include_str));
535 syntax_expanders.insert(intern("include_bytes"),
536 builtin_normal_expander(
537 ext::source_util::expand_include_bytes));
538 syntax_expanders.insert(intern("module_path"),
539 builtin_normal_expander(
540 ext::source_util::expand_mod));
541 syntax_expanders.insert(intern("asm"),
542 builtin_normal_expander(
543 ext::asm::expand_asm));
544 syntax_expanders.insert(intern("cfg"),
545 builtin_normal_expander(
546 ext::cfg::expand_cfg));
547 syntax_expanders.insert(intern("trace_macros"),
548 builtin_normal_expander(
549 ext::trace_macros::expand_trace_macros));
553 /// One of these is made during expansion and incrementally updated as we go;
554 /// when a macro expansion occurs, the resulting nodes have the backtrace()
555 /// -> expn_info of their expansion context stored into their span.
556 pub struct ExtCtxt<'a> {
557 pub parse_sess: &'a parse::ParseSess,
558 pub cfg: ast::CrateConfig,
559 pub backtrace: ExpnId,
560 pub ecfg: expand::ExpansionConfig<'a>,
561 pub crate_root: Option<&'static str>,
562 pub feature_gated_cfgs: &'a mut Vec<GatedCfg>,
564 pub mod_path: Vec<ast::Ident> ,
565 pub exported_macros: Vec<ast::MacroDef>,
567 pub syntax_env: SyntaxEnv,
568 pub recursion_count: usize,
571 impl<'a> ExtCtxt<'a> {
572 pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
573 ecfg: expand::ExpansionConfig<'a>,
574 feature_gated_cfgs: &'a mut Vec<GatedCfg>) -> ExtCtxt<'a> {
575 let env = initial_syntax_expander_table(&ecfg);
577 parse_sess: parse_sess,
579 backtrace: NO_EXPANSION,
580 mod_path: Vec::new(),
583 feature_gated_cfgs: feature_gated_cfgs,
584 exported_macros: Vec::new(),
590 #[unstable(feature = "rustc_private")]
591 #[deprecated(since = "1.0.0",
592 reason = "Replaced with `expander().fold_expr()`")]
593 pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
594 self.expander().fold_expr(e)
597 /// Returns a `Folder` for deeply expanding all macros in an AST node.
598 pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
599 expand::MacroExpander::new(self)
602 pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
603 -> parser::Parser<'a> {
604 parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
607 pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() }
608 pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
609 pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
610 pub fn call_site(&self) -> Span {
611 self.codemap().with_expn_info(self.backtrace, |ei| match ei {
612 Some(expn_info) => expn_info.call_site,
613 None => self.bug("missing top span")
616 pub fn backtrace(&self) -> ExpnId { self.backtrace }
618 /// Original span that caused the current exapnsion to happen.
619 pub fn original_span(&self) -> Span {
620 let mut expn_id = self.backtrace;
621 let mut call_site = None;
623 match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
626 call_site = Some(cs);
627 expn_id = cs.expn_id;
631 call_site.expect("missing expansion backtrace")
634 /// Returns span for the macro which originally caused the current expansion to happen.
636 /// Stops backtracing at include! boundary.
637 pub fn expansion_cause(&self) -> Span {
638 let mut expn_id = self.backtrace;
639 let mut last_macro = None;
641 if self.codemap().with_expn_info(expn_id, |info| {
642 info.map_or(None, |i| {
643 if i.callee.name().as_str() == "include" {
644 // Stop going up the backtrace once include! is encountered
647 expn_id = i.call_site.expn_id;
648 last_macro = Some(i.call_site);
655 last_macro.expect("missing expansion backtrace")
658 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
659 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
660 pub fn mod_path(&self) -> Vec<ast::Ident> {
661 let mut v = Vec::new();
662 v.push(token::str_to_ident(&self.ecfg.crate_name));
663 v.extend(self.mod_path.iter().cloned());
666 pub fn bt_push(&mut self, ei: ExpnInfo) {
667 self.recursion_count += 1;
668 if self.recursion_count > self.ecfg.recursion_limit {
669 panic!(self.span_fatal(ei.call_site,
670 &format!("recursion limit reached while expanding the macro `{}`",
674 let mut call_site = ei.call_site;
675 call_site.expn_id = self.backtrace;
676 self.backtrace = self.codemap().record_expansion(ExpnInfo {
677 call_site: call_site,
681 pub fn bt_pop(&mut self) {
682 match self.backtrace {
683 NO_EXPANSION => self.bug("tried to pop without a push"),
685 self.recursion_count -= 1;
686 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
687 expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
693 pub fn insert_macro(&mut self, def: ast::MacroDef) {
695 self.exported_macros.push(def.clone());
698 let ext = macro_rules::compile(self, &def);
699 self.syntax_env.insert(def.ident.name, ext);
703 /// Emit `msg` attached to `sp`, and stop compilation immediately.
705 /// `span_err` should be strongly preferred where-ever possible:
706 /// this should *only* be used when
707 /// - continuing has a high risk of flow-on errors (e.g. errors in
708 /// declaring a macro would cause all uses of that macro to
709 /// complain about "undefined macro"), or
710 /// - there is literally nothing else that can be done (however,
711 /// in most cases one can construct a dummy expression/item to
712 /// substitute; we never hit resolve/type-checking so the dummy
713 /// value doesn't have to match anything)
714 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
715 panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
718 /// Emit `msg` attached to `sp`, without immediately stopping
721 /// Compilation will be stopped in the near future (at the end of
722 /// the macro expansion phase).
723 pub fn span_err(&self, sp: Span, msg: &str) {
724 self.parse_sess.span_diagnostic.span_err(sp, msg);
726 pub fn span_warn(&self, sp: Span, msg: &str) {
727 self.parse_sess.span_diagnostic.span_warn(sp, msg);
729 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
730 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
732 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
733 self.parse_sess.span_diagnostic.span_bug(sp, msg);
735 pub fn span_note(&self, sp: Span, msg: &str) {
736 self.parse_sess.span_diagnostic.span_note(sp, msg);
738 pub fn span_help(&self, sp: Span, msg: &str) {
739 self.parse_sess.span_diagnostic.span_help(sp, msg);
741 pub fn fileline_help(&self, sp: Span, msg: &str) {
742 self.parse_sess.span_diagnostic.fileline_help(sp, msg);
744 pub fn bug(&self, msg: &str) -> ! {
745 self.parse_sess.span_diagnostic.handler().bug(msg);
747 pub fn trace_macros(&self) -> bool {
750 pub fn set_trace_macros(&mut self, x: bool) {
751 self.ecfg.trace_mac = x
753 pub fn ident_of(&self, st: &str) -> ast::Ident {
756 pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
757 let mut v = Vec::new();
758 if let Some(s) = self.crate_root {
759 v.push(self.ident_of(s));
761 v.extend(components.iter().map(|s| self.ident_of(s)));
764 pub fn name_of(&self, st: &str) -> ast::Name {
769 /// Extract a string literal from the macro expanded version of `expr`,
770 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
771 /// compilation on error, merely emits a non-fatal error and returns None.
772 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
773 -> Option<(InternedString, ast::StrStyle)> {
774 // we want to be able to handle e.g. concat("foo", "bar")
775 let expr = cx.expander().fold_expr(expr);
777 ast::ExprLit(ref l) => match l.node {
778 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
779 _ => cx.span_err(l.span, err_msg)
781 _ => cx.span_err(expr.span, err_msg)
786 /// Non-fatally assert that `tts` is empty. Note that this function
787 /// returns even when `tts` is non-empty, macros that *need* to stop
788 /// compilation should call
789 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
790 /// done as rarely as possible).
791 pub fn check_zero_tts(cx: &ExtCtxt,
793 tts: &[ast::TokenTree],
796 cx.span_err(sp, &format!("{} takes no arguments", name));
800 /// Extract the string literal from the first token of `tts`. If this
801 /// is not a string literal, emit an error and return None.
802 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
804 tts: &[ast::TokenTree],
807 let mut p = cx.new_parser_from_tts(tts);
808 if p.token == token::Eof {
809 cx.span_err(sp, &format!("{} takes 1 argument", name));
812 let ret = cx.expander().fold_expr(p.parse_expr());
813 if p.token != token::Eof {
814 cx.span_err(sp, &format!("{} takes 1 argument", name));
816 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
821 /// Extract comma-separated expressions from `tts`. If there is a
822 /// parsing error, emit a non-fatal error and return None.
823 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
825 tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
826 let mut p = cx.new_parser_from_tts(tts);
827 let mut es = Vec::new();
828 while p.token != token::Eof {
829 es.push(cx.expander().fold_expr(p.parse_expr()));
830 if panictry!(p.eat(&token::Comma)){
833 if p.token != token::Eof {
834 cx.span_err(sp, "expected token: `,`");
841 /// In order to have some notion of scoping for macros,
842 /// we want to implement the notion of a transformation
845 /// This environment maps Names to SyntaxExtensions.
846 pub struct SyntaxEnv {
847 chain: Vec<MapChainFrame> ,
850 // impl question: how to implement it? Initially, the
851 // env will contain only macros, so it might be painful
852 // to add an empty frame for every context. Let's just
853 // get it working, first....
855 // NB! the mutability of the underlying maps means that
856 // if expansion is out-of-order, a deeper scope may be
857 // able to refer to a macro that was added to an enclosing
858 // scope lexically later than the deeper scope.
860 struct MapChainFrame {
862 map: HashMap<Name, Rc<SyntaxExtension>>,
866 fn new() -> SyntaxEnv {
867 let mut map = SyntaxEnv { chain: Vec::new() };
872 pub fn push_frame(&mut self) {
873 self.chain.push(MapChainFrame {
874 info: BlockInfo::new(),
879 pub fn pop_frame(&mut self) {
880 assert!(self.chain.len() > 1, "too many pops on MapChain!");
884 fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
885 for (i, frame) in self.chain.iter_mut().enumerate().rev() {
886 if !frame.info.macros_escape || i == 0 {
893 pub fn find(&self, k: Name) -> Option<Rc<SyntaxExtension>> {
894 for frame in self.chain.iter().rev() {
895 match frame.map.get(&k) {
896 Some(v) => return Some(v.clone()),
903 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
904 self.find_escape_frame().map.insert(k, Rc::new(v));
907 pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
908 let last_chain_index = self.chain.len() - 1;
909 &mut self.chain[last_chain_index].info