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