]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/quote.rs
prefer "FIXME" to "TODO".
[rust.git] / src / libsyntax / ext / quote.rs
1 // Copyright 2012 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 codemap::Span;
13 use ext::base::ExtCtxt;
14 use ext::base;
15 use ext::build::AstBuilder;
16 use parse::token::*;
17 use parse::token;
18 use ptr::P;
19
20 ///  Quasiquoting works via token trees.
21 ///
22 ///  This is registered as a set of expression syntax extension called quote!
23 ///  that lifts its argument token-tree to an AST representing the
24 ///  construction of the same token tree, with token::SubstNt interpreted
25 ///  as antiquotes (splices).
26
27 pub mod rt {
28     use ast;
29     use codemap::Spanned;
30     use ext::base::ExtCtxt;
31     use parse::token;
32     use parse;
33     use print::pprust;
34     use ptr::P;
35
36     use ast::{TokenTree, Generics, Expr};
37
38     pub use parse::new_parser_from_tts;
39     pub use codemap::{BytePos, Span, dummy_spanned};
40
41     pub trait ToTokens {
42         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> ;
43     }
44
45     impl ToTokens for TokenTree {
46         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
47             vec!(self.clone())
48         }
49     }
50
51     impl<T: ToTokens> ToTokens for Vec<T> {
52         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
53             let a = self.iter().flat_map(|t| t.to_tokens(cx).into_iter());
54             FromIterator::from_iter(a)
55         }
56     }
57
58     impl<T: ToTokens> ToTokens for Spanned<T> {
59         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
60             // FIXME: use the span?
61             self.node.to_tokens(cx)
62         }
63     }
64
65     impl<T: ToTokens> ToTokens for Option<T> {
66         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
67             match self {
68                 &Some(ref t) => t.to_tokens(cx),
69                 &None => Vec::new(),
70             }
71         }
72     }
73
74     /* Should be (when bugs in default methods are fixed):
75
76     trait ToSource : ToTokens {
77         // Takes a thing and generates a string containing rust code for it.
78         pub fn to_source() -> String;
79
80         // If you can make source, you can definitely make tokens.
81         pub fn to_tokens(cx: &ExtCtxt) -> ~[TokenTree] {
82             cx.parse_tts(self.to_source())
83         }
84     }
85
86     */
87
88     // FIXME: Move this trait to pprust and get rid of *_to_str?
89     pub trait ToSource for Sized? {
90         // Takes a thing and generates a string containing rust code for it.
91         fn to_source(&self) -> String;
92     }
93
94     // FIXME (Issue #16472): This should go away after ToToken impls
95     // are revised to go directly to token-trees.
96     trait ToSourceWithHygiene for Sized? : ToSource {
97         // Takes a thing and generates a string containing rust code
98         // for it, encoding Idents as special byte sequences to
99         // maintain hygiene across serialization and deserialization.
100         fn to_source_with_hygiene(&self) -> String;
101     }
102
103     macro_rules! impl_to_source(
104         (P<$t:ty>, $pp:ident) => (
105             impl ToSource for P<$t> {
106                 fn to_source(&self) -> String {
107                     pprust::$pp(&**self)
108                 }
109             }
110             impl ToSourceWithHygiene for P<$t> {
111                 fn to_source_with_hygiene(&self) -> String {
112                     pprust::with_hygiene::$pp(&**self)
113                 }
114             }
115         );
116         ($t:ty, $pp:ident) => (
117             impl ToSource for $t {
118                 fn to_source(&self) -> String {
119                     pprust::$pp(self)
120                 }
121             }
122             impl ToSourceWithHygiene for $t {
123                 fn to_source_with_hygiene(&self) -> String {
124                     pprust::with_hygiene::$pp(self)
125                 }
126             }
127         );
128     )
129
130     fn slice_to_source<'a, T: ToSource>(sep: &'static str, xs: &'a [T]) -> String {
131         xs.iter()
132             .map(|i| i.to_source())
133             .collect::<Vec<String>>()
134             .connect(sep)
135             .to_string()
136     }
137
138     fn slice_to_source_with_hygiene<'a, T: ToSourceWithHygiene>(
139         sep: &'static str, xs: &'a [T]) -> String {
140         xs.iter()
141             .map(|i| i.to_source_with_hygiene())
142             .collect::<Vec<String>>()
143             .connect(sep)
144             .to_string()
145     }
146
147     macro_rules! impl_to_source_slice(
148         ($t:ty, $sep:expr) => (
149             impl ToSource for [$t] {
150                 fn to_source(&self) -> String {
151                     slice_to_source($sep, self)
152                 }
153             }
154
155             impl ToSourceWithHygiene for [$t] {
156                 fn to_source_with_hygiene(&self) -> String {
157                     slice_to_source_with_hygiene($sep, self)
158                 }
159             }
160         )
161     )
162
163     impl ToSource for ast::Ident {
164         fn to_source(&self) -> String {
165             token::get_ident(*self).get().to_string()
166         }
167     }
168
169     impl ToSourceWithHygiene for ast::Ident {
170         fn to_source_with_hygiene(&self) -> String {
171             self.encode_with_hygiene()
172         }
173     }
174
175     impl_to_source!(ast::Ty, ty_to_string)
176     impl_to_source!(ast::Block, block_to_string)
177     impl_to_source!(ast::Arg, arg_to_string)
178     impl_to_source!(Generics, generics_to_string)
179     impl_to_source!(P<ast::Item>, item_to_string)
180     impl_to_source!(P<ast::Method>, method_to_string)
181     impl_to_source!(P<ast::Stmt>, stmt_to_string)
182     impl_to_source!(P<ast::Expr>, expr_to_string)
183     impl_to_source!(P<ast::Pat>, pat_to_string)
184     impl_to_source!(ast::Arm, arm_to_string)
185     impl_to_source_slice!(ast::Ty, ", ")
186     impl_to_source_slice!(P<ast::Item>, "\n\n")
187
188     impl ToSource for ast::Attribute_ {
189         fn to_source(&self) -> String {
190             pprust::attribute_to_string(&dummy_spanned(self.clone()))
191         }
192     }
193     impl ToSourceWithHygiene for ast::Attribute_ {
194         fn to_source_with_hygiene(&self) -> String {
195             self.to_source()
196         }
197     }
198
199     impl ToSource for str {
200         fn to_source(&self) -> String {
201             let lit = dummy_spanned(ast::LitStr(
202                     token::intern_and_get_ident(self), ast::CookedStr));
203             pprust::lit_to_string(&lit)
204         }
205     }
206     impl ToSourceWithHygiene for str {
207         fn to_source_with_hygiene(&self) -> String {
208             self.to_source()
209         }
210     }
211
212     impl ToSource for () {
213         fn to_source(&self) -> String {
214             "()".to_string()
215         }
216     }
217     impl ToSourceWithHygiene for () {
218         fn to_source_with_hygiene(&self) -> String {
219             self.to_source()
220         }
221     }
222
223     impl ToSource for bool {
224         fn to_source(&self) -> String {
225             let lit = dummy_spanned(ast::LitBool(*self));
226             pprust::lit_to_string(&lit)
227         }
228     }
229     impl ToSourceWithHygiene for bool {
230         fn to_source_with_hygiene(&self) -> String {
231             self.to_source()
232         }
233     }
234
235     impl ToSource for char {
236         fn to_source(&self) -> String {
237             let lit = dummy_spanned(ast::LitChar(*self));
238             pprust::lit_to_string(&lit)
239         }
240     }
241     impl ToSourceWithHygiene for char {
242         fn to_source_with_hygiene(&self) -> String {
243             self.to_source()
244         }
245     }
246
247     macro_rules! impl_to_source_int(
248         (signed, $t:ty, $tag:ident) => (
249             impl ToSource for $t {
250                 fn to_source(&self) -> String {
251                     let lit = ast::LitInt(*self as u64, ast::SignedIntLit(ast::$tag,
252                                                                           ast::Sign::new(*self)));
253                     pprust::lit_to_string(&dummy_spanned(lit))
254                 }
255             }
256             impl ToSourceWithHygiene for $t {
257                 fn to_source_with_hygiene(&self) -> String {
258                     self.to_source()
259                 }
260             }
261         );
262         (unsigned, $t:ty, $tag:ident) => (
263             impl ToSource for $t {
264                 fn to_source(&self) -> String {
265                     let lit = ast::LitInt(*self as u64, ast::UnsignedIntLit(ast::$tag));
266                     pprust::lit_to_string(&dummy_spanned(lit))
267                 }
268             }
269             impl ToSourceWithHygiene for $t {
270                 fn to_source_with_hygiene(&self) -> String {
271                     self.to_source()
272                 }
273             }
274         );
275     )
276
277     impl_to_source_int!(signed, int, TyI)
278     impl_to_source_int!(signed, i8,  TyI8)
279     impl_to_source_int!(signed, i16, TyI16)
280     impl_to_source_int!(signed, i32, TyI32)
281     impl_to_source_int!(signed, i64, TyI64)
282
283     impl_to_source_int!(unsigned, uint, TyU)
284     impl_to_source_int!(unsigned, u8,   TyU8)
285     impl_to_source_int!(unsigned, u16,  TyU16)
286     impl_to_source_int!(unsigned, u32,  TyU32)
287     impl_to_source_int!(unsigned, u64,  TyU64)
288
289     // Alas ... we write these out instead. All redundant.
290
291     macro_rules! impl_to_tokens(
292         ($t:ty) => (
293             impl ToTokens for $t {
294                 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
295                     cx.parse_tts_with_hygiene(self.to_source_with_hygiene())
296                 }
297             }
298         )
299     )
300
301     macro_rules! impl_to_tokens_lifetime(
302         ($t:ty) => (
303             impl<'a> ToTokens for $t {
304                 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
305                     cx.parse_tts_with_hygiene(self.to_source_with_hygiene())
306                 }
307             }
308         )
309     )
310
311     impl_to_tokens!(ast::Ident)
312     impl_to_tokens!(P<ast::Item>)
313     impl_to_tokens!(P<ast::Pat>)
314     impl_to_tokens!(ast::Arm)
315     impl_to_tokens!(P<ast::Method>)
316     impl_to_tokens_lifetime!(&'a [P<ast::Item>])
317     impl_to_tokens!(ast::Ty)
318     impl_to_tokens_lifetime!(&'a [ast::Ty])
319     impl_to_tokens!(Generics)
320     impl_to_tokens!(P<ast::Stmt>)
321     impl_to_tokens!(P<ast::Expr>)
322     impl_to_tokens!(ast::Block)
323     impl_to_tokens!(ast::Arg)
324     impl_to_tokens!(ast::Attribute_)
325     impl_to_tokens_lifetime!(&'a str)
326     impl_to_tokens!(())
327     impl_to_tokens!(char)
328     impl_to_tokens!(bool)
329     impl_to_tokens!(int)
330     impl_to_tokens!(i8)
331     impl_to_tokens!(i16)
332     impl_to_tokens!(i32)
333     impl_to_tokens!(i64)
334     impl_to_tokens!(uint)
335     impl_to_tokens!(u8)
336     impl_to_tokens!(u16)
337     impl_to_tokens!(u32)
338     impl_to_tokens!(u64)
339
340     pub trait ExtParseUtils {
341         fn parse_item(&self, s: String) -> P<ast::Item>;
342         fn parse_expr(&self, s: String) -> P<ast::Expr>;
343         fn parse_stmt(&self, s: String) -> P<ast::Stmt>;
344         fn parse_tts(&self, s: String) -> Vec<ast::TokenTree>;
345     }
346
347     trait ExtParseUtilsWithHygiene {
348         // FIXME (Issue #16472): This should go away after ToToken impls
349         // are revised to go directly to token-trees.
350         fn parse_tts_with_hygiene(&self, s: String) -> Vec<ast::TokenTree>;
351     }
352
353     impl<'a> ExtParseUtils for ExtCtxt<'a> {
354
355         fn parse_item(&self, s: String) -> P<ast::Item> {
356             let res = parse::parse_item_from_source_str(
357                 "<quote expansion>".to_string(),
358                 s,
359                 self.cfg(),
360                 self.parse_sess());
361             match res {
362                 Some(ast) => ast,
363                 None => {
364                     error!("parse error");
365                     panic!()
366                 }
367             }
368         }
369
370         fn parse_stmt(&self, s: String) -> P<ast::Stmt> {
371             parse::parse_stmt_from_source_str("<quote expansion>".to_string(),
372                                               s,
373                                               self.cfg(),
374                                               Vec::new(),
375                                               self.parse_sess())
376         }
377
378         fn parse_expr(&self, s: String) -> P<ast::Expr> {
379             parse::parse_expr_from_source_str("<quote expansion>".to_string(),
380                                               s,
381                                               self.cfg(),
382                                               self.parse_sess())
383         }
384
385         fn parse_tts(&self, s: String) -> Vec<ast::TokenTree> {
386             parse::parse_tts_from_source_str("<quote expansion>".to_string(),
387                                              s,
388                                              self.cfg(),
389                                              self.parse_sess())
390         }
391     }
392
393     impl<'a> ExtParseUtilsWithHygiene for ExtCtxt<'a> {
394
395         fn parse_tts_with_hygiene(&self, s: String) -> Vec<ast::TokenTree> {
396             use parse::with_hygiene::parse_tts_from_source_str;
397             parse_tts_from_source_str("<quote expansion>".to_string(),
398                                       s,
399                                       self.cfg(),
400                                       self.parse_sess())
401         }
402
403     }
404
405 }
406
407 pub fn expand_quote_tokens<'cx>(cx: &'cx mut ExtCtxt,
408                                 sp: Span,
409                                 tts: &[ast::TokenTree])
410                                 -> Box<base::MacResult+'cx> {
411     let (cx_expr, expr) = expand_tts(cx, sp, tts);
412     let expanded = expand_wrapper(cx, sp, cx_expr, expr);
413     base::MacExpr::new(expanded)
414 }
415
416 pub fn expand_quote_expr<'cx>(cx: &'cx mut ExtCtxt,
417                               sp: Span,
418                               tts: &[ast::TokenTree])
419                               -> Box<base::MacResult+'cx> {
420     let expanded = expand_parse_call(cx, sp, "parse_expr", Vec::new(), tts);
421     base::MacExpr::new(expanded)
422 }
423
424 pub fn expand_quote_item<'cx>(cx: &mut ExtCtxt,
425                               sp: Span,
426                               tts: &[ast::TokenTree])
427                               -> Box<base::MacResult+'cx> {
428     let expanded = expand_parse_call(cx, sp, "parse_item_with_outer_attributes",
429                                     vec!(), tts);
430     base::MacExpr::new(expanded)
431 }
432
433 pub fn expand_quote_pat<'cx>(cx: &'cx mut ExtCtxt,
434                              sp: Span,
435                              tts: &[ast::TokenTree])
436                              -> Box<base::MacResult+'cx> {
437     let expanded = expand_parse_call(cx, sp, "parse_pat", vec!(), tts);
438     base::MacExpr::new(expanded)
439 }
440
441 pub fn expand_quote_arm(cx: &mut ExtCtxt,
442                         sp: Span,
443                         tts: &[ast::TokenTree])
444                         -> Box<base::MacResult+'static> {
445     let expanded = expand_parse_call(cx, sp, "parse_arm", vec!(), tts);
446     base::MacExpr::new(expanded)
447 }
448
449 pub fn expand_quote_ty(cx: &mut ExtCtxt,
450                        sp: Span,
451                        tts: &[ast::TokenTree])
452                        -> Box<base::MacResult+'static> {
453     let e_param_colons = cx.expr_lit(sp, ast::LitBool(false));
454     let expanded = expand_parse_call(cx, sp, "parse_ty",
455                                      vec!(e_param_colons), tts);
456     base::MacExpr::new(expanded)
457 }
458
459 pub fn expand_quote_method(cx: &mut ExtCtxt,
460                            sp: Span,
461                            tts: &[ast::TokenTree])
462                            -> Box<base::MacResult+'static> {
463     let expanded = expand_parse_call(cx, sp, "parse_method_with_outer_attributes",
464                                      vec!(), tts);
465     base::MacExpr::new(expanded)
466 }
467
468 pub fn expand_quote_stmt(cx: &mut ExtCtxt,
469                          sp: Span,
470                          tts: &[ast::TokenTree])
471                          -> Box<base::MacResult+'static> {
472     let e_attrs = cx.expr_vec_ng(sp);
473     let expanded = expand_parse_call(cx, sp, "parse_stmt",
474                                     vec!(e_attrs), tts);
475     base::MacExpr::new(expanded)
476 }
477
478 fn ids_ext(strs: Vec<String> ) -> Vec<ast::Ident> {
479     strs.iter().map(|str| str_to_ident((*str).as_slice())).collect()
480 }
481
482 fn id_ext(str: &str) -> ast::Ident {
483     str_to_ident(str)
484 }
485
486 // Lift an ident to the expr that evaluates to that ident.
487 fn mk_ident(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> {
488     let e_str = cx.expr_str(sp, token::get_ident(ident));
489     cx.expr_method_call(sp,
490                         cx.expr_ident(sp, id_ext("ext_cx")),
491                         id_ext("ident_of"),
492                         vec!(e_str))
493 }
494
495 // Lift a name to the expr that evaluates to that name
496 fn mk_name(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> {
497     let e_str = cx.expr_str(sp, token::get_ident(ident));
498     cx.expr_method_call(sp,
499                         cx.expr_ident(sp, id_ext("ext_cx")),
500                         id_ext("name_of"),
501                         vec!(e_str))
502 }
503
504 fn mk_ast_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> {
505     let idents = vec!(id_ext("syntax"), id_ext("ast"), id_ext(name));
506     cx.expr_path(cx.path_global(sp, idents))
507 }
508
509 fn mk_token_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> {
510     let idents = vec!(id_ext("syntax"), id_ext("parse"), id_ext("token"), id_ext(name));
511     cx.expr_path(cx.path_global(sp, idents))
512 }
513
514 fn mk_binop(cx: &ExtCtxt, sp: Span, bop: token::BinOpToken) -> P<ast::Expr> {
515     let name = match bop {
516         token::Plus     => "Plus",
517         token::Minus    => "Minus",
518         token::Star     => "Star",
519         token::Slash    => "Slash",
520         token::Percent  => "Percent",
521         token::Caret    => "Caret",
522         token::And      => "And",
523         token::Or       => "Or",
524         token::Shl      => "Shl",
525         token::Shr      => "Shr"
526     };
527     mk_token_path(cx, sp, name)
528 }
529
530 fn mk_delim(cx: &ExtCtxt, sp: Span, delim: token::DelimToken) -> P<ast::Expr> {
531     let name = match delim {
532         token::Paren     => "Paren",
533         token::Bracket   => "Bracket",
534         token::Brace     => "Brace",
535     };
536     mk_token_path(cx, sp, name)
537 }
538
539 #[allow(non_upper_case_globals)]
540 fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
541     macro_rules! mk_lit {
542         ($name: expr, $suffix: expr, $($args: expr),*) => {{
543             let inner = cx.expr_call(sp, mk_token_path(cx, sp, $name), vec![$($args),*]);
544             let suffix = match $suffix {
545                 Some(name) => cx.expr_some(sp, mk_name(cx, sp, ast::Ident::new(name))),
546                 None => cx.expr_none(sp)
547             };
548             cx.expr_call(sp, mk_token_path(cx, sp, "Literal"), vec![inner, suffix])
549         }}
550     }
551     match *tok {
552         token::BinOp(binop) => {
553             return cx.expr_call(sp, mk_token_path(cx, sp, "BinOp"), vec!(mk_binop(cx, sp, binop)));
554         }
555         token::BinOpEq(binop) => {
556             return cx.expr_call(sp, mk_token_path(cx, sp, "BinOpEq"),
557                                 vec!(mk_binop(cx, sp, binop)));
558         }
559
560         token::OpenDelim(delim) => {
561             return cx.expr_call(sp, mk_token_path(cx, sp, "OpenDelim"),
562                                 vec![mk_delim(cx, sp, delim)]);
563         }
564         token::CloseDelim(delim) => {
565             return cx.expr_call(sp, mk_token_path(cx, sp, "CloseDelim"),
566                                 vec![mk_delim(cx, sp, delim)]);
567         }
568
569         token::Literal(token::Byte(i), suf) => {
570             let e_byte = mk_name(cx, sp, i.ident());
571             return mk_lit!("Byte", suf, e_byte);
572         }
573
574         token::Literal(token::Char(i), suf) => {
575             let e_char = mk_name(cx, sp, i.ident());
576             return mk_lit!("Char", suf, e_char);
577         }
578
579         token::Literal(token::Integer(i), suf) => {
580             let e_int = mk_name(cx, sp, i.ident());
581             return mk_lit!("Integer", suf, e_int);
582         }
583
584         token::Literal(token::Float(fident), suf) => {
585             let e_fident = mk_name(cx, sp, fident.ident());
586             return mk_lit!("Float", suf, e_fident);
587         }
588
589         token::Literal(token::Str_(ident), suf) => {
590             return mk_lit!("Str_", suf, mk_name(cx, sp, ident.ident()))
591         }
592
593         token::Literal(token::StrRaw(ident, n), suf) => {
594             return mk_lit!("StrRaw", suf, mk_name(cx, sp, ident.ident()), cx.expr_uint(sp, n))
595         }
596
597         token::Ident(ident, style) => {
598             return cx.expr_call(sp,
599                                 mk_token_path(cx, sp, "Ident"),
600                                 vec![mk_ident(cx, sp, ident),
601                                      match style {
602                                         ModName => mk_token_path(cx, sp, "ModName"),
603                                         Plain   => mk_token_path(cx, sp, "Plain"),
604                                      }]);
605         }
606
607         token::Lifetime(ident) => {
608             return cx.expr_call(sp,
609                                 mk_token_path(cx, sp, "Lifetime"),
610                                 vec!(mk_ident(cx, sp, ident)));
611         }
612
613         token::DocComment(ident) => {
614             return cx.expr_call(sp,
615                                 mk_token_path(cx, sp, "DocComment"),
616                                 vec!(mk_name(cx, sp, ident.ident())));
617         }
618
619         token::Interpolated(_) => panic!("quote! with interpolated token"),
620
621         _ => ()
622     }
623
624     let name = match *tok {
625         token::Eq           => "Eq",
626         token::Lt           => "Lt",
627         token::Le           => "Le",
628         token::EqEq         => "EqEq",
629         token::Ne           => "Ne",
630         token::Ge           => "Ge",
631         token::Gt           => "Gt",
632         token::AndAnd       => "AndAnd",
633         token::OrOr         => "OrOr",
634         token::Not          => "Not",
635         token::Tilde        => "Tilde",
636         token::At           => "At",
637         token::Dot          => "Dot",
638         token::DotDot       => "DotDot",
639         token::Comma        => "Comma",
640         token::Semi         => "Semi",
641         token::Colon        => "Colon",
642         token::ModSep       => "ModSep",
643         token::RArrow       => "RArrow",
644         token::LArrow       => "LArrow",
645         token::FatArrow     => "FatArrow",
646         token::Pound        => "Pound",
647         token::Dollar       => "Dollar",
648         token::Underscore   => "Underscore",
649         token::Eof          => "Eof",
650         _                   => panic!(),
651     };
652     mk_token_path(cx, sp, name)
653 }
654
655 fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec<P<ast::Stmt>> {
656     match *tt {
657         ast::TtToken(sp, SubstNt(ident, _)) => {
658             // tt.extend($ident.to_tokens(ext_cx).into_iter())
659
660             let e_to_toks =
661                 cx.expr_method_call(sp,
662                                     cx.expr_ident(sp, ident),
663                                     id_ext("to_tokens"),
664                                     vec!(cx.expr_ident(sp, id_ext("ext_cx"))));
665             let e_to_toks =
666                 cx.expr_method_call(sp, e_to_toks, id_ext("into_iter"), vec![]);
667
668             let e_push =
669                 cx.expr_method_call(sp,
670                                     cx.expr_ident(sp, id_ext("tt")),
671                                     id_ext("extend"),
672                                     vec!(e_to_toks));
673
674             vec!(cx.stmt_expr(e_push))
675         }
676         ref tt @ ast::TtToken(_, MatchNt(..)) => {
677             let mut seq = vec![];
678             for i in range(0, tt.len()) {
679                 seq.push(tt.get_tt(i));
680             }
681             mk_tts(cx, seq.as_slice())
682         }
683         ast::TtToken(sp, ref tok) => {
684             let e_sp = cx.expr_ident(sp, id_ext("_sp"));
685             let e_tok = cx.expr_call(sp,
686                                      mk_ast_path(cx, sp, "TtToken"),
687                                      vec!(e_sp, mk_token(cx, sp, tok)));
688             let e_push =
689                 cx.expr_method_call(sp,
690                                     cx.expr_ident(sp, id_ext("tt")),
691                                     id_ext("push"),
692                                     vec!(e_tok));
693             vec!(cx.stmt_expr(e_push))
694         },
695         ast::TtDelimited(_, ref delimed) => {
696             mk_tt(cx, &delimed.open_tt()).into_iter()
697                 .chain(delimed.tts.iter().flat_map(|tt| mk_tt(cx, tt).into_iter()))
698                 .chain(mk_tt(cx, &delimed.close_tt()).into_iter())
699                 .collect()
700         },
701         ast::TtSequence(..) => panic!("TtSequence in quote!"),
702     }
703 }
704
705 fn mk_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> Vec<P<ast::Stmt>> {
706     let mut ss = Vec::new();
707     for tt in tts.iter() {
708         ss.extend(mk_tt(cx, tt).into_iter());
709     }
710     ss
711 }
712
713 fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
714               -> (P<ast::Expr>, P<ast::Expr>) {
715     // NB: It appears that the main parser loses its mind if we consider
716     // $foo as a TtNonterminal during the main parse, so we have to re-parse
717     // under quote_depth > 0. This is silly and should go away; the _guess_ is
718     // it has to do with transition away from supporting old-style macros, so
719     // try removing it when enough of them are gone.
720
721     let mut p = cx.new_parser_from_tts(tts);
722     p.quote_depth += 1u;
723
724     let cx_expr = p.parse_expr();
725     if !p.eat(&token::Comma) {
726         p.fatal("expected token `,`");
727     }
728
729     let tts = p.parse_all_token_trees();
730     p.abort_if_errors();
731
732     // We also bind a single value, sp, to ext_cx.call_site()
733     //
734     // This causes every span in a token-tree quote to be attributed to the
735     // call site of the extension using the quote. We can't really do much
736     // better since the source of the quote may well be in a library that
737     // was not even parsed by this compilation run, that the user has no
738     // source code for (eg. in libsyntax, which they're just _using_).
739     //
740     // The old quasiquoter had an elaborate mechanism for denoting input
741     // file locations from which quotes originated; unfortunately this
742     // relied on feeding the source string of the quote back into the
743     // compiler (which we don't really want to do) and, in any case, only
744     // pushed the problem a very small step further back: an error
745     // resulting from a parse of the resulting quote is still attributed to
746     // the site the string literal occurred, which was in a source file
747     // _other_ than the one the user has control over. For example, an
748     // error in a quote from the protocol compiler, invoked in user code
749     // using macro_rules! for example, will be attributed to the macro_rules.rs
750     // file in libsyntax, which the user might not even have source to (unless
751     // they happen to have a compiler on hand). Over all, the phase distinction
752     // just makes quotes "hard to attribute". Possibly this could be fixed
753     // by recreating some of the original qq machinery in the tt regime
754     // (pushing fake FileMaps onto the parser to account for original sites
755     // of quotes, for example) but at this point it seems not likely to be
756     // worth the hassle.
757
758     let e_sp = cx.expr_method_call(sp,
759                                    cx.expr_ident(sp, id_ext("ext_cx")),
760                                    id_ext("call_site"),
761                                    Vec::new());
762
763     let stmt_let_sp = cx.stmt_let(sp, false,
764                                   id_ext("_sp"),
765                                   e_sp);
766
767     let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
768
769     let mut vector = vec!(stmt_let_sp, stmt_let_tt);
770     vector.extend(mk_tts(cx, tts.as_slice()).into_iter());
771     let block = cx.expr_block(
772         cx.block_all(sp,
773                      Vec::new(),
774                      vector,
775                      Some(cx.expr_ident(sp, id_ext("tt")))));
776
777     (cx_expr, block)
778 }
779
780 fn expand_wrapper(cx: &ExtCtxt,
781                   sp: Span,
782                   cx_expr: P<ast::Expr>,
783                   expr: P<ast::Expr>) -> P<ast::Expr> {
784     let uses = [
785         &["syntax", "ext", "quote", "rt"],
786     ].iter().map(|path| {
787         let path = path.iter().map(|s| s.to_string()).collect();
788         cx.view_use_glob(sp, ast::Inherited, ids_ext(path))
789     }).collect();
790
791     // Explicitly borrow to avoid moving from the invoker (#16992)
792     let cx_expr_borrow = cx.expr_addr_of(sp, cx.expr_deref(sp, cx_expr));
793     let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr_borrow);
794
795     cx.expr_block(cx.block_all(sp, uses, vec!(stmt_let_ext_cx), Some(expr)))
796 }
797
798 fn expand_parse_call(cx: &ExtCtxt,
799                      sp: Span,
800                      parse_method: &str,
801                      arg_exprs: Vec<P<ast::Expr>> ,
802                      tts: &[ast::TokenTree]) -> P<ast::Expr> {
803     let (cx_expr, tts_expr) = expand_tts(cx, sp, tts);
804
805     let cfg_call = || cx.expr_method_call(
806         sp, cx.expr_ident(sp, id_ext("ext_cx")),
807         id_ext("cfg"), Vec::new());
808
809     let parse_sess_call = || cx.expr_method_call(
810         sp, cx.expr_ident(sp, id_ext("ext_cx")),
811         id_ext("parse_sess"), Vec::new());
812
813     let new_parser_call =
814         cx.expr_call(sp,
815                      cx.expr_ident(sp, id_ext("new_parser_from_tts")),
816                      vec!(parse_sess_call(), cfg_call(), tts_expr));
817
818     let expr = cx.expr_method_call(sp, new_parser_call, id_ext(parse_method),
819                                    arg_exprs);
820
821     expand_wrapper(cx, sp, cx_expr, expr)
822 }