]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Auto merge of #28969 - chrisccerami:link_to_ffi_in_concurrency_chapter, r=steveklabnik
[rust.git] / src / libsyntax / ext / base.rs
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.
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 pub use self::SyntaxExtension::*;
12
13 use ast;
14 use ast::Name;
15 use codemap;
16 use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION};
17 use ext;
18 use ext::expand;
19 use ext::tt::macro_rules;
20 use feature_gate::GatedCfg;
21 use parse;
22 use parse::parser;
23 use parse::token;
24 use parse::token::{InternedString, intern, str_to_ident};
25 use ptr::P;
26 use util::small_vector::SmallVector;
27 use ext::mtwt;
28 use fold::Folder;
29
30 use std::collections::HashMap;
31 use std::rc::Rc;
32 use std::default::Default;
33
34
35 #[derive(Debug,Clone)]
36 pub enum Annotatable {
37     Item(P<ast::Item>),
38     TraitItem(P<ast::TraitItem>),
39     ImplItem(P<ast::ImplItem>),
40 }
41
42 impl Annotatable {
43     pub fn attrs(&self) -> &[ast::Attribute] {
44         match *self {
45             Annotatable::Item(ref i) => &i.attrs,
46             Annotatable::TraitItem(ref ti) => &ti.attrs,
47             Annotatable::ImplItem(ref ii) => &ii.attrs,
48         }
49     }
50
51     pub fn fold_attrs(self, attrs: Vec<ast::Attribute>) -> Annotatable {
52         match self {
53             Annotatable::Item(i) => Annotatable::Item(i.map(|i| ast::Item {
54                 attrs: attrs,
55                 ..i
56             })),
57             Annotatable::TraitItem(i) => Annotatable::TraitItem(i.map(|ti| {
58                 ast::TraitItem { attrs: attrs, ..ti }
59             })),
60             Annotatable::ImplItem(i) => Annotatable::ImplItem(i.map(|ii| {
61                 ast::ImplItem { attrs: attrs, ..ii }
62             })),
63         }
64     }
65
66     pub fn expect_item(self) -> P<ast::Item> {
67         match self {
68             Annotatable::Item(i) => i,
69             _ => panic!("expected Item")
70         }
71     }
72
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
76     {
77         match self {
78             Annotatable::Item(i) => Annotatable::Item(f(i)),
79             _ => or(self)
80         }
81     }
82
83     pub fn expect_trait_item(self) -> P<ast::TraitItem> {
84         match self {
85             Annotatable::TraitItem(i) => i,
86             _ => panic!("expected Item")
87         }
88     }
89
90     pub fn expect_impl_item(self) -> P<ast::ImplItem> {
91         match self {
92             Annotatable::ImplItem(i) => i,
93             _ => panic!("expected Item")
94         }
95     }
96 }
97
98 // A more flexible ItemDecorator.
99 pub trait MultiItemDecorator {
100     fn expand(&self,
101               ecx: &mut ExtCtxt,
102               sp: Span,
103               meta_item: &ast::MetaItem,
104               item: &Annotatable,
105               push: &mut FnMut(Annotatable));
106 }
107
108 impl<F> MultiItemDecorator for F
109     where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
110 {
111     fn expand(&self,
112               ecx: &mut ExtCtxt,
113               sp: Span,
114               meta_item: &ast::MetaItem,
115               item: &Annotatable,
116               push: &mut FnMut(Annotatable)) {
117         (*self)(ecx, sp, meta_item, item, push)
118     }
119 }
120
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 {
126     fn expand(&self,
127               ecx: &mut ExtCtxt,
128               span: Span,
129               meta_item: &ast::MetaItem,
130               item: Annotatable)
131               -> Annotatable;
132 }
133
134 impl<F> MultiItemModifier for F
135     where F: Fn(&mut ExtCtxt,
136                 Span,
137                 &ast::MetaItem,
138                 Annotatable) -> Annotatable
139 {
140     fn expand(&self,
141               ecx: &mut ExtCtxt,
142               span: Span,
143               meta_item: &ast::MetaItem,
144               item: Annotatable)
145               -> Annotatable {
146         (*self)(ecx, span, meta_item, item)
147     }
148 }
149
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,
154                    span: Span,
155                    token_tree: &[ast::TokenTree])
156                    -> Box<MacResult+'cx>;
157 }
158
159 pub type MacroExpanderFn =
160     for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
161
162 impl<F> TTMacroExpander for F
163     where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>
164 {
165     fn expand<'cx>(&self,
166                    ecx: &'cx mut ExtCtxt,
167                    span: Span,
168                    token_tree: &[ast::TokenTree])
169                    -> Box<MacResult+'cx> {
170         (*self)(ecx, span, token_tree)
171     }
172 }
173
174 pub trait IdentMacroExpander {
175     fn expand<'cx>(&self,
176                    cx: &'cx mut ExtCtxt,
177                    sp: Span,
178                    ident: ast::Ident,
179                    token_tree: Vec<ast::TokenTree> )
180                    -> Box<MacResult+'cx>;
181 }
182
183 pub type IdentMacroExpanderFn =
184     for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
185
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>
189 {
190     fn expand<'cx>(&self,
191                    cx: &'cx mut ExtCtxt,
192                    sp: Span,
193                    ident: ast::Ident,
194                    token_tree: Vec<ast::TokenTree> )
195                    -> Box<MacResult+'cx>
196     {
197         (*self)(cx, sp, ident, token_tree)
198     }
199 }
200
201 // Use a macro because forwarding to a simple function has type system issues
202 macro_rules! make_stmts_default {
203     ($me:expr) => {
204         $me.make_expr().map(|e| {
205             SmallVector::one(P(codemap::respan(
206                 e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
207         })
208     }
209 }
210
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>> {
216         None
217     }
218     /// Create zero or more items.
219     fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
220         None
221     }
222
223     /// Create zero or more impl items.
224     fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
225         None
226     }
227
228     /// Create a pattern.
229     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
230         None
231     }
232
233     /// Create zero or more statements.
234     ///
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)
239     }
240
241     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
242         None
243     }
244 }
245
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.
250         #[derive(Default)]
251         pub struct MacEager {
252             $(
253                 pub $fld: Option<$t>,
254             )*
255         }
256
257         impl MacEager {
258             $(
259                 pub fn $fld(v: $t) -> Box<MacResult> {
260                     Box::new(MacEager {
261                         $fld: Some(v),
262                         ..Default::default()
263                     })
264                 }
265             )*
266         }
267     }
268 }
269
270 make_MacEager! {
271     expr: P<ast::Expr>,
272     pat: P<ast::Pat>,
273     items: SmallVector<P<ast::Item>>,
274     impl_items: SmallVector<P<ast::ImplItem>>,
275     stmts: SmallVector<P<ast::Stmt>>,
276     ty: P<ast::Ty>,
277 }
278
279 impl MacResult for MacEager {
280     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
281         self.expr
282     }
283
284     fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
285         self.items
286     }
287
288     fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
289         self.impl_items
290     }
291
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),
295             _ => self.stmts,
296         }
297     }
298
299     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
300         if let Some(p) = self.pat {
301             return Some(p);
302         }
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,
307                     span: e.span,
308                     node: ast::PatLit(e),
309                 }));
310             }
311         }
312         None
313     }
314
315     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
316         self.ty
317     }
318 }
319
320 /// Fill-in macro expansion result, to allow compilation to continue
321 /// after hitting errors.
322 #[derive(Copy, Clone)]
323 pub struct DummyResult {
324     expr_only: bool,
325     span: Span
326 }
327
328 impl DummyResult {
329     /// Create a default MacResult that can be anything.
330     ///
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 })
335     }
336
337     /// Create a default MacResult that can only be an expression.
338     ///
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 })
344     }
345
346     /// A plain dummy expression.
347     pub fn raw_expr(sp: Span) -> P<ast::Expr> {
348         P(ast::Expr {
349             id: ast::DUMMY_NODE_ID,
350             node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
351             span: sp,
352         })
353     }
354
355     /// A plain dummy pattern.
356     pub fn raw_pat(sp: Span) -> ast::Pat {
357         ast::Pat {
358             id: ast::DUMMY_NODE_ID,
359             node: ast::PatWild(ast::PatWildSingle),
360             span: sp,
361         }
362     }
363
364     pub fn raw_ty(sp: Span) -> P<ast::Ty> {
365         P(ast::Ty {
366             id: ast::DUMMY_NODE_ID,
367             node: ast::TyInfer,
368             span: sp
369         })
370     }
371 }
372
373 impl MacResult for DummyResult {
374     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
375         Some(DummyResult::raw_expr(self.span))
376     }
377
378     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
379         Some(P(DummyResult::raw_pat(self.span)))
380     }
381
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() ?
384         if self.expr_only {
385             None
386         } else {
387             Some(SmallVector::zero())
388         }
389     }
390
391     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::ImplItem>>> {
392         if self.expr_only {
393             None
394         } else {
395             Some(SmallVector::zero())
396         }
397     }
398
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)))))
404     }
405 }
406
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
410     /// based upon it.
411     ///
412     /// `#[derive(...)]` is a `MultiItemDecorator`.
413     MultiDecorator(Box<MultiItemDecorator + 'static>),
414
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>),
418
419     /// A normal, function-like syntax extension.
420     ///
421     /// `bytes!` is a `NormalTT`.
422     ///
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),
426
427     /// A function-like syntax extension that has an extra ident before
428     /// the block.
429     ///
430     IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>, bool),
431
432     /// Represents `macro_rules!` itself.
433     MacroRulesTT,
434 }
435
436 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
437
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,
443 }
444
445 impl BlockInfo {
446     pub fn new() -> BlockInfo {
447         BlockInfo {
448             macros_escape: false,
449             pending_renames: Vec::new(),
450         }
451     }
452 }
453
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>)
457                                         -> SyntaxEnv {
458     // utility function to simplify creating NormalTT syntax extensions
459     fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
460         NormalTT(Box::new(f), None, false)
461     }
462
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));
483
484     ext::deriving::register_all(&mut syntax_expanders);
485
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));
515     }
516
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("push_unsafe"),
548                             builtin_normal_expander(
549                                 ext::pushpop_safe::expand_push_unsafe));
550     syntax_expanders.insert(intern("pop_unsafe"),
551                             builtin_normal_expander(
552                                 ext::pushpop_safe::expand_pop_unsafe));
553     syntax_expanders.insert(intern("trace_macros"),
554                             builtin_normal_expander(
555                                     ext::trace_macros::expand_trace_macros));
556     syntax_expanders
557 }
558
559 /// One of these is made during expansion and incrementally updated as we go;
560 /// when a macro expansion occurs, the resulting nodes have the backtrace()
561 /// -> expn_info of their expansion context stored into their span.
562 pub struct ExtCtxt<'a> {
563     pub parse_sess: &'a parse::ParseSess,
564     pub cfg: ast::CrateConfig,
565     pub backtrace: ExpnId,
566     pub ecfg: expand::ExpansionConfig<'a>,
567     pub crate_root: Option<&'static str>,
568     pub feature_gated_cfgs: &'a mut Vec<GatedCfg>,
569
570     pub mod_path: Vec<ast::Ident> ,
571     pub exported_macros: Vec<ast::MacroDef>,
572
573     pub syntax_env: SyntaxEnv,
574     pub recursion_count: usize,
575 }
576
577 impl<'a> ExtCtxt<'a> {
578     pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
579                ecfg: expand::ExpansionConfig<'a>,
580                feature_gated_cfgs: &'a mut Vec<GatedCfg>) -> ExtCtxt<'a> {
581         let env = initial_syntax_expander_table(&ecfg);
582         ExtCtxt {
583             parse_sess: parse_sess,
584             cfg: cfg,
585             backtrace: NO_EXPANSION,
586             mod_path: Vec::new(),
587             ecfg: ecfg,
588             crate_root: None,
589             feature_gated_cfgs: feature_gated_cfgs,
590             exported_macros: Vec::new(),
591             syntax_env: env,
592             recursion_count: 0,
593         }
594     }
595
596     #[unstable(feature = "rustc_private")]
597     #[deprecated(since = "1.0.0",
598                  reason = "Replaced with `expander().fold_expr()`")]
599     pub fn expand_expr(&mut self, e: P<ast::Expr>) -> P<ast::Expr> {
600         self.expander().fold_expr(e)
601     }
602
603     /// Returns a `Folder` for deeply expanding all macros in an AST node.
604     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
605         expand::MacroExpander::new(self)
606     }
607
608     pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree])
609         -> parser::Parser<'a> {
610         parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg())
611     }
612
613     pub fn codemap(&self) -> &'a CodeMap { self.parse_sess.codemap() }
614     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
615     pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() }
616     pub fn call_site(&self) -> Span {
617         self.codemap().with_expn_info(self.backtrace, |ei| match ei {
618             Some(expn_info) => expn_info.call_site,
619             None => self.bug("missing top span")
620         })
621     }
622     pub fn backtrace(&self) -> ExpnId { self.backtrace }
623
624     /// Original span that caused the current exapnsion to happen.
625     pub fn original_span(&self) -> Span {
626         let mut expn_id = self.backtrace;
627         let mut call_site = None;
628         loop {
629             match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
630                 None => break,
631                 Some(cs) => {
632                     call_site = Some(cs);
633                     expn_id = cs.expn_id;
634                 }
635             }
636         }
637         call_site.expect("missing expansion backtrace")
638     }
639
640     /// Returns span for the macro which originally caused the current expansion to happen.
641     ///
642     /// Stops backtracing at include! boundary.
643     pub fn expansion_cause(&self) -> Span {
644         let mut expn_id = self.backtrace;
645         let mut last_macro = None;
646         loop {
647             if self.codemap().with_expn_info(expn_id, |info| {
648                 info.map_or(None, |i| {
649                     if i.callee.name().as_str() == "include" {
650                         // Stop going up the backtrace once include! is encountered
651                         return None;
652                     }
653                     expn_id = i.call_site.expn_id;
654                     last_macro = Some(i.call_site);
655                     return Some(());
656                 })
657             }).is_none() {
658                 break
659             }
660         }
661         last_macro.expect("missing expansion backtrace")
662     }
663
664     pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); }
665     pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); }
666     pub fn mod_path(&self) -> Vec<ast::Ident> {
667         let mut v = Vec::new();
668         v.push(token::str_to_ident(&self.ecfg.crate_name));
669         v.extend(self.mod_path.iter().cloned());
670         return v;
671     }
672     pub fn bt_push(&mut self, ei: ExpnInfo) {
673         self.recursion_count += 1;
674         if self.recursion_count > self.ecfg.recursion_limit {
675             panic!(self.span_fatal(ei.call_site,
676                             &format!("recursion limit reached while expanding the macro `{}`",
677                                     ei.callee.name())));
678         }
679
680         let mut call_site = ei.call_site;
681         call_site.expn_id = self.backtrace;
682         self.backtrace = self.codemap().record_expansion(ExpnInfo {
683             call_site: call_site,
684             callee: ei.callee
685         });
686     }
687     pub fn bt_pop(&mut self) {
688         match self.backtrace {
689             NO_EXPANSION => self.bug("tried to pop without a push"),
690             expn_id => {
691                 self.recursion_count -= 1;
692                 self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| {
693                     expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id)
694                 });
695             }
696         }
697     }
698
699     pub fn insert_macro(&mut self, def: ast::MacroDef) {
700         if def.export {
701             self.exported_macros.push(def.clone());
702         }
703         if def.use_locally {
704             let ext = macro_rules::compile(self, &def);
705             self.syntax_env.insert(def.ident.name, ext);
706         }
707     }
708
709     /// Emit `msg` attached to `sp`, and stop compilation immediately.
710     ///
711     /// `span_err` should be strongly preferred where-ever possible:
712     /// this should *only* be used when
713     /// - continuing has a high risk of flow-on errors (e.g. errors in
714     ///   declaring a macro would cause all uses of that macro to
715     ///   complain about "undefined macro"), or
716     /// - there is literally nothing else that can be done (however,
717     ///   in most cases one can construct a dummy expression/item to
718     ///   substitute; we never hit resolve/type-checking so the dummy
719     ///   value doesn't have to match anything)
720     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
721         panic!(self.parse_sess.span_diagnostic.span_fatal(sp, msg));
722     }
723
724     /// Emit `msg` attached to `sp`, without immediately stopping
725     /// compilation.
726     ///
727     /// Compilation will be stopped in the near future (at the end of
728     /// the macro expansion phase).
729     pub fn span_err(&self, sp: Span, msg: &str) {
730         self.parse_sess.span_diagnostic.span_err(sp, msg);
731     }
732     pub fn span_warn(&self, sp: Span, msg: &str) {
733         self.parse_sess.span_diagnostic.span_warn(sp, msg);
734     }
735     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
736         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
737     }
738     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
739         self.parse_sess.span_diagnostic.span_bug(sp, msg);
740     }
741     pub fn span_note(&self, sp: Span, msg: &str) {
742         self.parse_sess.span_diagnostic.span_note(sp, msg);
743     }
744     pub fn span_help(&self, sp: Span, msg: &str) {
745         self.parse_sess.span_diagnostic.span_help(sp, msg);
746     }
747     pub fn fileline_help(&self, sp: Span, msg: &str) {
748         self.parse_sess.span_diagnostic.fileline_help(sp, msg);
749     }
750     pub fn bug(&self, msg: &str) -> ! {
751         self.parse_sess.span_diagnostic.handler().bug(msg);
752     }
753     pub fn trace_macros(&self) -> bool {
754         self.ecfg.trace_mac
755     }
756     pub fn set_trace_macros(&mut self, x: bool) {
757         self.ecfg.trace_mac = x
758     }
759     pub fn ident_of(&self, st: &str) -> ast::Ident {
760         str_to_ident(st)
761     }
762     pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
763         let mut v = Vec::new();
764         if let Some(s) = self.crate_root {
765             v.push(self.ident_of(s));
766         }
767         v.extend(components.iter().map(|s| self.ident_of(s)));
768         return v
769     }
770     pub fn name_of(&self, st: &str) -> ast::Name {
771         token::intern(st)
772     }
773 }
774
775 /// Extract a string literal from the macro expanded version of `expr`,
776 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
777 /// compilation on error, merely emits a non-fatal error and returns None.
778 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
779                       -> Option<(InternedString, ast::StrStyle)> {
780     // we want to be able to handle e.g. concat("foo", "bar")
781     let expr = cx.expander().fold_expr(expr);
782     match expr.node {
783         ast::ExprLit(ref l) => match l.node {
784             ast::LitStr(ref s, style) => return Some(((*s).clone(), style)),
785             _ => cx.span_err(l.span, err_msg)
786         },
787         _ => cx.span_err(expr.span, err_msg)
788     }
789     None
790 }
791
792 /// Non-fatally assert that `tts` is empty. Note that this function
793 /// returns even when `tts` is non-empty, macros that *need* to stop
794 /// compilation should call
795 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
796 /// done as rarely as possible).
797 pub fn check_zero_tts(cx: &ExtCtxt,
798                       sp: Span,
799                       tts: &[ast::TokenTree],
800                       name: &str) {
801     if !tts.is_empty() {
802         cx.span_err(sp, &format!("{} takes no arguments", name));
803     }
804 }
805
806 /// Extract the string literal from the first token of `tts`. If this
807 /// is not a string literal, emit an error and return None.
808 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
809                                sp: Span,
810                                tts: &[ast::TokenTree],
811                                name: &str)
812                                -> Option<String> {
813     let mut p = cx.new_parser_from_tts(tts);
814     if p.token == token::Eof {
815         cx.span_err(sp, &format!("{} takes 1 argument", name));
816         return None
817     }
818     let ret = cx.expander().fold_expr(p.parse_expr());
819     if p.token != token::Eof {
820         cx.span_err(sp, &format!("{} takes 1 argument", name));
821     }
822     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
823         s.to_string()
824     })
825 }
826
827 /// Extract comma-separated expressions from `tts`. If there is a
828 /// parsing error, emit a non-fatal error and return None.
829 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
830                           sp: Span,
831                           tts: &[ast::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
832     let mut p = cx.new_parser_from_tts(tts);
833     let mut es = Vec::new();
834     while p.token != token::Eof {
835         es.push(cx.expander().fold_expr(p.parse_expr()));
836         if panictry!(p.eat(&token::Comma)){
837             continue;
838         }
839         if p.token != token::Eof {
840             cx.span_err(sp, "expected token: `,`");
841             return None;
842         }
843     }
844     Some(es)
845 }
846
847 /// In order to have some notion of scoping for macros,
848 /// we want to implement the notion of a transformation
849 /// environment.
850 ///
851 /// This environment maps Names to SyntaxExtensions.
852 pub struct SyntaxEnv {
853     chain: Vec<MapChainFrame> ,
854 }
855
856 // impl question: how to implement it? Initially, the
857 // env will contain only macros, so it might be painful
858 // to add an empty frame for every context. Let's just
859 // get it working, first....
860
861 // NB! the mutability of the underlying maps means that
862 // if expansion is out-of-order, a deeper scope may be
863 // able to refer to a macro that was added to an enclosing
864 // scope lexically later than the deeper scope.
865
866 struct MapChainFrame {
867     info: BlockInfo,
868     map: HashMap<Name, Rc<SyntaxExtension>>,
869 }
870
871 impl SyntaxEnv {
872     fn new() -> SyntaxEnv {
873         let mut map = SyntaxEnv { chain: Vec::new() };
874         map.push_frame();
875         map
876     }
877
878     pub fn push_frame(&mut self) {
879         self.chain.push(MapChainFrame {
880             info: BlockInfo::new(),
881             map: HashMap::new(),
882         });
883     }
884
885     pub fn pop_frame(&mut self) {
886         assert!(self.chain.len() > 1, "too many pops on MapChain!");
887         self.chain.pop();
888     }
889
890     fn find_escape_frame<'a>(&'a mut self) -> &'a mut MapChainFrame {
891         for (i, frame) in self.chain.iter_mut().enumerate().rev() {
892             if !frame.info.macros_escape || i == 0 {
893                 return frame
894             }
895         }
896         unreachable!()
897     }
898
899     pub fn find(&self, k: Name) -> Option<Rc<SyntaxExtension>> {
900         for frame in self.chain.iter().rev() {
901             match frame.map.get(&k) {
902                 Some(v) => return Some(v.clone()),
903                 None => {}
904             }
905         }
906         None
907     }
908
909     pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
910         self.find_escape_frame().map.insert(k, Rc::new(v));
911     }
912
913     pub fn info<'a>(&'a mut self) -> &'a mut BlockInfo {
914         let last_chain_index = self.chain.len() - 1;
915         &mut self.chain[last_chain_index].info
916     }
917 }