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