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