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