]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Auto merge of #30624 - Ticki:specialization, r=alexcrichton
[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 errors::DiagnosticBuilder;
18 use ext;
19 use ext::expand;
20 use ext::tt::macro_rules;
21 use feature_gate::GatedCfgAttr;
22 use parse;
23 use parse::parser;
24 use parse::token;
25 use parse::token::{InternedString, intern, str_to_ident};
26 use ptr::P;
27 use util::small_vector::SmallVector;
28 use util::lev_distance::find_best_match_for_name;
29 use ext::mtwt;
30 use fold::Folder;
31
32 use std::collections::{HashMap, HashSet};
33 use std::rc::Rc;
34 use std::default::Default;
35
36
37 #[derive(Debug,Clone)]
38 pub enum Annotatable {
39     Item(P<ast::Item>),
40     TraitItem(P<ast::TraitItem>),
41     ImplItem(P<ast::ImplItem>),
42 }
43
44 impl Annotatable {
45     pub fn attrs(&self) -> &[ast::Attribute] {
46         match *self {
47             Annotatable::Item(ref i) => &i.attrs,
48             Annotatable::TraitItem(ref ti) => &ti.attrs,
49             Annotatable::ImplItem(ref ii) => &ii.attrs,
50         }
51     }
52
53     pub fn fold_attrs(self, attrs: Vec<ast::Attribute>) -> Annotatable {
54         match self {
55             Annotatable::Item(i) => Annotatable::Item(i.map(|i| ast::Item {
56                 attrs: attrs,
57                 ..i
58             })),
59             Annotatable::TraitItem(i) => Annotatable::TraitItem(i.map(|ti| {
60                 ast::TraitItem { attrs: attrs, ..ti }
61             })),
62             Annotatable::ImplItem(i) => Annotatable::ImplItem(i.map(|ii| {
63                 ast::ImplItem { attrs: attrs, ..ii }
64             })),
65         }
66     }
67
68     pub fn expect_item(self) -> P<ast::Item> {
69         match self {
70             Annotatable::Item(i) => i,
71             _ => panic!("expected Item")
72         }
73     }
74
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
78     {
79         match self {
80             Annotatable::Item(i) => Annotatable::Item(f(i)),
81             _ => or(self)
82         }
83     }
84
85     pub fn expect_trait_item(self) -> P<ast::TraitItem> {
86         match self {
87             Annotatable::TraitItem(i) => i,
88             _ => panic!("expected Item")
89         }
90     }
91
92     pub fn expect_impl_item(self) -> P<ast::ImplItem> {
93         match self {
94             Annotatable::ImplItem(i) => i,
95             _ => panic!("expected Item")
96         }
97     }
98 }
99
100 // A more flexible ItemDecorator.
101 pub trait MultiItemDecorator {
102     fn expand(&self,
103               ecx: &mut ExtCtxt,
104               sp: Span,
105               meta_item: &ast::MetaItem,
106               item: &Annotatable,
107               push: &mut FnMut(Annotatable));
108 }
109
110 impl<F> MultiItemDecorator for F
111     where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut FnMut(Annotatable))
112 {
113     fn expand(&self,
114               ecx: &mut ExtCtxt,
115               sp: Span,
116               meta_item: &ast::MetaItem,
117               item: &Annotatable,
118               push: &mut FnMut(Annotatable)) {
119         (*self)(ecx, sp, meta_item, item, push)
120     }
121 }
122
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 {
128     fn expand(&self,
129               ecx: &mut ExtCtxt,
130               span: Span,
131               meta_item: &ast::MetaItem,
132               item: Annotatable)
133               -> Annotatable;
134 }
135
136 impl<F> MultiItemModifier for F
137     where F: Fn(&mut ExtCtxt,
138                 Span,
139                 &ast::MetaItem,
140                 Annotatable) -> Annotatable
141 {
142     fn expand(&self,
143               ecx: &mut ExtCtxt,
144               span: Span,
145               meta_item: &ast::MetaItem,
146               item: Annotatable)
147               -> Annotatable {
148         (*self)(ecx, span, meta_item, item)
149     }
150 }
151
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,
156                    span: Span,
157                    token_tree: &[ast::TokenTree])
158                    -> Box<MacResult+'cx>;
159 }
160
161 pub type MacroExpanderFn =
162     for<'cx> fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>;
163
164 impl<F> TTMacroExpander for F
165     where F : for<'cx> Fn(&'cx mut ExtCtxt, Span, &[ast::TokenTree]) -> Box<MacResult+'cx>
166 {
167     fn expand<'cx>(&self,
168                    ecx: &'cx mut ExtCtxt,
169                    span: Span,
170                    token_tree: &[ast::TokenTree])
171                    -> Box<MacResult+'cx> {
172         (*self)(ecx, span, token_tree)
173     }
174 }
175
176 pub trait IdentMacroExpander {
177     fn expand<'cx>(&self,
178                    cx: &'cx mut ExtCtxt,
179                    sp: Span,
180                    ident: ast::Ident,
181                    token_tree: Vec<ast::TokenTree> )
182                    -> Box<MacResult+'cx>;
183 }
184
185 pub type IdentMacroExpanderFn =
186     for<'cx> fn(&'cx mut ExtCtxt, Span, ast::Ident, Vec<ast::TokenTree>) -> Box<MacResult+'cx>;
187
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>
191 {
192     fn expand<'cx>(&self,
193                    cx: &'cx mut ExtCtxt,
194                    sp: Span,
195                    ident: ast::Ident,
196                    token_tree: Vec<ast::TokenTree> )
197                    -> Box<MacResult+'cx>
198     {
199         (*self)(cx, sp, ident, token_tree)
200     }
201 }
202
203 // Use a macro because forwarding to a simple function has type system issues
204 macro_rules! make_stmts_default {
205     ($me:expr) => {
206         $me.make_expr().map(|e| {
207             SmallVector::one(P(codemap::respan(
208                 e.span, ast::StmtExpr(e, ast::DUMMY_NODE_ID))))
209         })
210     }
211 }
212
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>> {
218         None
219     }
220     /// Create zero or more items.
221     fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
222         None
223     }
224
225     /// Create zero or more impl items.
226     fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
227         None
228     }
229
230     /// Create a pattern.
231     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
232         None
233     }
234
235     /// Create zero or more statements.
236     ///
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)
241     }
242
243     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
244         None
245     }
246 }
247
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.
252         #[derive(Default)]
253         pub struct MacEager {
254             $(
255                 pub $fld: Option<$t>,
256             )*
257         }
258
259         impl MacEager {
260             $(
261                 pub fn $fld(v: $t) -> Box<MacResult> {
262                     Box::new(MacEager {
263                         $fld: Some(v),
264                         ..Default::default()
265                     })
266                 }
267             )*
268         }
269     }
270 }
271
272 make_MacEager! {
273     expr: P<ast::Expr>,
274     pat: P<ast::Pat>,
275     items: SmallVector<P<ast::Item>>,
276     impl_items: SmallVector<P<ast::ImplItem>>,
277     stmts: SmallVector<P<ast::Stmt>>,
278     ty: P<ast::Ty>,
279 }
280
281 impl MacResult for MacEager {
282     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
283         self.expr
284     }
285
286     fn make_items(self: Box<Self>) -> Option<SmallVector<P<ast::Item>>> {
287         self.items
288     }
289
290     fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> {
291         self.impl_items
292     }
293
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),
297             _ => self.stmts,
298         }
299     }
300
301     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
302         if let Some(p) = self.pat {
303             return Some(p);
304         }
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,
309                     span: e.span,
310                     node: ast::PatLit(e),
311                 }));
312             }
313         }
314         None
315     }
316
317     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
318         self.ty
319     }
320 }
321
322 /// Fill-in macro expansion result, to allow compilation to continue
323 /// after hitting errors.
324 #[derive(Copy, Clone)]
325 pub struct DummyResult {
326     expr_only: bool,
327     span: Span
328 }
329
330 impl DummyResult {
331     /// Create a default MacResult that can be anything.
332     ///
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 })
337     }
338
339     /// Create a default MacResult that can only be an expression.
340     ///
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 })
346     }
347
348     /// A plain dummy expression.
349     pub fn raw_expr(sp: Span) -> P<ast::Expr> {
350         P(ast::Expr {
351             id: ast::DUMMY_NODE_ID,
352             node: ast::ExprLit(P(codemap::respan(sp, ast::LitBool(false)))),
353             span: sp,
354             attrs: None,
355         })
356     }
357
358     /// A plain dummy pattern.
359     pub fn raw_pat(sp: Span) -> ast::Pat {
360         ast::Pat {
361             id: ast::DUMMY_NODE_ID,
362             node: ast::PatWild,
363             span: sp,
364         }
365     }
366
367     pub fn raw_ty(sp: Span) -> P<ast::Ty> {
368         P(ast::Ty {
369             id: ast::DUMMY_NODE_ID,
370             node: ast::TyInfer,
371             span: sp
372         })
373     }
374 }
375
376 impl MacResult for DummyResult {
377     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
378         Some(DummyResult::raw_expr(self.span))
379     }
380
381     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
382         Some(P(DummyResult::raw_pat(self.span)))
383     }
384
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() ?
387         if self.expr_only {
388             None
389         } else {
390             Some(SmallVector::zero())
391         }
392     }
393
394     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::ImplItem>>> {
395         if self.expr_only {
396             None
397         } else {
398             Some(SmallVector::zero())
399         }
400     }
401
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)))))
407     }
408 }
409
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
413     /// based upon it.
414     ///
415     /// `#[derive(...)]` is a `MultiItemDecorator`.
416     MultiDecorator(Box<MultiItemDecorator + 'static>),
417
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>),
421
422     /// A normal, function-like syntax extension.
423     ///
424     /// `bytes!` is a `NormalTT`.
425     ///
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),
429
430     /// A function-like syntax extension that has an extra ident before
431     /// the block.
432     ///
433     IdentTT(Box<IdentMacroExpander + 'static>, Option<Span>, bool),
434
435     /// Represents `macro_rules!` itself.
436     MacroRulesTT,
437 }
438
439 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
440
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,
446 }
447
448 impl BlockInfo {
449     pub fn new() -> BlockInfo {
450         BlockInfo {
451             macros_escape: false,
452             pending_renames: Vec::new(),
453         }
454     }
455 }
456
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>)
460                                         -> SyntaxEnv {
461     // utility function to simplify creating NormalTT syntax extensions
462     fn builtin_normal_expander(f: MacroExpanderFn) -> SyntaxExtension {
463         NormalTT(Box::new(f), None, false)
464     }
465
466     let mut syntax_expanders = SyntaxEnv::new();
467     syntax_expanders.insert(intern("macro_rules"), MacroRulesTT);
468
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));
510     }
511
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));
536     syntax_expanders
537 }
538
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>,
549
550     pub mod_path: Vec<ast::Ident> ,
551     pub exported_macros: Vec<ast::MacroDef>,
552
553     pub syntax_env: SyntaxEnv,
554     pub recursion_count: usize,
555 }
556
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);
562         ExtCtxt {
563             parse_sess: parse_sess,
564             cfg: cfg,
565             backtrace: NO_EXPANSION,
566             mod_path: Vec::new(),
567             ecfg: ecfg,
568             crate_root: None,
569             feature_gated_cfgs: feature_gated_cfgs,
570             exported_macros: Vec::new(),
571             syntax_env: env,
572             recursion_count: 0,
573         }
574     }
575
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)
579     }
580
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())
584     }
585
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")
593         })
594     }
595     pub fn backtrace(&self) -> ExpnId { self.backtrace }
596
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;
601         loop {
602             match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) {
603                 None => break,
604                 Some(cs) => {
605                     call_site = Some(cs);
606                     expn_id = cs.expn_id;
607                 }
608             }
609         }
610         call_site.expect("missing expansion backtrace")
611     }
612
613     /// Returns span for the macro which originally caused the current expansion to happen.
614     ///
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;
619         loop {
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
624                         return None;
625                     }
626                     expn_id = i.call_site.expn_id;
627                     last_macro = Some(i.call_site);
628                     return Some(());
629                 })
630             }).is_none() {
631                 break
632             }
633         }
634         last_macro.expect("missing expansion backtrace")
635     }
636
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());
643         return v;
644     }
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 `{}`",
650                                     ei.callee.name()));
651         }
652
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,
657             callee: ei.callee
658         });
659     }
660     pub fn bt_pop(&mut self) {
661         match self.backtrace {
662             NO_EXPANSION => self.bug("tried to pop without a push"),
663             expn_id => {
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)
667                 });
668             }
669         }
670     }
671
672     pub fn insert_macro(&mut self, def: ast::MacroDef) {
673         if def.export {
674             self.exported_macros.push(def.clone());
675         }
676         if def.use_locally {
677             let ext = macro_rules::compile(self, &def);
678             self.syntax_env.insert(def.ident.name, ext);
679         }
680     }
681
682     pub fn struct_span_warn(&self,
683                             sp: Span,
684                             msg: &str)
685                             -> DiagnosticBuilder<'a> {
686         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
687     }
688     pub fn struct_span_err(&self,
689                            sp: Span,
690                            msg: &str)
691                            -> DiagnosticBuilder<'a> {
692         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
693     }
694     pub fn struct_span_fatal(&self,
695                              sp: Span,
696                              msg: &str)
697                              -> DiagnosticBuilder<'a> {
698         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
699     }
700
701     /// Emit `msg` attached to `sp`, and stop compilation immediately.
702     ///
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));
714     }
715
716     /// Emit `msg` attached to `sp`, without immediately stopping
717     /// compilation.
718     ///
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);
723     }
724     pub fn span_warn(&self, sp: Span, msg: &str) {
725         self.parse_sess.span_diagnostic.span_warn(sp, msg);
726     }
727     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
728         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
729     }
730     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
731         self.parse_sess.span_diagnostic.span_bug(sp, msg);
732     }
733     pub fn bug(&self, msg: &str) -> ! {
734         self.parse_sess.span_diagnostic.bug(msg);
735     }
736     pub fn trace_macros(&self) -> bool {
737         self.ecfg.trace_mac
738     }
739     pub fn set_trace_macros(&mut self, x: bool) {
740         self.ecfg.trace_mac = x
741     }
742     pub fn ident_of(&self, st: &str) -> ast::Ident {
743         str_to_ident(st)
744     }
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));
749         }
750         v.extend(components.iter().map(|s| self.ident_of(s)));
751         return v
752     }
753     pub fn name_of(&self, st: &str) -> ast::Name {
754         token::intern(st)
755     }
756
757     pub fn suggest_macro_name(&mut self,
758                               name: &str,
759                               span: Span,
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));
764         }
765     }
766 }
767
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);
775     match expr.node {
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)
779         },
780         _ => cx.span_err(expr.span, err_msg)
781     }
782     None
783 }
784
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,
791                       sp: Span,
792                       tts: &[ast::TokenTree],
793                       name: &str) {
794     if !tts.is_empty() {
795         cx.span_err(sp, &format!("{} takes no arguments", name));
796     }
797 }
798
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,
802                                sp: Span,
803                                tts: &[ast::TokenTree],
804                                name: &str)
805                                -> Option<String> {
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));
809         return None
810     }
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));
814     }
815     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
816         s.to_string()
817     })
818 }
819
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,
823                           sp: Span,
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 p.eat(&token::Comma) {
830             continue;
831         }
832         if p.token != token::Eof {
833             cx.span_err(sp, "expected token: `,`");
834             return None;
835         }
836     }
837     Some(es)
838 }
839
840 /// In order to have some notion of scoping for macros,
841 /// we want to implement the notion of a transformation
842 /// environment.
843 ///
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>,
850 }
851
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....
856
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.
861
862 struct MapChainFrame {
863     info: BlockInfo,
864     map: HashMap<Name, Rc<SyntaxExtension>>,
865 }
866
867 impl SyntaxEnv {
868     fn new() -> SyntaxEnv {
869         let mut map = SyntaxEnv { chain: Vec::new() , names: HashSet::new()};
870         map.push_frame();
871         map
872     }
873
874     pub fn push_frame(&mut self) {
875         self.chain.push(MapChainFrame {
876             info: BlockInfo::new(),
877             map: HashMap::new(),
878         });
879     }
880
881     pub fn pop_frame(&mut self) {
882         assert!(self.chain.len() > 1, "too many pops on MapChain!");
883         self.chain.pop();
884     }
885
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 {
889                 return frame
890             }
891         }
892         unreachable!()
893     }
894
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()),
899                 None => {}
900             }
901         }
902         None
903     }
904
905     pub fn insert(&mut self, k: Name, v: SyntaxExtension) {
906         if let NormalTT(..) = v {
907             self.names.insert(k);
908         }
909         self.find_escape_frame().map.insert(k, Rc::new(v));
910     }
911
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
915     }
916 }