]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Register new snapshots
[rust.git] / src / libsyntax / ext / base.rs
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.
4 //
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.
10
11 use ast;
12 use ast::Name;
13 use codemap;
14 use codemap::{CodeMap, Span, ExpnInfo};
15 use ext;
16 use ext::expand;
17 use parse;
18 use parse::token;
19 use parse::token::{InternedString, intern, str_to_ident};
20 use util::small_vector::SmallVector;
21
22 use std::collections::HashMap;
23 use std::gc::{Gc, GC};
24
25 // new-style macro! tt code:
26 //
27 //    MacResult, NormalTT, IdentTT
28 //
29 // also note that ast::Mac used to have a bunch of extraneous cases and
30 // is now probably a redundant AST node, can be merged with
31 // ast::MacInvocTT.
32
33 pub struct MacroDef {
34     pub name: String,
35     pub ext: SyntaxExtension
36 }
37
38 pub type ItemDecorator =
39     fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>, |Gc<ast::Item>|);
40
41 pub type ItemModifier =
42     fn(&mut ExtCtxt, Span, Gc<ast::MetaItem>, Gc<ast::Item>) -> Gc<ast::Item>;
43
44 pub struct BasicMacroExpander {
45     pub expander: MacroExpanderFn,
46     pub span: Option<Span>
47 }
48
49 pub trait MacroExpander {
50     fn expand(&self,
51               ecx: &mut ExtCtxt,
52               span: Span,
53               token_tree: &[ast::TokenTree])
54               -> Box<MacResult>;
55 }
56
57 pub type MacroExpanderFn =
58     fn(ecx: &mut ExtCtxt, span: codemap::Span, token_tree: &[ast::TokenTree])
59        -> Box<MacResult>;
60
61 impl MacroExpander for BasicMacroExpander {
62     fn expand(&self,
63               ecx: &mut ExtCtxt,
64               span: Span,
65               token_tree: &[ast::TokenTree])
66               -> Box<MacResult> {
67         (self.expander)(ecx, span, token_tree)
68     }
69 }
70
71 pub struct BasicIdentMacroExpander {
72     pub expander: IdentMacroExpanderFn,
73     pub span: Option<Span>
74 }
75
76 pub trait IdentMacroExpander {
77     fn expand(&self,
78               cx: &mut ExtCtxt,
79               sp: Span,
80               ident: ast::Ident,
81               token_tree: Vec<ast::TokenTree> )
82               -> Box<MacResult>;
83 }
84
85 impl IdentMacroExpander for BasicIdentMacroExpander {
86     fn expand(&self,
87               cx: &mut ExtCtxt,
88               sp: Span,
89               ident: ast::Ident,
90               token_tree: Vec<ast::TokenTree> )
91               -> Box<MacResult> {
92         (self.expander)(cx, sp, ident, token_tree)
93     }
94 }
95
96 pub type IdentMacroExpanderFn =
97     fn(&mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult>;
98
99 /// The result of a macro expansion. The return values of the various
100 /// methods are spliced into the AST at the callsite of the macro (or
101 /// just into the compiler's internal macro table, for `make_def`).
102 pub trait MacResult {
103     /// Define a new macro.
104     fn make_def(&self) -> Option<MacroDef> {
105         None
106     }
107     /// Create an expression.
108     fn make_expr(&self) -> Option<Gc<ast::Expr>> {
109         None
110     }
111     /// Create zero or more items.
112     fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
113         None
114     }
115     /// Create a pattern.
116     fn make_pat(&self) -> Option<Gc<ast::Pat>> {
117         None
118     }
119
120     /// Create a statement.
121     ///
122     /// By default this attempts to create an expression statement,
123     /// returning None if that fails.
124     fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
125         self.make_expr()
126             .map(|e| box(GC) codemap::respan(e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID)))
127     }
128 }
129
130 /// A convenience type for macros that return a single expression.
131 pub struct MacExpr {
132     e: Gc<ast::Expr>,
133 }
134 impl MacExpr {
135     pub fn new(e: Gc<ast::Expr>) -> Box<MacResult> {
136         box MacExpr { e: e } as Box<MacResult>
137     }
138 }
139 impl MacResult for MacExpr {
140     fn make_expr(&self) -> Option<Gc<ast::Expr>> {
141         Some(self.e)
142     }
143 }
144 /// A convenience type for macros that return a single pattern.
145 pub struct MacPat {
146     p: Gc<ast::Pat>,
147 }
148 impl MacPat {
149     pub fn new(p: Gc<ast::Pat>) -> Box<MacResult> {
150         box MacPat { p: p } as Box<MacResult>
151     }
152 }
153 impl MacResult for MacPat {
154     fn make_pat(&self) -> Option<Gc<ast::Pat>> {
155         Some(self.p)
156     }
157 }
158 /// A convenience type for macros that return a single item.
159 pub struct MacItem {
160     i: Gc<ast::Item>
161 }
162 impl MacItem {
163     pub fn new(i: Gc<ast::Item>) -> Box<MacResult> {
164         box MacItem { i: i } as Box<MacResult>
165     }
166 }
167 impl MacResult for MacItem {
168     fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
169         Some(SmallVector::one(self.i))
170     }
171     fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
172         Some(box(GC) codemap::respan(
173             self.i.span,
174             ast::StmtDecl(
175                 box(GC) codemap::respan(self.i.span, ast::DeclItem(self.i)),
176                 ast::DUMMY_NODE_ID)))
177     }
178 }
179
180 /// Fill-in macro expansion result, to allow compilation to continue
181 /// after hitting errors.
182 pub struct DummyResult {
183     expr_only: bool,
184     span: Span
185 }
186
187 impl DummyResult {
188     /// Create a default MacResult that can be anything.
189     ///
190     /// Use this as a return value after hitting any errors and
191     /// calling `span_err`.
192     pub fn any(sp: Span) -> Box<MacResult> {
193         box DummyResult { expr_only: false, span: sp } as Box<MacResult>
194     }
195
196     /// Create a default MacResult that can only be an expression.
197     ///
198     /// Use this for macros that must expand to an expression, so even
199     /// if an error is encountered internally, the user will receive
200     /// an error that they also used it in the wrong place.
201     pub fn expr(sp: Span) -> Box<MacResult> {
202         box DummyResult { expr_only: true, span: sp } as Box<MacResult>
203     }
204
205     /// A plain dummy expression.
206     pub fn raw_expr(sp: Span) -> Gc<ast::Expr> {
207         box(GC) ast::Expr {
208             id: ast::DUMMY_NODE_ID,
209             node: ast::ExprLit(box(GC) codemap::respan(sp, ast::LitNil)),
210             span: sp,
211         }
212     }
213
214     /// A plain dummy pattern.
215     pub fn raw_pat(sp: Span) -> Gc<ast::Pat> {
216         box(GC) ast::Pat {
217             id: ast::DUMMY_NODE_ID,
218             node: ast::PatWild,
219             span: sp,
220         }
221     }
222 }
223
224 impl MacResult for DummyResult {
225     fn make_expr(&self) -> Option<Gc<ast::Expr>> {
226         Some(DummyResult::raw_expr(self.span))
227     }
228     fn make_pat(&self) -> Option<Gc<ast::Pat>> {
229         Some(DummyResult::raw_pat(self.span))
230     }
231     fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
232         if self.expr_only {
233             None
234         } else {
235             Some(SmallVector::zero())
236         }
237     }
238     fn make_stmt(&self) -> Option<Gc<ast::Stmt>> {
239         Some(box(GC) codemap::respan(self.span,
240                               ast::StmtExpr(DummyResult::raw_expr(self.span),
241                                             ast::DUMMY_NODE_ID)))
242     }
243 }
244
245 /// An enum representing the different kinds of syntax extensions.
246 pub enum SyntaxExtension {
247     /// A syntax extension that is attached to an item and creates new items
248     /// based upon it.
249     ///
250     /// `#[deriving(...)]` is an `ItemDecorator`.
251     ItemDecorator(ItemDecorator),
252
253     /// A syntax extension that is attached to an item and modifies it
254     /// in-place.
255     ItemModifier(ItemModifier),
256
257     /// A normal, function-like syntax extension.
258     ///
259     /// `bytes!` is a `NormalTT`.
260     NormalTT(Box<MacroExpander + 'static>, Option<Span>),
261
262     /// A function-like syntax extension that has an extra ident before
263     /// the block.
264     ///
265     /// `macro_rules!` is an `IdentTT`.
266     IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>),
267 }
268
269 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
270
271 pub struct BlockInfo {
272     // should macros escape from this scope?
273     pub macros_escape: bool,
274     // what are the pending renames?
275     pub pending_renames: RenameList,
276 }
277
278 impl BlockInfo {
279     pub fn new() -> BlockInfo {
280         BlockInfo {
281             macros_escape: false,
282             pending_renames: Vec::new(),
283         }
284     }
285 }
286
287 // a list of ident->name renamings
288 pub type RenameList = Vec<(ast::Ident, Name)>;
289
290 // The base map of methods for expanding syntax extension
291 // AST nodes into full ASTs
292 pub fn syntax_expander_table() -> SyntaxEnv {
293     // utility function to simplify creating NormalTT syntax extensions
294     fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
295         NormalTT(box BasicMacroExpander {
296                 expander: f,
297                 span: None,
298             },
299             None)
300     }
301
302     let mut syntax_expanders = SyntaxEnv::new();
303     syntax_expanders.insert(intern("macro_rules"),
304                             IdentTT(box BasicIdentMacroExpander {
305                                 expander: ext::tt::macro_rules::add_new_extension,
306                                 span: None,
307                             },
308                             None));
309     syntax_expanders.insert(intern("fmt"),
310                             builtin_normal_expander(
311                                 ext::fmt::expand_syntax_ext));
312     syntax_expanders.insert(intern("format_args"),
313                             builtin_normal_expander(
314                                 ext::format::expand_format_args));
315     syntax_expanders.insert(intern("format_args_method"),
316                             builtin_normal_expander(
317                                 ext::format::expand_format_args_method));
318     syntax_expanders.insert(intern("env"),
319                             builtin_normal_expander(
320                                     ext::env::expand_env));
321     syntax_expanders.insert(intern("option_env"),
322                             builtin_normal_expander(
323                                     ext::env::expand_option_env));
324     syntax_expanders.insert(intern("bytes"),
325                             builtin_normal_expander(
326                                     ext::bytes::expand_syntax_ext));
327     syntax_expanders.insert(intern("concat_idents"),
328                             builtin_normal_expander(
329                                     ext::concat_idents::expand_syntax_ext));
330     syntax_expanders.insert(intern("concat"),
331                             builtin_normal_expander(
332                                     ext::concat::expand_syntax_ext));
333     syntax_expanders.insert(intern("log_syntax"),
334                             builtin_normal_expander(
335                                     ext::log_syntax::expand_syntax_ext));
336     syntax_expanders.insert(intern("deriving"),
337                             ItemDecorator(ext::deriving::expand_meta_deriving));
338
339     // Quasi-quoting expanders
340     syntax_expanders.insert(intern("quote_tokens"),
341                        builtin_normal_expander(
342                             ext::quote::expand_quote_tokens));
343     syntax_expanders.insert(intern("quote_expr"),
344                        builtin_normal_expander(
345                             ext::quote::expand_quote_expr));
346     syntax_expanders.insert(intern("quote_ty"),
347                        builtin_normal_expander(
348                             ext::quote::expand_quote_ty));
349     syntax_expanders.insert(intern("quote_item"),
350                        builtin_normal_expander(
351                             ext::quote::expand_quote_item));
352     syntax_expanders.insert(intern("quote_pat"),
353                        builtin_normal_expander(
354                             ext::quote::expand_quote_pat));
355     syntax_expanders.insert(intern("quote_stmt"),
356                        builtin_normal_expander(
357                             ext::quote::expand_quote_stmt));
358
359     syntax_expanders.insert(intern("line"),
360                             builtin_normal_expander(
361                                     ext::source_util::expand_line));
362     syntax_expanders.insert(intern("col"),
363                             builtin_normal_expander(
364                                     ext::source_util::expand_col));
365     syntax_expanders.insert(intern("file"),
366                             builtin_normal_expander(
367                                     ext::source_util::expand_file));
368     syntax_expanders.insert(intern("stringify"),
369                             builtin_normal_expander(
370                                     ext::source_util::expand_stringify));
371     syntax_expanders.insert(intern("include"),
372                             builtin_normal_expander(
373                                     ext::source_util::expand_include));
374     syntax_expanders.insert(intern("include_str"),
375                             builtin_normal_expander(
376                                     ext::source_util::expand_include_str));
377     syntax_expanders.insert(intern("include_bin"),
378                             builtin_normal_expander(
379                                     ext::source_util::expand_include_bin));
380     syntax_expanders.insert(intern("module_path"),
381                             builtin_normal_expander(
382                                     ext::source_util::expand_mod));
383     syntax_expanders.insert(intern("asm"),
384                             builtin_normal_expander(
385                                     ext::asm::expand_asm));
386     syntax_expanders.insert(intern("cfg"),
387                             builtin_normal_expander(
388                                     ext::cfg::expand_cfg));
389     syntax_expanders.insert(intern("trace_macros"),
390                             builtin_normal_expander(
391                                     ext::trace_macros::expand_trace_macros));
392     syntax_expanders
393 }
394
395 // One of these is made during expansion and incrementally updated as we go;
396 // when a macro expansion occurs, the resulting nodes have the backtrace()
397 // -> expn_info of their expansion context stored into their span.
398 pub struct ExtCtxt<'a> {
399     pub parse_sess: &'a parse::ParseSess,
400     pub cfg: ast::CrateConfig,
401     pub backtrace: Option<Gc<ExpnInfo>>,
402     pub ecfg: expand::ExpansionConfig,
403
404     pub mod_path: Vec<ast::Ident> ,
405     pub trace_mac: bool,
406 }
407
408 impl<'a> ExtCtxt<'a> {
409     pub fn new<'a>(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
410                    ecfg: expand::ExpansionConfig) -> ExtCtxt<'a> {
411         ExtCtxt {
412             parse_sess: parse_sess,
413             cfg: cfg,
414             backtrace: None,
415             mod_path: Vec::new(),
416             ecfg: ecfg,
417             trace_mac: false
418         }
419     }
420
421     pub fn expand_expr(&mut self, mut e: Gc<ast::Expr>) -> Gc<ast::Expr> {
422         loop {
423             match e.node {
424                 ast::ExprMac(..) => {
425                     let mut expander = expand::MacroExpander {
426                         extsbox: syntax_expander_table(),
427                         cx: self,
428                     };
429                     e = expand::expand_expr(e, &mut expander);
430                 }
431                 _ => return e
432             }
433         }
434     }
435
436     pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm }
437     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
438     pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
439     pub fn call_site(&self) -> Span {
440         match self.backtrace {
441             Some(expn_info) => expn_info.call_site,
442             None => self.bug("missing top span")
443         }
444     }
445     pub fn print_backtrace(&self) { }
446     pub fn backtrace(&self) -> Option<Gc<ExpnInfo>> { self.backtrace }
447     pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
448     pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
449     pub fn mod_path(&self) -> Vec<ast::Ident> {
450         let mut v = Vec::new();
451         v.push(token::str_to_ident(self.ecfg.crate_id.name.as_slice()));
452         v.extend(self.mod_path.iter().map(|a| *a));
453         return v;
454     }
455     pub fn bt_push(&mut self, ei: codemap::ExpnInfo) {
456         match ei {
457             ExpnInfo {call_site: cs, callee: ref callee} => {
458                 self.backtrace =
459                     Some(box(GC) ExpnInfo {
460                         call_site: Span {lo: cs.lo, hi: cs.hi,
461                                          expn_info: self.backtrace.clone()},
462                         callee: (*callee).clone()
463                     });
464             }
465         }
466     }
467     pub fn bt_pop(&mut self) {
468         match self.backtrace {
469             Some(expn_info) => self.backtrace = expn_info.call_site.expn_info,
470             _ => self.bug("tried to pop without a push")
471         }
472     }
473     /// Emit `msg` attached to `sp`, and stop compilation immediately.
474     ///
475     /// `span_err` should be strongly prefered where-ever possible:
476     /// this should *only* be used when
477     /// - continuing has a high risk of flow-on errors (e.g. errors in
478     ///   declaring a macro would cause all uses of that macro to
479     ///   complain about "undefined macro"), or
480     /// - there is literally nothing else that can be done (however,
481     ///   in most cases one can construct a dummy expression/item to
482     ///   substitute; we never hit resolve/type-checking so the dummy
483     ///   value doesn't have to match anything)
484     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
485         self.print_backtrace();
486         self.parse_sess.span_diagnostic.span_fatal(sp, msg);
487     }
488
489     /// Emit `msg` attached to `sp`, without immediately stopping
490     /// compilation.
491     ///
492     /// Compilation will be stopped in the near future (at the end of
493     /// the macro expansion phase).
494     pub fn span_err(&self, sp: Span, msg: &str) {
495         self.print_backtrace();
496         self.parse_sess.span_diagnostic.span_err(sp, msg);
497     }
498     pub fn span_warn(&self, sp: Span, msg: &str) {
499         self.print_backtrace();
500         self.parse_sess.span_diagnostic.span_warn(sp, msg);
501     }
502     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
503         self.print_backtrace();
504         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
505     }
506     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
507         self.print_backtrace();
508         self.parse_sess.span_diagnostic.span_bug(sp, msg);
509     }
510     pub fn span_note(&self, sp: Span, msg: &str) {
511         self.print_backtrace();
512         self.parse_sess.span_diagnostic.span_note(sp, msg);
513     }
514     pub fn bug(&self, msg: &str) -> ! {
515         self.print_backtrace();
516         self.parse_sess.span_diagnostic.handler().bug(msg);
517     }
518     pub fn trace_macros(&self) -> bool {
519         self.trace_mac
520     }
521     pub fn set_trace_macros(&mut self, x: bool) {
522         self.trace_mac = x
523     }
524     pub fn ident_of(&self, st: &str) -> ast::Ident {
525         str_to_ident(st)
526     }
527 }
528
529 /// Extract a string literal from the macro expanded version of `expr`,
530 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
531 /// compilation on error, merely emits a non-fatal error and returns None.
532 pub fn expr_to_str(cx: &mut ExtCtxt, expr: Gc<ast::Expr>, err_msg: &str)
533                    -> Option<(InternedString, ast::StrStyle)> {
534     // we want to be able to handle e.g. concat("foo", "bar")
535     let expr = cx.expand_expr(expr);
536     match expr.node {
537         ast::ExprLit(l) => match l.node {
538             ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
539             _ => cx.span_err(l.span, err_msg)
540         },
541         _ => cx.span_err(expr.span, err_msg)
542     }
543     None
544 }
545
546 /// Non-fatally assert that `tts` is empty. Note that this function
547 /// returns even when `tts` is non-empty, macros that *need* to stop
548 /// compilation should call
549 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
550 /// done as rarely as possible).
551 pub fn check_zero_tts(cx: &ExtCtxt,
552                       sp: Span,
553                       tts: &[ast::TokenTree],
554                       name: &str) {
555     if tts.len() != 0 {
556         cx.span_err(sp, format!("{} takes no arguments", name).as_slice());
557     }
558 }
559
560 /// Extract the string literal from the first token of `tts`. If this
561 /// is not a string literal, emit an error and return None.
562 pub fn get_single_str_from_tts(cx: &ExtCtxt,
563                                sp: Span,
564                                tts: &[ast::TokenTree],
565                                name: &str)
566                                -> Option<String> {
567     if tts.len() != 1 {
568         cx.span_err(sp, format!("{} takes 1 argument.", name).as_slice());
569     } else {
570         match tts[0] {
571             ast::TTTok(_, token::LIT_STR(ident))
572             | ast::TTTok(_, token::LIT_STR_RAW(ident, _)) => {
573                 return Some(token::get_ident(ident).get().to_string())
574             }
575             _ => {
576                 cx.span_err(sp,
577                             format!("{} requires a string.", name).as_slice())
578             }
579         }
580     }
581     None
582 }
583
584 /// Extract comma-separated expressions from `tts`. If there is a
585 /// parsing error, emit a non-fatal error and return None.
586 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
587                           sp: Span,
588                           tts: &[ast::TokenTree]) -> Option<Vec<Gc<ast::Expr>>> {
589     let mut p = parse::new_parser_from_tts(cx.parse_sess(),
590                                            cx.cfg(),
591                                            tts.iter()
592                                               .map(|x| (*x).clone())
593                                               .collect());
594     let mut es = Vec::new();
595     while p.token != token::EOF {
596         if es.len() != 0 && !p.eat(&token::COMMA) {
597             cx.span_err(sp, "expected token: `,`");
598             return None;
599         }
600         es.push(cx.expand_expr(p.parse_expr()));
601     }
602     Some(es)
603 }
604
605 // in order to have some notion of scoping for macros,
606 // we want to implement the notion of a transformation
607 // environment.
608
609 // This environment maps Names to SyntaxExtensions.
610
611 //impl question: how to implement it? Initially, the
612 // env will contain only macros, so it might be painful
613 // to add an empty frame for every context. Let's just
614 // get it working, first....
615
616 // NB! the mutability of the underlying maps means that
617 // if expansion is out-of-order, a deeper scope may be
618 // able to refer to a macro that was added to an enclosing
619 // scope lexically later than the deeper scope.
620
621 struct MapChainFrame {
622     info: BlockInfo,
623     map: HashMap<Name, SyntaxExtension>,
624 }
625
626 // Only generic to make it easy to test
627 pub struct SyntaxEnv {
628     chain: Vec<MapChainFrame> ,
629 }
630
631 impl SyntaxEnv {
632     pub fn new() -> SyntaxEnv {
633         let mut map = SyntaxEnv { chain: Vec::new() };
634         map.push_frame();
635         map
636     }
637
638     pub fn push_frame(&mut self) {
639         self.chain.push(MapChainFrame {
640             info: BlockInfo::new(),
641             map: HashMap::new(),
642         });
643     }
644
645     pub fn pop_frame(&mut self) {
646         assert!(self.chain.len() > 1, "too many pops on MapChain!");
647         self.chain.pop();
648     }
649
650     fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
651         for (i, frame) in self.chain.mut_iter().enumerate().rev() {
652             if !frame.info.macros_escape || i == 0 {
653                 return frame
654             }
655         }
656         unreachable!()
657     }
658
659     pub fn find<'a>(&'a self, k: &Name) -> Option<&'a SyntaxExtension> {
660         for frame in self.chain.iter().rev() {
661             match frame.map.find(k) {
662                 Some(v) => return Some(v),
663                 None => {}
664             }
665         }
666         None
667     }
668
669     pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
670         self.find_escape_frame().map.insert(k, v);
671     }
672
673     pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
674         let last_chain_index = self.chain.len() - 1;
675         &mut self.chain.get_mut(last_chain_index).info
676     }
677 }