]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/quote.rs
Rollup merge of #40696 - cramertj:remove-unused-adt-def-code, r=petrochenkov
[rust.git] / src / libsyntax / ext / quote.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 use ast::{self, Arg, Arm, Block, Expr, Item, Pat, Stmt, Ty};
12 use syntax_pos::Span;
13 use ext::base::ExtCtxt;
14 use ext::base;
15 use ext::build::AstBuilder;
16 use parse::parser::{Parser, PathStyle};
17 use parse::token;
18 use ptr::P;
19 use tokenstream::{TokenStream, TokenTree};
20
21
22 /// Quasiquoting works via token trees.
23 ///
24 /// This is registered as a set of expression syntax extension called quote!
25 /// that lifts its argument token-tree to an AST representing the
26 /// construction of the same token tree, with token::SubstNt interpreted
27 /// as antiquotes (splices).
28
29 pub mod rt {
30     use ast;
31     use codemap::Spanned;
32     use ext::base::ExtCtxt;
33     use parse::{self, token, classify};
34     use ptr::P;
35     use std::rc::Rc;
36     use symbol::Symbol;
37
38     use tokenstream::{self, TokenTree, TokenStream};
39
40     pub use parse::new_parser_from_tts;
41     pub use syntax_pos::{BytePos, Span, DUMMY_SP};
42     pub use codemap::{dummy_spanned};
43
44     pub trait ToTokens {
45         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree>;
46     }
47
48     impl ToTokens for TokenTree {
49         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
50             vec![self.clone()]
51         }
52     }
53
54     impl<T: ToTokens> ToTokens for Vec<T> {
55         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
56             self.iter().flat_map(|t| t.to_tokens(cx)).collect()
57         }
58     }
59
60     impl<T: ToTokens> ToTokens for Spanned<T> {
61         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
62             // FIXME: use the span?
63             self.node.to_tokens(cx)
64         }
65     }
66
67     impl<T: ToTokens> ToTokens for Option<T> {
68         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
69             match *self {
70                 Some(ref t) => t.to_tokens(cx),
71                 None => Vec::new(),
72             }
73         }
74     }
75
76     impl ToTokens for ast::Ident {
77         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
78             vec![TokenTree::Token(DUMMY_SP, token::Ident(*self))]
79         }
80     }
81
82     impl ToTokens for ast::Path {
83         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
84             let nt = token::NtPath(self.clone());
85             vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))]
86         }
87     }
88
89     impl ToTokens for ast::Ty {
90         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
91             let nt = token::NtTy(P(self.clone()));
92             vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]
93         }
94     }
95
96     impl ToTokens for ast::Block {
97         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
98             let nt = token::NtBlock(P(self.clone()));
99             vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]
100         }
101     }
102
103     impl ToTokens for ast::Generics {
104         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
105             let nt = token::NtGenerics(self.clone());
106             vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))]
107         }
108     }
109
110     impl ToTokens for ast::WhereClause {
111         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
112             let nt = token::NtWhereClause(self.clone());
113             vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))]
114         }
115     }
116
117     impl ToTokens for P<ast::Item> {
118         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
119             let nt = token::NtItem(self.clone());
120             vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]
121         }
122     }
123
124     impl ToTokens for ast::ImplItem {
125         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
126             let nt = token::NtImplItem(self.clone());
127             vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]
128         }
129     }
130
131     impl ToTokens for P<ast::ImplItem> {
132         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
133             let nt = token::NtImplItem((**self).clone());
134             vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]
135         }
136     }
137
138     impl ToTokens for ast::TraitItem {
139         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
140             let nt = token::NtTraitItem(self.clone());
141             vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]
142         }
143     }
144
145     impl ToTokens for ast::Stmt {
146         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
147             let nt = token::NtStmt(self.clone());
148             let mut tts = vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))];
149
150             // Some statements require a trailing semicolon.
151             if classify::stmt_ends_with_semi(&self.node) {
152                 tts.push(TokenTree::Token(self.span, token::Semi));
153             }
154
155             tts
156         }
157     }
158
159     impl ToTokens for P<ast::Expr> {
160         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
161             let nt = token::NtExpr(self.clone());
162             vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]
163         }
164     }
165
166     impl ToTokens for P<ast::Pat> {
167         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
168             let nt = token::NtPat(self.clone());
169             vec![TokenTree::Token(self.span, token::Interpolated(Rc::new(nt)))]
170         }
171     }
172
173     impl ToTokens for ast::Arm {
174         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
175             let nt = token::NtArm(self.clone());
176             vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))]
177         }
178     }
179
180     impl ToTokens for ast::Arg {
181         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
182             let nt = token::NtArg(self.clone());
183             vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))]
184         }
185     }
186
187     impl ToTokens for P<ast::Block> {
188         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
189             let nt = token::NtBlock(self.clone());
190             vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))]
191         }
192     }
193
194     macro_rules! impl_to_tokens_slice {
195         ($t: ty, $sep: expr) => {
196             impl ToTokens for [$t] {
197                 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
198                     let mut v = vec![];
199                     for (i, x) in self.iter().enumerate() {
200                         if i > 0 {
201                             v.extend_from_slice(&$sep);
202                         }
203                         v.extend(x.to_tokens(cx));
204                     }
205                     v
206                 }
207             }
208         };
209     }
210
211     impl_to_tokens_slice! { ast::Ty, [TokenTree::Token(DUMMY_SP, token::Comma)] }
212     impl_to_tokens_slice! { P<ast::Item>, [] }
213     impl_to_tokens_slice! { ast::Arg, [TokenTree::Token(DUMMY_SP, token::Comma)] }
214
215     impl ToTokens for ast::MetaItem {
216         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
217             let nt = token::NtMeta(self.clone());
218             vec![TokenTree::Token(DUMMY_SP, token::Interpolated(Rc::new(nt)))]
219         }
220     }
221
222     impl ToTokens for ast::Attribute {
223         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
224             let mut r = vec![];
225             // FIXME: The spans could be better
226             r.push(TokenTree::Token(self.span, token::Pound));
227             if self.style == ast::AttrStyle::Inner {
228                 r.push(TokenTree::Token(self.span, token::Not));
229             }
230             let mut inner = Vec::new();
231             for (i, segment) in self.path.segments.iter().enumerate() {
232                 if i > 0 {
233                     inner.push(TokenTree::Token(self.span, token::Colon).into());
234                 }
235                 inner.push(TokenTree::Token(self.span, token::Ident(segment.identifier)).into());
236             }
237             inner.push(self.tokens.clone());
238
239             r.push(TokenTree::Delimited(self.span, tokenstream::Delimited {
240                 delim: token::Bracket, tts: TokenStream::concat(inner).into()
241             }));
242             r
243         }
244     }
245
246     impl ToTokens for str {
247         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
248             let lit = ast::LitKind::Str(Symbol::intern(self), ast::StrStyle::Cooked);
249             dummy_spanned(lit).to_tokens(cx)
250         }
251     }
252
253     impl ToTokens for () {
254         fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
255             vec![TokenTree::Delimited(DUMMY_SP, tokenstream::Delimited {
256                 delim: token::Paren,
257                 tts: TokenStream::empty().into(),
258             })]
259         }
260     }
261
262     impl ToTokens for ast::Lit {
263         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
264             // FIXME: This is wrong
265             P(ast::Expr {
266                 id: ast::DUMMY_NODE_ID,
267                 node: ast::ExprKind::Lit(P(self.clone())),
268                 span: DUMMY_SP,
269                 attrs: ast::ThinVec::new(),
270             }).to_tokens(cx)
271         }
272     }
273
274     impl ToTokens for bool {
275         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
276             dummy_spanned(ast::LitKind::Bool(*self)).to_tokens(cx)
277         }
278     }
279
280     impl ToTokens for char {
281         fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
282             dummy_spanned(ast::LitKind::Char(*self)).to_tokens(cx)
283         }
284     }
285
286     macro_rules! impl_to_tokens_int {
287         (signed, $t:ty, $tag:expr) => (
288             impl ToTokens for $t {
289                 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
290                     let val = if *self < 0 {
291                         -self
292                     } else {
293                         *self
294                     };
295                     let lit = ast::LitKind::Int(val as u128, ast::LitIntType::Signed($tag));
296                     let lit = P(ast::Expr {
297                         id: ast::DUMMY_NODE_ID,
298                         node: ast::ExprKind::Lit(P(dummy_spanned(lit))),
299                         span: DUMMY_SP,
300                         attrs: ast::ThinVec::new(),
301                     });
302                     if *self >= 0 {
303                         return lit.to_tokens(cx);
304                     }
305                     P(ast::Expr {
306                         id: ast::DUMMY_NODE_ID,
307                         node: ast::ExprKind::Unary(ast::UnOp::Neg, lit),
308                         span: DUMMY_SP,
309                         attrs: ast::ThinVec::new(),
310                     }).to_tokens(cx)
311                 }
312             }
313         );
314         (unsigned, $t:ty, $tag:expr) => (
315             impl ToTokens for $t {
316                 fn to_tokens(&self, cx: &ExtCtxt) -> Vec<TokenTree> {
317                     let lit = ast::LitKind::Int(*self as u128, ast::LitIntType::Unsigned($tag));
318                     dummy_spanned(lit).to_tokens(cx)
319                 }
320             }
321         );
322     }
323
324     impl_to_tokens_int! { signed, isize, ast::IntTy::Is }
325     impl_to_tokens_int! { signed, i8,  ast::IntTy::I8 }
326     impl_to_tokens_int! { signed, i16, ast::IntTy::I16 }
327     impl_to_tokens_int! { signed, i32, ast::IntTy::I32 }
328     impl_to_tokens_int! { signed, i64, ast::IntTy::I64 }
329
330     impl_to_tokens_int! { unsigned, usize, ast::UintTy::Us }
331     impl_to_tokens_int! { unsigned, u8,   ast::UintTy::U8 }
332     impl_to_tokens_int! { unsigned, u16,  ast::UintTy::U16 }
333     impl_to_tokens_int! { unsigned, u32,  ast::UintTy::U32 }
334     impl_to_tokens_int! { unsigned, u64,  ast::UintTy::U64 }
335
336     pub trait ExtParseUtils {
337         fn parse_item(&self, s: String) -> P<ast::Item>;
338         fn parse_expr(&self, s: String) -> P<ast::Expr>;
339         fn parse_stmt(&self, s: String) -> ast::Stmt;
340         fn parse_tts(&self, s: String) -> Vec<TokenTree>;
341     }
342
343     impl<'a> ExtParseUtils for ExtCtxt<'a> {
344         fn parse_item(&self, s: String) -> P<ast::Item> {
345             panictry!(parse::parse_item_from_source_str(
346                 "<quote expansion>".to_string(),
347                 s,
348                 self.parse_sess())).expect("parse error")
349         }
350
351         fn parse_stmt(&self, s: String) -> ast::Stmt {
352             panictry!(parse::parse_stmt_from_source_str(
353                 "<quote expansion>".to_string(),
354                 s,
355                 self.parse_sess())).expect("parse error")
356         }
357
358         fn parse_expr(&self, s: String) -> P<ast::Expr> {
359             panictry!(parse::parse_expr_from_source_str(
360                 "<quote expansion>".to_string(),
361                 s,
362                 self.parse_sess()))
363         }
364
365         fn parse_tts(&self, s: String) -> Vec<TokenTree> {
366             let source_name = "<quote expansion>".to_owned();
367             parse::parse_stream_from_source_str(source_name, s, self.parse_sess())
368                 .into_trees().collect()
369         }
370     }
371 }
372
373 // Replaces `Token::OpenDelim .. Token::CloseDelim` with `TokenTree::Delimited(..)`.
374 pub fn unflatten(tts: Vec<TokenTree>) -> Vec<TokenTree> {
375     use tokenstream::Delimited;
376
377     let mut results = Vec::new();
378     let mut result = Vec::new();
379     for tree in tts {
380         match tree {
381             TokenTree::Token(_, token::OpenDelim(..)) => {
382                 results.push(::std::mem::replace(&mut result, Vec::new()));
383             }
384             TokenTree::Token(span, token::CloseDelim(delim)) => {
385                 let tree = TokenTree::Delimited(span, Delimited {
386                     delim: delim,
387                     tts: result.into_iter().map(TokenStream::from).collect::<TokenStream>().into(),
388                 });
389                 result = results.pop().unwrap();
390                 result.push(tree);
391             }
392             tree @ _ => result.push(tree),
393         }
394     }
395     result
396 }
397
398 // These panicking parsing functions are used by the quote_*!() syntax extensions,
399 // but shouldn't be used otherwise.
400 pub fn parse_expr_panic(parser: &mut Parser) -> P<Expr> {
401     panictry!(parser.parse_expr())
402 }
403
404 pub fn parse_item_panic(parser: &mut Parser) -> Option<P<Item>> {
405     panictry!(parser.parse_item())
406 }
407
408 pub fn parse_pat_panic(parser: &mut Parser) -> P<Pat> {
409     panictry!(parser.parse_pat())
410 }
411
412 pub fn parse_arm_panic(parser: &mut Parser) -> Arm {
413     panictry!(parser.parse_arm())
414 }
415
416 pub fn parse_ty_panic(parser: &mut Parser) -> P<Ty> {
417     panictry!(parser.parse_ty())
418 }
419
420 pub fn parse_stmt_panic(parser: &mut Parser) -> Option<Stmt> {
421     panictry!(parser.parse_stmt())
422 }
423
424 pub fn parse_attribute_panic(parser: &mut Parser, permit_inner: bool) -> ast::Attribute {
425     panictry!(parser.parse_attribute(permit_inner))
426 }
427
428 pub fn parse_arg_panic(parser: &mut Parser) -> Arg {
429     panictry!(parser.parse_arg())
430 }
431
432 pub fn parse_block_panic(parser: &mut Parser) -> P<Block> {
433     panictry!(parser.parse_block())
434 }
435
436 pub fn parse_meta_item_panic(parser: &mut Parser) -> ast::MetaItem {
437     panictry!(parser.parse_meta_item())
438 }
439
440 pub fn parse_path_panic(parser: &mut Parser, mode: PathStyle) -> ast::Path {
441     panictry!(parser.parse_path(mode))
442 }
443
444 pub fn expand_quote_tokens<'cx>(cx: &'cx mut ExtCtxt,
445                                 sp: Span,
446                                 tts: &[TokenTree])
447                                 -> Box<base::MacResult+'cx> {
448     let (cx_expr, expr) = expand_tts(cx, sp, tts);
449     let expanded = expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]]);
450     base::MacEager::expr(expanded)
451 }
452
453 pub fn expand_quote_expr<'cx>(cx: &'cx mut ExtCtxt,
454                               sp: Span,
455                               tts: &[TokenTree])
456                               -> Box<base::MacResult+'cx> {
457     let expanded = expand_parse_call(cx, sp, "parse_expr_panic", vec![], tts);
458     base::MacEager::expr(expanded)
459 }
460
461 pub fn expand_quote_item<'cx>(cx: &'cx mut ExtCtxt,
462                               sp: Span,
463                               tts: &[TokenTree])
464                               -> Box<base::MacResult+'cx> {
465     let expanded = expand_parse_call(cx, sp, "parse_item_panic", vec![], tts);
466     base::MacEager::expr(expanded)
467 }
468
469 pub fn expand_quote_pat<'cx>(cx: &'cx mut ExtCtxt,
470                              sp: Span,
471                              tts: &[TokenTree])
472                              -> Box<base::MacResult+'cx> {
473     let expanded = expand_parse_call(cx, sp, "parse_pat_panic", vec![], tts);
474     base::MacEager::expr(expanded)
475 }
476
477 pub fn expand_quote_arm(cx: &mut ExtCtxt,
478                         sp: Span,
479                         tts: &[TokenTree])
480                         -> Box<base::MacResult+'static> {
481     let expanded = expand_parse_call(cx, sp, "parse_arm_panic", vec![], tts);
482     base::MacEager::expr(expanded)
483 }
484
485 pub fn expand_quote_ty(cx: &mut ExtCtxt,
486                        sp: Span,
487                        tts: &[TokenTree])
488                        -> Box<base::MacResult+'static> {
489     let expanded = expand_parse_call(cx, sp, "parse_ty_panic", vec![], tts);
490     base::MacEager::expr(expanded)
491 }
492
493 pub fn expand_quote_stmt(cx: &mut ExtCtxt,
494                          sp: Span,
495                          tts: &[TokenTree])
496                          -> Box<base::MacResult+'static> {
497     let expanded = expand_parse_call(cx, sp, "parse_stmt_panic", vec![], tts);
498     base::MacEager::expr(expanded)
499 }
500
501 pub fn expand_quote_attr(cx: &mut ExtCtxt,
502                          sp: Span,
503                          tts: &[TokenTree])
504                          -> Box<base::MacResult+'static> {
505     let expanded = expand_parse_call(cx, sp, "parse_attribute_panic",
506                                     vec![cx.expr_bool(sp, true)], tts);
507
508     base::MacEager::expr(expanded)
509 }
510
511 pub fn expand_quote_arg(cx: &mut ExtCtxt,
512                         sp: Span,
513                         tts: &[TokenTree])
514                         -> Box<base::MacResult+'static> {
515     let expanded = expand_parse_call(cx, sp, "parse_arg_panic", vec![], tts);
516     base::MacEager::expr(expanded)
517 }
518
519 pub fn expand_quote_block(cx: &mut ExtCtxt,
520                         sp: Span,
521                         tts: &[TokenTree])
522                         -> Box<base::MacResult+'static> {
523     let expanded = expand_parse_call(cx, sp, "parse_block_panic", vec![], tts);
524     base::MacEager::expr(expanded)
525 }
526
527 pub fn expand_quote_meta_item(cx: &mut ExtCtxt,
528                         sp: Span,
529                         tts: &[TokenTree])
530                         -> Box<base::MacResult+'static> {
531     let expanded = expand_parse_call(cx, sp, "parse_meta_item_panic", vec![], tts);
532     base::MacEager::expr(expanded)
533 }
534
535 pub fn expand_quote_path(cx: &mut ExtCtxt,
536                         sp: Span,
537                         tts: &[TokenTree])
538                         -> Box<base::MacResult+'static> {
539     let mode = mk_parser_path(cx, sp, &["PathStyle", "Type"]);
540     let expanded = expand_parse_call(cx, sp, "parse_path_panic", vec![mode], tts);
541     base::MacEager::expr(expanded)
542 }
543
544 fn ids_ext(strs: Vec<String>) -> Vec<ast::Ident> {
545     strs.iter().map(|s| ast::Ident::from_str(s)).collect()
546 }
547
548 fn id_ext(s: &str) -> ast::Ident {
549     ast::Ident::from_str(s)
550 }
551
552 // Lift an ident to the expr that evaluates to that ident.
553 fn mk_ident(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> {
554     let e_str = cx.expr_str(sp, ident.name);
555     cx.expr_method_call(sp,
556                         cx.expr_ident(sp, id_ext("ext_cx")),
557                         id_ext("ident_of"),
558                         vec![e_str])
559 }
560
561 // Lift a name to the expr that evaluates to that name
562 fn mk_name(cx: &ExtCtxt, sp: Span, ident: ast::Ident) -> P<ast::Expr> {
563     let e_str = cx.expr_str(sp, ident.name);
564     cx.expr_method_call(sp,
565                         cx.expr_ident(sp, id_ext("ext_cx")),
566                         id_ext("name_of"),
567                         vec![e_str])
568 }
569
570 fn mk_tt_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> {
571     let idents = vec![id_ext("syntax"), id_ext("tokenstream"), id_ext("TokenTree"), id_ext(name)];
572     cx.expr_path(cx.path_global(sp, idents))
573 }
574
575 fn mk_token_path(cx: &ExtCtxt, sp: Span, name: &str) -> P<ast::Expr> {
576     let idents = vec![id_ext("syntax"), id_ext("parse"), id_ext("token"), id_ext(name)];
577     cx.expr_path(cx.path_global(sp, idents))
578 }
579
580 fn mk_parser_path(cx: &ExtCtxt, sp: Span, names: &[&str]) -> P<ast::Expr> {
581     let mut idents = vec![id_ext("syntax"), id_ext("parse"), id_ext("parser")];
582     idents.extend(names.iter().cloned().map(id_ext));
583     cx.expr_path(cx.path_global(sp, idents))
584 }
585
586 fn mk_binop(cx: &ExtCtxt, sp: Span, bop: token::BinOpToken) -> P<ast::Expr> {
587     let name = match bop {
588         token::Plus     => "Plus",
589         token::Minus    => "Minus",
590         token::Star     => "Star",
591         token::Slash    => "Slash",
592         token::Percent  => "Percent",
593         token::Caret    => "Caret",
594         token::And      => "And",
595         token::Or       => "Or",
596         token::Shl      => "Shl",
597         token::Shr      => "Shr"
598     };
599     mk_token_path(cx, sp, name)
600 }
601
602 fn mk_delim(cx: &ExtCtxt, sp: Span, delim: token::DelimToken) -> P<ast::Expr> {
603     let name = match delim {
604         token::Paren   => "Paren",
605         token::Bracket => "Bracket",
606         token::Brace   => "Brace",
607         token::NoDelim => "NoDelim",
608     };
609     mk_token_path(cx, sp, name)
610 }
611
612 #[allow(non_upper_case_globals)]
613 fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
614     macro_rules! mk_lit {
615         ($name: expr, $suffix: expr, $($args: expr),*) => {{
616             let inner = cx.expr_call(sp, mk_token_path(cx, sp, $name), vec![$($args),*]);
617             let suffix = match $suffix {
618                 Some(name) => cx.expr_some(sp, mk_name(cx, sp, ast::Ident::with_empty_ctxt(name))),
619                 None => cx.expr_none(sp)
620             };
621             cx.expr_call(sp, mk_token_path(cx, sp, "Literal"), vec![inner, suffix])
622         }}
623     }
624     match *tok {
625         token::BinOp(binop) => {
626             return cx.expr_call(sp, mk_token_path(cx, sp, "BinOp"), vec![mk_binop(cx, sp, binop)]);
627         }
628         token::BinOpEq(binop) => {
629             return cx.expr_call(sp, mk_token_path(cx, sp, "BinOpEq"),
630                                 vec![mk_binop(cx, sp, binop)]);
631         }
632
633         token::OpenDelim(delim) => {
634             return cx.expr_call(sp, mk_token_path(cx, sp, "OpenDelim"),
635                                 vec![mk_delim(cx, sp, delim)]);
636         }
637         token::CloseDelim(delim) => {
638             return cx.expr_call(sp, mk_token_path(cx, sp, "CloseDelim"),
639                                 vec![mk_delim(cx, sp, delim)]);
640         }
641
642         token::Literal(token::Byte(i), suf) => {
643             let e_byte = mk_name(cx, sp, ast::Ident::with_empty_ctxt(i));
644             return mk_lit!("Byte", suf, e_byte);
645         }
646
647         token::Literal(token::Char(i), suf) => {
648             let e_char = mk_name(cx, sp, ast::Ident::with_empty_ctxt(i));
649             return mk_lit!("Char", suf, e_char);
650         }
651
652         token::Literal(token::Integer(i), suf) => {
653             let e_int = mk_name(cx, sp, ast::Ident::with_empty_ctxt(i));
654             return mk_lit!("Integer", suf, e_int);
655         }
656
657         token::Literal(token::Float(fident), suf) => {
658             let e_fident = mk_name(cx, sp, ast::Ident::with_empty_ctxt(fident));
659             return mk_lit!("Float", suf, e_fident);
660         }
661
662         token::Literal(token::Str_(ident), suf) => {
663             return mk_lit!("Str_", suf, mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident)))
664         }
665
666         token::Literal(token::StrRaw(ident, n), suf) => {
667             return mk_lit!("StrRaw", suf, mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident)),
668                            cx.expr_usize(sp, n))
669         }
670
671         token::Ident(ident) => {
672             return cx.expr_call(sp,
673                                 mk_token_path(cx, sp, "Ident"),
674                                 vec![mk_ident(cx, sp, ident)]);
675         }
676
677         token::Lifetime(ident) => {
678             return cx.expr_call(sp,
679                                 mk_token_path(cx, sp, "Lifetime"),
680                                 vec![mk_ident(cx, sp, ident)]);
681         }
682
683         token::DocComment(ident) => {
684             return cx.expr_call(sp,
685                                 mk_token_path(cx, sp, "DocComment"),
686                                 vec![mk_name(cx, sp, ast::Ident::with_empty_ctxt(ident))]);
687         }
688
689         token::Interpolated(_) => panic!("quote! with interpolated token"),
690
691         _ => ()
692     }
693
694     let name = match *tok {
695         token::Eq           => "Eq",
696         token::Lt           => "Lt",
697         token::Le           => "Le",
698         token::EqEq         => "EqEq",
699         token::Ne           => "Ne",
700         token::Ge           => "Ge",
701         token::Gt           => "Gt",
702         token::AndAnd       => "AndAnd",
703         token::OrOr         => "OrOr",
704         token::Not          => "Not",
705         token::Tilde        => "Tilde",
706         token::At           => "At",
707         token::Dot          => "Dot",
708         token::DotDot       => "DotDot",
709         token::Comma        => "Comma",
710         token::Semi         => "Semi",
711         token::Colon        => "Colon",
712         token::ModSep       => "ModSep",
713         token::RArrow       => "RArrow",
714         token::LArrow       => "LArrow",
715         token::FatArrow     => "FatArrow",
716         token::Pound        => "Pound",
717         token::Dollar       => "Dollar",
718         token::Question     => "Question",
719         token::Underscore   => "Underscore",
720         token::Eof          => "Eof",
721         _                   => panic!("unhandled token in quote!"),
722     };
723     mk_token_path(cx, sp, name)
724 }
725
726 fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, quoted: bool) -> Vec<ast::Stmt> {
727     match *tt {
728         TokenTree::Token(sp, token::Ident(ident)) if quoted => {
729             // tt.extend($ident.to_tokens(ext_cx))
730
731             let e_to_toks =
732                 cx.expr_method_call(sp,
733                                     cx.expr_ident(sp, ident),
734                                     id_ext("to_tokens"),
735                                     vec![cx.expr_ident(sp, id_ext("ext_cx"))]);
736             let e_to_toks =
737                 cx.expr_method_call(sp, e_to_toks, id_ext("into_iter"), vec![]);
738
739             let e_push =
740                 cx.expr_method_call(sp,
741                                     cx.expr_ident(sp, id_ext("tt")),
742                                     id_ext("extend"),
743                                     vec![e_to_toks]);
744
745             vec![cx.stmt_expr(e_push)]
746         }
747         TokenTree::Token(sp, ref tok) => {
748             let e_sp = cx.expr_ident(sp, id_ext("_sp"));
749             let e_tok = cx.expr_call(sp,
750                                      mk_tt_path(cx, sp, "Token"),
751                                      vec![e_sp, expr_mk_token(cx, sp, tok)]);
752             let e_push =
753                 cx.expr_method_call(sp,
754                                     cx.expr_ident(sp, id_ext("tt")),
755                                     id_ext("push"),
756                                     vec![e_tok]);
757             vec![cx.stmt_expr(e_push)]
758         },
759         TokenTree::Delimited(span, ref delimed) => {
760             let mut stmts = statements_mk_tt(cx, &delimed.open_tt(span), false);
761             stmts.extend(statements_mk_tts(cx, delimed.stream()));
762             stmts.extend(statements_mk_tt(cx, &delimed.close_tt(span), false));
763             stmts
764         }
765     }
766 }
767
768 fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[TokenTree])
769                             -> (P<ast::Expr>, Vec<TokenTree>) {
770     let mut p = cx.new_parser_from_tts(tts);
771
772     let cx_expr = panictry!(p.parse_expr());
773     if !p.eat(&token::Comma) {
774         let _ = p.diagnostic().fatal("expected token `,`");
775     }
776
777     let tts = panictry!(p.parse_all_token_trees());
778     p.abort_if_errors();
779
780     (cx_expr, tts)
781 }
782
783 fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<ast::Stmt> {
784     // We also bind a single value, sp, to ext_cx.call_site()
785     //
786     // This causes every span in a token-tree quote to be attributed to the
787     // call site of the extension using the quote. We can't really do much
788     // better since the source of the quote may well be in a library that
789     // was not even parsed by this compilation run, that the user has no
790     // source code for (eg. in libsyntax, which they're just _using_).
791     //
792     // The old quasiquoter had an elaborate mechanism for denoting input
793     // file locations from which quotes originated; unfortunately this
794     // relied on feeding the source string of the quote back into the
795     // compiler (which we don't really want to do) and, in any case, only
796     // pushed the problem a very small step further back: an error
797     // resulting from a parse of the resulting quote is still attributed to
798     // the site the string literal occurred, which was in a source file
799     // _other_ than the one the user has control over. For example, an
800     // error in a quote from the protocol compiler, invoked in user code
801     // using macro_rules! for example, will be attributed to the macro_rules.rs
802     // file in libsyntax, which the user might not even have source to (unless
803     // they happen to have a compiler on hand). Over all, the phase distinction
804     // just makes quotes "hard to attribute". Possibly this could be fixed
805     // by recreating some of the original qq machinery in the tt regime
806     // (pushing fake FileMaps onto the parser to account for original sites
807     // of quotes, for example) but at this point it seems not likely to be
808     // worth the hassle.
809
810     let e_sp = cx.expr_method_call(sp,
811                                    cx.expr_ident(sp, id_ext("ext_cx")),
812                                    id_ext("call_site"),
813                                    Vec::new());
814
815     let stmt_let_sp = cx.stmt_let(sp, false,
816                                   id_ext("_sp"),
817                                   e_sp);
818
819     let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp));
820
821     vec![stmt_let_sp, stmt_let_tt]
822 }
823
824 fn statements_mk_tts(cx: &ExtCtxt, tts: TokenStream) -> Vec<ast::Stmt> {
825     let mut ss = Vec::new();
826     let mut quoted = false;
827     for tt in tts.into_trees() {
828         quoted = match tt {
829             TokenTree::Token(_, token::Dollar) if !quoted => true,
830             _ => {
831                 ss.extend(statements_mk_tt(cx, &tt, quoted));
832                 false
833             }
834         }
835     }
836     ss
837 }
838
839 fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[TokenTree]) -> (P<ast::Expr>, P<ast::Expr>) {
840     let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
841
842     let mut vector = mk_stmts_let(cx, sp);
843     vector.extend(statements_mk_tts(cx, tts.iter().cloned().collect()));
844     vector.push(cx.stmt_expr(cx.expr_ident(sp, id_ext("tt"))));
845     let block = cx.expr_block(cx.block(sp, vector));
846     let unflatten = vec![id_ext("syntax"), id_ext("ext"), id_ext("quote"), id_ext("unflatten")];
847
848     (cx_expr, cx.expr_call_global(sp, unflatten, vec![block]))
849 }
850
851 fn expand_wrapper(cx: &ExtCtxt,
852                   sp: Span,
853                   cx_expr: P<ast::Expr>,
854                   expr: P<ast::Expr>,
855                   imports: &[&[&str]]) -> P<ast::Expr> {
856     // Explicitly borrow to avoid moving from the invoker (#16992)
857     let cx_expr_borrow = cx.expr_addr_of(sp, cx.expr_deref(sp, cx_expr));
858     let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr_borrow);
859
860     let mut stmts = imports.iter().map(|path| {
861         // make item: `use ...;`
862         let path = path.iter().map(|s| s.to_string()).collect();
863         cx.stmt_item(sp, cx.item_use_glob(sp, ast::Visibility::Inherited, ids_ext(path)))
864     }).chain(Some(stmt_let_ext_cx)).collect::<Vec<_>>();
865     stmts.push(cx.stmt_expr(expr));
866
867     cx.expr_block(cx.block(sp, stmts))
868 }
869
870 fn expand_parse_call(cx: &ExtCtxt,
871                      sp: Span,
872                      parse_method: &str,
873                      arg_exprs: Vec<P<ast::Expr>> ,
874                      tts: &[TokenTree]) -> P<ast::Expr> {
875     let (cx_expr, tts_expr) = expand_tts(cx, sp, tts);
876
877     let parse_sess_call = || cx.expr_method_call(
878         sp, cx.expr_ident(sp, id_ext("ext_cx")),
879         id_ext("parse_sess"), Vec::new());
880
881     let new_parser_call =
882         cx.expr_call(sp,
883                      cx.expr_ident(sp, id_ext("new_parser_from_tts")),
884                      vec![parse_sess_call(), tts_expr]);
885
886     let path = vec![id_ext("syntax"), id_ext("ext"), id_ext("quote"), id_ext(parse_method)];
887     let mut args = vec![cx.expr_mut_addr_of(sp, new_parser_call)];
888     args.extend(arg_exprs);
889     let expr = cx.expr_call_global(sp, path, args);
890
891     if parse_method == "parse_attribute" {
892         expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"],
893                                                 &["syntax", "parse", "attr"]])
894     } else {
895         expand_wrapper(cx, sp, cx_expr, expr, &[&["syntax", "ext", "quote", "rt"]])
896     }
897 }