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