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};
17 use errors::DiagnosticBuilder;
20 use ext::tt::macro_rules;
21 use feature_gate::GatedCfgAttr;
25 use parse::token::{InternedString, intern, str_to_ident};
27 use util::small_vector::SmallVector;
28 use util::lev_distance::find_best_match_for_name;
32 use std::collections::{HashMap, HashSet};
34 use std::default::Default;
37 #[derive(Debug,Clone)]
38 pub enum Annotatable {
40 TraitItem(P<ast::TraitItem>),
41 ImplItem(P<ast::ImplItem>),
45 pub fn attrs(&self) -> &[ast::Attribute] {
47 Annotatable::Item(ref i) => &i.attrs,
48 Annotatable::TraitItem(ref ti) => &ti.attrs,
49 Annotatable::ImplItem(ref ii) => &ii.attrs,
53 pub fn fold_attrs(self, attrs: Vec<ast::Attribute>) -> Annotatable {
55 Annotatable::Item(i) => Annotatable::Item(i.map(|i| ast::Item {
59 Annotatable::TraitItem(i) => Annotatable::TraitItem(i.map(|ti| {
60 ast::TraitItem { attrs: attrs, ..ti }
62 Annotatable::ImplItem(i) => Annotatable::ImplItem(i.map(|ii| {
63 ast::ImplItem { attrs: attrs, ..ii }
68 pub fn expect_item(self) -> P<ast::Item> {
70 Annotatable::Item(i) => i,
71 _ => panic!("expected Item")
75 pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
76 where F: FnMut(P<ast::Item>) -> P<ast::Item>,
77 G: FnMut(Annotatable) -> Annotatable
80 Annotatable::Item(i) => Annotatable::Item(f(i)),
85 pub fn expect_trait_item(self) -> P<ast::TraitItem> {
87 Annotatable::TraitItem(i) => i,
88 _ => panic!("expected Item")
92 pub fn expect_impl_item(self) -> P<ast::ImplItem> {
94 Annotatable::ImplItem(i) => i,
95 _ => panic!("expected Item")
100 // A more flexible ItemDecorator.
101 pub trait MultiItemDecorator {
105 meta_item: &ast::MetaItem,
107 push: &mut FnMut(Annotatable));
110 impl<F> MultiItemDecorator for F
111 where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
116 meta_item: &ast::MetaItem,
118 push: &mut FnMut(Annotatable)) {
119 (*self)(ecx, sp, meta_item, item, push)
123 // A more flexible ItemModifier (ItemModifier should go away, eventually, FIXME).
124 // meta_item is the annotation, item is the item being modified, parent_item
125 // is the impl or trait item is declared in if item is part of such a thing.
126 // FIXME Decorators should follow the same pattern too.
127 pub trait MultiItemModifier {
131 meta_item: &ast::MetaItem,
136 impl<F> MultiItemModifier for F
137 where F: Fn(&mut ExtCtxt,
140 Annotatable) -> Annotatable
145 meta_item: &ast::MetaItem,
148 (*self)(ecx, span, meta_item, item)
152 /// Represents a thing that maps token trees to Macro Results
153 pub trait TTMacroExpander {
154 fn expand<'cx>(&self,
155 ecx: &'cx mut ExtCtxt,
157 token_tree: &[ast::TokenTree])
158 -> Box<MacResult+'cx>;
161 pub type MacroExpanderFn =
162 for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
164 impl<F> TTMacroExpander for F
165 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>
167 fn expand<'cx>(&self,
168 ecx: &'cx mut ExtCtxt,
170 token_tree: &[ast::TokenTree])
171 -> Box<MacResult+'cx> {
172 (*self)(ecx, span, token_tree)
176 pub trait IdentMacroExpander {
177 fn expand<'cx>(&self,
178 cx: &'cx mut ExtCtxt,
181 token_tree: Vec<ast::TokenTree> )
182 -> Box<MacResult+'cx>;
185 pub type IdentMacroExpanderFn =
186 for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
188 impl<F> IdentMacroExpander for F
189 where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, ast::Ident,
190 Vec<ast::TokenTree>) -> Box<MacResult+'cx>
192 fn expand<'cx>(&self,
193 cx: &'cx mut ExtCtxt,
196 token_tree: Vec<ast::TokenTree> )
197 -> Box<MacResult+'cx>
199 (*self)(cx, sp, ident, token_tree)
203 // Use a macro because forwarding to a simple function has type system issues
204 macro_rules! make_stmts_default {
206 $me.make_expr().map(|e| {
207 SmallVector::one(P(codemap::respan(
208 e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
213 /// The result of a macro expansion. The return values of the various
214 /// methods are spliced into the AST at the callsite of the macro.
215 pub trait MacResult {
216 /// Create an expression.
217 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
220 /// Create zero or more items.
221 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
225 /// Create zero or more impl items.
226 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
230 /// Create a pattern.
231 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
235 /// Create zero or more statements.
237 /// By default this attempts to create an expression statement,
238 /// returning None if that fails.
239 fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> {
240 make_stmts_default!(self)
243 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
248 macro_rules! make_MacEager {
249 ( $( $fld:ident: $t:ty, )* ) => {
250 /// `MacResult` implementation for the common case where you've already
251 /// built each form of AST that you might return.
253 pub struct MacEager {
255 pub $fld: Option<$t>,
261 pub fn $fld(v: $t) -> Box<MacResult> {
275 items: SmallVector<P<ast::Item>>,
276 impl_items: SmallVector<P<ast::ImplItem>>,
277 stmts: SmallVector<P<ast::Stmt>>,
281 impl MacResult for MacEager {
282 fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
286 fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
290 fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
294 fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> {
295 match self.stmts.as_ref().map_or(0, |s| s.len()) {
296 0 => make_stmts_default!(self),
301 fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
302 if let Some(p) = self.pat {
305 if let Some(e) = self.expr {
306 if let ast::ExprLit(_) = e.node {
307 return Some(P(ast::Pat {
308 id: ast::DUMMY_NODE_ID,
310 node: ast::PatLit(e),
317 fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
322 /// Fill-in macro expansion result, to allow compilation to continue
323 /// after hitting errors.
324 #[derive(Copy, Clone)]
325 pub struct DummyResult {
331 /// Create a default MacResult that can be anything.
333 /// Use this as a return value after hitting any errors and
334 /// calling `span_err`.
335 pub fn any(sp: Span) -> Box<MacResult+'static> {
336 Box::new(DummyResult { expr_only: false, span: sp })
339 /// Create a default MacResult that can only be an expression.
341 /// Use this for macros that must expand to an expression, so even
342 /// if an error is encountered internally, the user will receive
343 /// an error that they also used it in the wrong place.
344 pub fn expr(sp: Span) -> Box<MacResult+'static> {
345 Box::new(DummyResult { expr_only: true, span: sp })
348 /// A plain dummy expression.
349 pub fn raw_expr(sp: Span) -> P<ast::Expr> {
351 id: ast::DUMMY_NODE_ID,
352 node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
358 /// A plain dummy pattern.
359 pub fn raw_pat(sp: Span) -> ast::Pat {
361 id: ast::DUMMY_NODE_ID,
367 pub fn raw_ty(sp: Span) -> P<ast::Ty> {
369 id: ast::DUMMY_NODE_ID,
376 impl MacResult for DummyResult {
377 fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
378 Some(DummyResult::raw_expr(self.span))
381 fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
382 Some(P(DummyResult::raw_pat(self.span)))
385 fn make_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Item>>> {
386 // this code needs a comment... why not always just return the Some() ?
390 Some(SmallVector::zero())
394 fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::ImplItem>>> {
398 Some(SmallVector::zero())
402 fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Stmt>>> {
403 Some(SmallVector::one(P(
404 codemap::respan(self.span,
405 ast::StmtExpr(DummyResult::raw_expr(self.span),
406 ast::DUMMY_NODE_ID)))))
410 /// An enum representing the different kinds of syntax extensions.
411 pub enum SyntaxExtension {
412 /// A syntax extension that is attached to an item and creates new items
415 /// `#[derive(...)]` is a `MultiItemDecorator`.
416 MultiDecorator(Box<MultiItemDecorator + 'static>),
418 /// A syntax extension that is attached to an item and modifies it
419 /// in-place. More flexible version than Modifier.
420 MultiModifier(Box<MultiItemModifier + 'static>),
422 /// A normal, function-like syntax extension.
424 /// `bytes!` is a `NormalTT`.
426 /// The `bool` dictates whether the contents of the macro can
427 /// directly use `#[unstable]` things (true == yes).
428 NormalTT(Box<TTMacroExpander + 'static>, Option<Span>, bool),
430 /// A function-like syntax extension that has an extra ident before
433 IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>, bool),
435 /// Represents `macro_rules!` itself.
439 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
441 pub struct BlockInfo {
442 /// Should macros escape from this scope?
443 pub macros_escape: bool,
444 /// What are the pending renames?
445 pub pending_renames: mtwt::RenameList,
449 pub fn new() -> BlockInfo {
451 macros_escape: false,
452 pending_renames: Vec::new(),
457 /// The base map of methods for expanding syntax extension
458 /// AST nodes into full ASTs
459 fn initial_syntax_expander_table<'feat>(ecfg: &expand::ExpansionConfig<'feat>)
461 // utility function to simplify creating NormalTT syntax extensions
462 fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
463 NormalTT(Box::new(f), None, false)
466 let mut syntax_expanders = SyntaxEnv::new();
467 syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
469 if ecfg.enable_quotes() {
470 // Quasi-quoting expanders
471 syntax_expanders.insert(intern("quote_tokens"),
472 builtin_normal_expander(
473 ext::quote::expand_quote_tokens));
474 syntax_expanders.insert(intern("quote_expr"),
475 builtin_normal_expander(
476 ext::quote::expand_quote_expr));
477 syntax_expanders.insert(intern("quote_ty"),
478 builtin_normal_expander(
479 ext::quote::expand_quote_ty));
480 syntax_expanders.insert(intern("quote_item"),
481 builtin_normal_expander(
482 ext::quote::expand_quote_item));
483 syntax_expanders.insert(intern("quote_pat"),
484 builtin_normal_expander(
485 ext::quote::expand_quote_pat));
486 syntax_expanders.insert(intern("quote_arm"),
487 builtin_normal_expander(
488 ext::quote::expand_quote_arm));
489 syntax_expanders.insert(intern("quote_stmt"),
490 builtin_normal_expander(
491 ext::quote::expand_quote_stmt));
492 syntax_expanders.insert(intern("quote_matcher"),
493 builtin_normal_expander(
494 ext::quote::expand_quote_matcher));
495 syntax_expanders.insert(intern("quote_attr"),
496 builtin_normal_expander(
497 ext::quote::expand_quote_attr));
498 syntax_expanders.insert(intern("quote_arg"),
499 builtin_normal_expander(
500 ext::quote::expand_quote_arg));
501 syntax_expanders.insert(intern("quote_block"),
502 builtin_normal_expander(
503 ext::quote::expand_quote_block));
504 syntax_expanders.insert(intern("quote_meta_item"),
505 builtin_normal_expander(
506 ext::quote::expand_quote_meta_item));
507 syntax_expanders.insert(intern("quote_path"),
508 builtin_normal_expander(
509 ext::quote::expand_quote_path));
512 syntax_expanders.insert(intern("line"),
513 builtin_normal_expander(
514 ext::source_util::expand_line));
515 syntax_expanders.insert(intern("column"),
516 builtin_normal_expander(
517 ext::source_util::expand_column));
518 syntax_expanders.insert(intern("file"),
519 builtin_normal_expander(
520 ext::source_util::expand_file));
521 syntax_expanders.insert(intern("stringify"),
522 builtin_normal_expander(
523 ext::source_util::expand_stringify));
524 syntax_expanders.insert(intern("include"),
525 builtin_normal_expander(
526 ext::source_util::expand_include));
527 syntax_expanders.insert(intern("include_str"),
528 builtin_normal_expander(
529 ext::source_util::expand_include_str));
530 syntax_expanders.insert(intern("include_bytes"),
531 builtin_normal_expander(
532 ext::source_util::expand_include_bytes));
533 syntax_expanders.insert(intern("module_path"),
534 builtin_normal_expander(
535 ext::source_util::expand_mod));
539 /// One of these is made during expansion and incrementally updated as we go;
540 /// when a macro expansion occurs, the resulting nodes have the backtrace()
541 /// -> expn_info of their expansion context stored into their span.
542 pub struct ExtCtxt<'a> {
543 pub parse_sess: &'a parse::ParseSess,
544 pub cfg: ast::CrateConfig,
545 pub backtrace: ExpnId,
546 pub ecfg: expand::ExpansionConfig<'a>,
547 pub crate_root: Option<&'static str>,
548 pub feature_gated_cfgs: &'a mut Vec<GatedCfgAttr>,
550 pub mod_path: Vec<ast::Ident> ,
551 pub exported_macros: Vec<ast::MacroDef>,
553 pub syntax_env: SyntaxEnv,
554 pub recursion_count: usize,
557 impl<'a> ExtCtxt<'a> {
558 pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
559 ecfg: expand::ExpansionConfig<'a>,
560 feature_gated_cfgs: &'a mut Vec<GatedCfgAttr>) -> ExtCtxt<'a> {
561 let env = initial_syntax_expander_table(&ecfg);
563 parse_sess: parse_sess,
565 backtrace: NO_EXPANSION,
566 mod_path: Vec::new(),
569 feature_gated_cfgs: feature_gated_cfgs,
570 exported_macros: Vec::new(),
576 /// Returns a `Folder` for deeply expanding all macros in an 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.codemap() }
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 backtrace(&self) -> ExpnId { self.backtrace }
597 /// Original span that caused the current exapnsion to happen.
598 pub fn original_span(&self) -> Span {
599 let mut expn_id = self.backtrace;
600 let mut call_site = None;
602 match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
605 call_site = Some(cs);
606 expn_id = cs.expn_id;
610 call_site.expect("missing expansion backtrace")
613 /// Returns span for the macro which originally caused the current expansion to happen.
615 /// Stops backtracing at include! boundary.
616 pub fn expansion_cause(&self) -> Span {
617 let mut expn_id = self.backtrace;
618 let mut last_macro = None;
620 if self.codemap().with_expn_info(expn_id, |info| {
621 info.map_or(None, |i| {
622 if i.callee.name().as_str() == "include" {
623 // Stop going up the backtrace once include! is encountered
626 expn_id = i.call_site.expn_id;
627 last_macro = Some(i.call_site);
634 last_macro.expect("missing expansion backtrace")
637 pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
638 pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
639 pub fn mod_path(&self) -> Vec<ast::Ident> {
640 let mut v = Vec::new();
641 v.push(token::str_to_ident(&self.ecfg.crate_name));
642 v.extend(self.mod_path.iter().cloned());
645 pub fn bt_push(&mut self, ei: ExpnInfo) {
646 self.recursion_count += 1;
647 if self.recursion_count > self.ecfg.recursion_limit {
648 self.span_fatal(ei.call_site,
649 &format!("recursion limit reached while expanding the macro `{}`",
653 let mut call_site = ei.call_site;
654 call_site.expn_id = self.backtrace;
655 self.backtrace = self.codemap().record_expansion(ExpnInfo {
656 call_site: call_site,
660 pub fn bt_pop(&mut self) {
661 match self.backtrace {
662 NO_EXPANSION => self.bug("tried to pop without a push"),
664 self.recursion_count -= 1;
665 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
666 expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
672 pub fn insert_macro(&mut self, def: ast::MacroDef) {
674 self.exported_macros.push(def.clone());
677 let ext = macro_rules::compile(self, &def);
678 self.syntax_env.insert(def.ident.name, ext);
682 pub fn struct_span_warn(&self,
685 -> DiagnosticBuilder<'a> {
686 self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
688 pub fn struct_span_err(&self,
691 -> DiagnosticBuilder<'a> {
692 self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
694 pub fn struct_span_fatal(&self,
697 -> DiagnosticBuilder<'a> {
698 self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
701 /// Emit `msg` attached to `sp`, and stop compilation immediately.
703 /// `span_err` should be strongly preferred where-ever possible:
704 /// this should *only* be used when
705 /// - continuing has a high risk of flow-on errors (e.g. errors in
706 /// declaring a macro would cause all uses of that macro to
707 /// complain about "undefined macro"), or
708 /// - there is literally nothing else that can be done (however,
709 /// in most cases one can construct a dummy expression/item to
710 /// substitute; we never hit resolve/type-checking so the dummy
711 /// value doesn't have to match anything)
712 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
713 panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
716 /// Emit `msg` attached to `sp`, without immediately stopping
719 /// Compilation will be stopped in the near future (at the end of
720 /// the macro expansion phase).
721 pub fn span_err(&self, sp: Span, msg: &str) {
722 self.parse_sess.span_diagnostic.span_err(sp, msg);
724 pub fn span_warn(&self, sp: Span, msg: &str) {
725 self.parse_sess.span_diagnostic.span_warn(sp, msg);
727 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
728 self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
730 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
731 self.parse_sess.span_diagnostic.span_bug(sp, msg);
733 pub fn bug(&self, msg: &str) -> ! {
734 self.parse_sess.span_diagnostic.bug(msg);
736 pub fn trace_macros(&self) -> bool {
739 pub fn set_trace_macros(&mut self, x: bool) {
740 self.ecfg.trace_mac = x
742 pub fn ident_of(&self, st: &str) -> ast::Ident {
745 pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
746 let mut v = Vec::new();
747 if let Some(s) = self.crate_root {
748 v.push(self.ident_of(s));
750 v.extend(components.iter().map(|s| self.ident_of(s)));
753 pub fn name_of(&self, st: &str) -> ast::Name {
757 pub fn suggest_macro_name(&mut self,
760 err: &mut DiagnosticBuilder<'a>) {
761 let names = &self.syntax_env.names;
762 if let Some(suggestion) = find_best_match_for_name(names.iter(), name, None) {
763 err.fileline_help(span, &format!("did you mean `{}!`?", suggestion));
768 /// Extract a string literal from the macro expanded version of `expr`,
769 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
770 /// compilation on error, merely emits a non-fatal error and returns None.
771 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
772 -> Option<(InternedString, ast::StrStyle)> {
773 // we want to be able to handle e.g. concat("foo", "bar")
774 let expr = cx.expander().fold_expr(expr);
776 ast::ExprLit(ref l) => match l.node {
777 ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
778 _ => cx.span_err(l.span, err_msg)
780 _ => cx.span_err(expr.span, err_msg)
785 /// Non-fatally assert that `tts` is empty. Note that this function
786 /// returns even when `tts` is non-empty, macros that *need* to stop
787 /// compilation should call
788 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
789 /// done as rarely as possible).
790 pub fn check_zero_tts(cx: &ExtCtxt,
792 tts: &[ast::TokenTree],
795 cx.span_err(sp, &format!("{} takes no arguments", name));
799 /// Extract the string literal from the first token of `tts`. If this
800 /// is not a string literal, emit an error and return None.
801 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
803 tts: &[ast::TokenTree],
806 let mut p = cx.new_parser_from_tts(tts);
807 if p.token == token::Eof {
808 cx.span_err(sp, &format!("{} takes 1 argument", name));
811 let ret = cx.expander().fold_expr(panictry!(p.parse_expr()));
812 if p.token != token::Eof {
813 cx.span_err(sp, &format!("{} takes 1 argument", name));
815 expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
820 /// Extract comma-separated expressions from `tts`. If there is a
821 /// parsing error, emit a non-fatal error and return None.
822 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
824 tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
825 let mut p = cx.new_parser_from_tts(tts);
826 let mut es = Vec::new();
827 while p.token != token::Eof {
828 es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
829 if panictry!(p.eat(&token::Comma)){
832 if p.token != token::Eof {
833 cx.span_err(sp, "expected token: `,`");
840 /// In order to have some notion of scoping for macros,
841 /// we want to implement the notion of a transformation
844 /// This environment maps Names to SyntaxExtensions.
845 pub struct SyntaxEnv {
846 chain: Vec<MapChainFrame>,
847 /// All bang-style macro/extension names
848 /// encountered so far; to be used for diagnostics in resolve
849 pub names: HashSet<Name>,
852 // impl question: how to implement it? Initially, the
853 // env will contain only macros, so it might be painful
854 // to add an empty frame for every context. Let's just
855 // get it working, first....
857 // NB! the mutability of the underlying maps means that
858 // if expansion is out-of-order, a deeper scope may be
859 // able to refer to a macro that was added to an enclosing
860 // scope lexically later than the deeper scope.
862 struct MapChainFrame {
864 map: HashMap<Name, Rc<SyntaxExtension>>,
868 fn new() -> SyntaxEnv {
869 let mut map = SyntaxEnv { chain: Vec::new() , names: HashSet::new()};
874 pub fn push_frame(&mut self) {
875 self.chain.push(MapChainFrame {
876 info: BlockInfo::new(),
881 pub fn pop_frame(&mut self) {
882 assert!(self.chain.len() > 1, "too many pops on MapChain!");
886 fn find_escape_frame(&mut self) -> &mut MapChainFrame {
887 for (i, frame) in self.chain.iter_mut().enumerate().rev() {
888 if !frame.info.macros_escape || i == 0 {
895 pub fn find(&self, k: Name) -> Option<Rc<SyntaxExtension>> {
896 for frame in self.chain.iter().rev() {
897 match frame.map.get(&k) {
898 Some(v) => return Some(v.clone()),
905 pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
906 if let NormalTT(..) = v {
907 self.names.insert(k);
909 self.find_escape_frame().map.insert(k, Rc::new(v));
912 pub fn info(&mut self) -> &mut BlockInfo {
913 let last_chain_index = self.chain.len() - 1;
914 &mut self.chain[last_chain_index].info