1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private))]

extern crate aster;

#[cfg(feature = "with-syntex")]
extern crate syntex;

#[cfg(feature = "with-syntex")]
extern crate syntex_syntax as syntax;

#[cfg(not(feature = "with-syntex"))]
extern crate syntax;

#[cfg(not(feature = "with-syntex"))]
extern crate rustc;

use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::ExtCtxt;
use syntax::ext::base;
use syntax::parse::token::*;
use syntax::parse::token;
use syntax::ptr::P;

///  Quasiquoting works via token trees.
///
///  This is registered as a set of expression syntax extension called quote!
///  that lifts its argument token-tree to an AST representing the
///  construction of the same token tree, with token::SubstNt interpreted
///  as antiquotes (splices).

fn expand_quote_tokens<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree],
) -> Box<base::MacResult + 'cx> {
    let (cx_expr, expr) = expand_tts(cx, sp, tts);
    let expanded = expand_wrapper(sp, cx_expr, expr);
    base::MacEager::expr(expanded)
}

fn expand_quote_ty<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "parser", "Parser", "parse_ty"],
        vec!(),
        tts);
    base::MacEager::expr(expanded)
}

fn expand_quote_expr<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "parser", "Parser", "parse_expr"],
        Vec::new(),
        tts);
    base::MacEager::expr(expanded)
}

fn expand_quote_stmt<'cx>(
    cx: &mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "parser", "Parser", "parse_stmt"],
        vec!(),
        tts);
    base::MacEager::expr(expanded)
}

fn expand_quote_attr<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let builder = aster::AstBuilder::new().span(sp);

    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "attr", "ParserAttr", "parse_attribute"],
        vec![builder.expr().bool(true)],
        tts);

    base::MacEager::expr(expanded)
}

fn expand_quote_matcher<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let builder = aster::AstBuilder::new().span(sp);

    let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);
    let mut vector = mk_stmts_let(&builder);
    vector.extend(statements_mk_tts(&tts[..], true).into_iter());

    let block = builder.expr().block()
        .with_stmts(vector)
        .expr().id("tt");
    
    let expanded = expand_wrapper(sp, cx_expr, block);
    base::MacEager::expr(expanded)
}

fn expand_quote_pat<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "parser", "Parser", "parse_pat"],
        vec!(),
        tts);
    base::MacEager::expr(expanded)
}

fn expand_quote_arm<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "parser", "Parser", "parse_arm"],
        vec!(),
        tts);
    base::MacEager::expr(expanded)
}

fn expand_quote_block<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "parser", "Parser", "parse_block"],
        Vec::new(),
        tts);
    base::MacEager::expr(expanded)
}

fn expand_quote_item<'cx>(
    cx: &mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "parser", "Parser", "parse_item"],
        vec!(),
        tts);
    base::MacEager::expr(expanded)
}

fn expand_quote_impl_item<'cx>(
    cx: &'cx mut ExtCtxt,
    sp: Span,
    tts: &[ast::TokenTree]
) -> Box<base::MacResult + 'cx> {
    let expanded = expand_parse_call(
        cx,
        sp,
        &["syntax", "parse", "parser", "Parser", "parse_impl_item"],
        vec!(),
        tts);
    base::MacEager::expr(expanded)
}

/*
fn expand_quote_where_clause<'cx>(cx: &mut ExtCtxt,
                                      sp: Span,
                                      tts: &[ast::TokenTree])
                                      -> Box<base::MacResult+'cx> {
    let expanded = expand_parse_call(cx, sp, "parse_where_clause",
                                    vec!(), tts);
    base::MacEager::expr(expanded)
}
*/

// Lift an ident to the expr that evaluates to that ident.
fn mk_ident(builder: &aster::AstBuilder, ident: ast::Ident) -> P<ast::Expr> {
    builder.expr().method_call("ident_of").id("ext_cx")
        .arg().str(ident)
        .build()
}

// Lift a name to the expr that evaluates to that name
fn mk_name<T>(builder: &aster::AstBuilder, name: T) -> P<ast::Expr>
    where T: aster::str::ToInternedString,
{
    builder.expr().method_call("name_of").id("ext_cx")
        .arg().str(name)
        .build()
}

fn mk_ast_path(builder: &aster::AstBuilder, name: &str) -> P<ast::Expr> {
    builder.expr().path()
        .global()
        .ids(&["syntax", "ast", name])
        .build()
}

fn mk_token_path(builder: &aster::AstBuilder, name: &str) -> P<ast::Expr> {
    builder.expr().path()
        .global()
        .ids(&["syntax", "parse", "token", name])
        .build()
}

fn mk_binop(builder: &aster::AstBuilder, bop: token::BinOpToken) -> P<ast::Expr> {
    let name = match bop {
        token::Plus     => "Plus",
        token::Minus    => "Minus",
        token::Star     => "Star",
        token::Slash    => "Slash",
        token::Percent  => "Percent",
        token::Caret    => "Caret",
        token::And      => "And",
        token::Or       => "Or",
        token::Shl      => "Shl",
        token::Shr      => "Shr"
    };
    mk_token_path(builder, name)
}

fn mk_delim(builder: &aster::AstBuilder, delim: token::DelimToken) -> P<ast::Expr> {
    let name = match delim {
        token::Paren     => "Paren",
        token::Bracket   => "Bracket",
        token::Brace     => "Brace",
    };
    mk_token_path(builder, name)
}

#[allow(non_upper_case_globals)]
fn expr_mk_token(builder: &aster::AstBuilder, tok: &token::Token) -> P<ast::Expr> {
    macro_rules! mk_lit {
        ($name: expr, $suffix: expr, $($args: expr),+) => {{
            let inner = builder.expr().call()
                .build(mk_token_path(builder, $name))
                $(.with_arg($args))+
                .build();

            let suffix = match $suffix {
                Some(name) => builder.expr().some().build(mk_name(builder, name)),
                None => builder.expr().none(),
            };

            builder.expr().call()
                .build(mk_token_path(builder, "Literal"))
                .with_arg(inner)
                .with_arg(suffix)
                .build()
        }}
    }

    match *tok {
        token::BinOp(binop) => {
            builder.expr().call()
                .build(mk_token_path(builder, "BinOp"))
                .with_arg(mk_binop(builder, binop))
                .build()
        }
        token::BinOpEq(binop) => {
            builder.expr().call()
                .build(mk_token_path(builder, "BinOpEq"))
                .with_arg(mk_binop(builder, binop))
                .build()
        }

        token::OpenDelim(delim) => {
            builder.expr().call()
                .build(mk_token_path(builder, "OpenDelim"))
                .with_arg(mk_delim(builder, delim))
                .build()
        }
        token::CloseDelim(delim) => {
            builder.expr().call()
                .build(mk_token_path(builder, "CloseDelim"))
                .with_arg(mk_delim(builder, delim))
                .build()
        }

        token::Literal(token::Byte(i), suf) => {
            let e_byte = mk_name(builder, i.ident());
            mk_lit!("Byte", suf, e_byte)
        }

        token::Literal(token::Char(i), suf) => {
            let e_char = mk_name(builder, i.ident());
            mk_lit!("Char", suf, e_char)
        }

        token::Literal(token::Integer(i), suf) => {
            let e_int = mk_name(builder, i.ident());
            mk_lit!("Integer", suf, e_int)
        }

        token::Literal(token::Float(fident), suf) => {
            let e_fident = mk_name(builder, fident.ident());
            mk_lit!("Float", suf, e_fident)
        }

        token::Literal(token::Binary(ident), suf) => {
            mk_lit!("Binary", suf, mk_name(builder, ident.ident()))
        }

        token::Literal(token::BinaryRaw(ident, n), suf) => {
            mk_lit!(
                "BinaryRaw",
                suf,
                mk_name(builder, ident.ident()),
                builder.expr().usize(n))
        }

        token::Literal(token::Str_(ident), suf) => {
            mk_lit!("Str_", suf, mk_name(builder, ident.ident()))
        }

        token::Literal(token::StrRaw(ident, n), suf) => {
            mk_lit!(
                "StrRaw",
                suf,
                mk_name(builder, ident.ident()),
                builder.expr().usize(n))
        }

        token::Ident(ident, style) => {
            let style = match style {
                ModName => mk_token_path(builder, "ModName"),
                Plain   => mk_token_path(builder, "Plain"),
            };

            builder.expr().call()
                .build(mk_token_path(builder, "Ident"))
                .with_arg(mk_ident(builder, ident))
                .with_arg(style)
                .build()
        }

        token::Lifetime(ident) => {
            builder.expr().call()
                .build(mk_token_path(builder, "Lifetime"))
                .with_arg(mk_ident(builder, ident))
                .build()
        }

        token::DocComment(ident) => {
            builder.expr().call()
                .build(mk_token_path(builder, "DocComment"))
                .with_arg(mk_name(builder, ident))
                .build()
        }

        token::Eq           => mk_token_path(builder, "Eq"),
        token::Lt           => mk_token_path(builder, "Lt"),
        token::Le           => mk_token_path(builder, "Le"),
        token::EqEq         => mk_token_path(builder, "EqEq"),
        token::Ne           => mk_token_path(builder, "Ne"),
        token::Ge           => mk_token_path(builder, "Ge"),
        token::Gt           => mk_token_path(builder, "Gt"),
        token::AndAnd       => mk_token_path(builder, "AndAnd"),
        token::OrOr         => mk_token_path(builder, "OrOr"),
        token::Not          => mk_token_path(builder, "Not"),
        token::Tilde        => mk_token_path(builder, "Tilde"),
        token::At           => mk_token_path(builder, "At"),
        token::Dot          => mk_token_path(builder, "Dot"),
        token::DotDot       => mk_token_path(builder, "DotDot"),
        token::Comma        => mk_token_path(builder, "Comma"),
        token::Semi         => mk_token_path(builder, "Semi"),
        token::Colon        => mk_token_path(builder, "Colon"),
        token::ModSep       => mk_token_path(builder, "ModSep"),
        token::RArrow       => mk_token_path(builder, "RArrow"),
        token::LArrow       => mk_token_path(builder, "LArrow"),
        token::FatArrow     => mk_token_path(builder, "FatArrow"),
        token::Pound        => mk_token_path(builder, "Pound"),
        token::Dollar       => mk_token_path(builder, "Dollar"),
        token::Underscore   => mk_token_path(builder, "Underscore"),
        token::Eof          => mk_token_path(builder, "Eof"),
        token::DotDotDot    => mk_token_path(builder, "DotDotDot"),
        token::Question     => mk_token_path(builder, "Question"),
        token::Whitespace   => mk_token_path(builder, "Whitespace"),
        token::Comment      => mk_token_path(builder, "Comment"),

        token::Shebang(s) => {
            builder.expr().call()
                .build(mk_token_path(builder, "Shebang"))
                .arg().str(s)
                .build()
        }

        token::MatchNt(name, kind, namep, kindp) => {
            let namep = match namep {
                ModName => mk_token_path(builder, "ModName"),
                Plain => mk_token_path(builder, "Plain"),
            };

            let kindp = match kindp {
                ModName => mk_token_path(builder, "ModName"),
                Plain => mk_token_path(builder, "Plain"),
            };

            builder.expr().call()
                .build(mk_token_path(builder, "MatchNt"))
                .arg().build(mk_ident(builder, name))
                .arg().build(mk_ident(builder, kind))
                .arg().build(namep)
                .arg().build(kindp)
                .build()
        }

        token::Interpolated(..)
        | token::SubstNt(..)
        | token::SpecialVarNt(..) => {
            panic!("quote! with {:?} token", tok)
        }
    }
}

fn statements_mk_tt(tt: &ast::TokenTree, matcher: bool) -> Vec<P<ast::Stmt>> {
    let builder = aster::AstBuilder::new();

    match *tt {
        ast::TtToken(sp, SubstNt(ident, _)) => {
            // tt.extend($ident.to_tokens(ext_cx).into_iter())

            let builder = builder.clone().span(sp);

            let to_tokens = builder.path()
                .global()
                .ids(&["quasi", "ToTokens", "to_tokens"])
                .build();

            let e_to_toks = builder.expr().call()
                .build_path(to_tokens)
                .arg().addr_of().id(ident)
                .arg().id("ext_cx")
                .build();

            let e_to_toks = builder.expr().method_call("into_iter")
                .build(e_to_toks)
                .build();

            let e_push = builder.expr().method_call("extend")
                .id("tt")
                .with_arg(e_to_toks)
                .build();

            vec![builder.stmt().build_expr(e_push)]
        }
        ref tt @ ast::TtToken(_, MatchNt(..)) if !matcher => {
            let mut seq = vec![];
            for i in 0..tt.len() {
                seq.push(tt.get_tt(i));
            }
            statements_mk_tts(&seq[..], matcher)
        }
        ast::TtToken(sp, ref tok) => {
            let builder = builder.clone().span(sp);

            let e_tok = builder.expr().call()
                .build(mk_ast_path(&builder, "TtToken"))
                .arg().id("_sp")
                .with_arg(expr_mk_token(&builder, tok))
                .build();

            let e_push = builder.expr().method_call("push")
                .id("tt")
                .with_arg(e_tok)
                .build();

            vec![builder.stmt().build_expr(e_push)]
        },
        ast::TtDelimited(_, ref delimed) => {
            statements_mk_tt(&delimed.open_tt(), matcher).into_iter()
                .chain(delimed.tts.iter()
                                  .flat_map(|tt| statements_mk_tt(tt, matcher).into_iter()))
                .chain(statements_mk_tt(&delimed.close_tt(), matcher).into_iter())
                .collect()
        },
        ast::TtSequence(sp, ref seq) => {
            if !matcher {
                panic!("TtSequence in quote!");
            }

            let builder = builder.clone().span(sp);

            let e_sp = builder.expr().id("_sp");

            let stmt_let_tt = builder.stmt().let_()
                .mut_id("tt")
                .expr().vec().build();
            
            let mut tts_stmts = vec![stmt_let_tt];
            tts_stmts.extend(statements_mk_tts(&seq.tts[..], matcher).into_iter());

            let e_tts = builder.expr().block()
                .with_stmts(tts_stmts)
                .expr().id("tt");

            let e_separator = match seq.separator {
                Some(ref sep) => builder.expr().some().build(expr_mk_token(&builder, sep)),
                None => builder.expr().none(),
            };

            let e_op = match seq.op {
                ast::ZeroOrMore => mk_ast_path(&builder, "ZeroOrMore"),
                ast::OneOrMore => mk_ast_path(&builder, "OneOrMore"),
            };

            let e_seq_struct = builder.expr().struct_()
                .global().ids(&["syntax", "ast", "SequenceRepetition"]).build()
                .field("tts").build(e_tts)
                .field("separator").build(e_separator)
                .field("op").build(e_op)
                .field("num_captures").usize(seq.num_captures)
                .build();

            let e_rc_new = builder.expr().rc()
                .build(e_seq_struct);

            let e_tok = builder.expr().call()
                .build(mk_ast_path(&builder, "TtSequence"))
                .arg().build(e_sp)
                .arg().build(e_rc_new)
                .build();

            let e_push = builder.expr().method_call("push").id("tt")
                .arg().build(e_tok)
                .build();

            vec![builder.stmt().expr().build(e_push)]
        }
    }
}

fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[ast::TokenTree])
                            -> (P<ast::Expr>, Vec<ast::TokenTree>) {
    // NB: It appears that the main parser loses its mind if we consider
    // $foo as a SubstNt during the main parse, so we have to re-parse
    // under quote_depth > 0. This is silly and should go away; the _guess_ is
    // it has to do with transition away from supporting old-style macros, so
    // try removing it when enough of them are gone.

    let mut p = cx.new_parser_from_tts(tts);
    p.quote_depth += 1;

    let cx_expr = p.parse_expr();
    if !p.eat(&token::Comma).ok().unwrap() {
        let _ = p.fatal("expected token `,`");
    }

    let tts = p.parse_all_token_trees().ok().unwrap();
    p.abort_if_errors();

    (cx_expr, tts)
}

fn mk_stmts_let(builder: &aster::AstBuilder) -> Vec<P<ast::Stmt>> {
    // We also bind a single value, sp, to ext_cx.call_site()
    //
    // This causes every span in a token-tree quote to be attributed to the
    // call site of the extension using the quote. We can't really do much
    // better since the source of the quote may well be in a library that
    // was not even parsed by this compilation run, that the user has no
    // source code for (eg. in libsyntax, which they're just _using_).
    //
    // The old quasiquoter had an elaborate mechanism for denoting input
    // file locations from which quotes originated; unfortunately this
    // relied on feeding the source string of the quote back into the
    // compiler (which we don't really want to do) and, in any case, only
    // pushed the problem a very small step further back: an error
    // resulting from a parse of the resulting quote is still attributed to
    // the site the string literal occurred, which was in a source file
    // _other_ than the one the user has control over. For example, an
    // error in a quote from the protocol compiler, invoked in user code
    // using macro_rules! for example, will be attributed to the macro_rules.rs
    // file in libsyntax, which the user might not even have source to (unless
    // they happen to have a compiler on hand). Over all, the phase distinction
    // just makes quotes "hard to attribute". Possibly this could be fixed
    // by recreating some of the original qq machinery in the tt regime
    // (pushing fake FileMaps onto the parser to account for original sites
    // of quotes, for example) but at this point it seems not likely to be
    // worth the hassle.

    let e_sp = builder.expr().method_call("call_site")
        .id("ext_cx")
        .build();

    let stmt_let_sp = builder.stmt()
        .let_id("_sp").build(e_sp);

    let stmt_let_tt = builder.stmt().let_().mut_id("tt")
        .expr().call()
            .path().global().ids(&["std", "vec", "Vec", "new"]).build()
            .build();

    vec!(stmt_let_sp, stmt_let_tt)
}

fn statements_mk_tts(tts: &[ast::TokenTree], matcher: bool) -> Vec<P<ast::Stmt>> {
    let mut ss = Vec::new();
    for tt in tts {
        ss.extend(statements_mk_tt(tt, matcher).into_iter());
    }
    ss
}

fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree])
              -> (P<ast::Expr>, P<ast::Expr>) {
    let builder = aster::AstBuilder::new().span(sp);

    let (cx_expr, tts) = parse_arguments_to_quote(cx, tts);

    let mut vector = mk_stmts_let(&builder);
    vector.extend(statements_mk_tts(&tts[..], false).into_iter());
    let block = builder.expr().block()
        .with_stmts(vector)
        .expr().id("tt");

    (cx_expr, block)
}

fn expand_wrapper(sp: Span,
                  cx_expr: P<ast::Expr>,
                  expr: P<ast::Expr>) -> P<ast::Expr> {
    let builder = aster::AstBuilder::new().span(sp);

    // Explicitly borrow to avoid moving from the invoker (#16992)
    let cx_expr_borrow = builder.expr()
        .addr_of().build_deref(cx_expr);

    let stmt_let_ext_cx = builder.stmt().let_id("ext_cx")
        .build(cx_expr_borrow);

    builder.expr().block()
        .with_stmt(stmt_let_ext_cx)
        .build_expr(expr)
}

fn expand_parse_call(cx: &ExtCtxt,
                     sp: Span,
                     parse_method: &[&str],
                     arg_exprs: Vec<P<ast::Expr>> ,
                     tts: &[ast::TokenTree]) -> P<ast::Expr> {
    let builder = aster::AstBuilder::new().span(sp);

    let (cx_expr, tts_expr) = expand_tts(cx, sp, tts);

    let cfg_call = builder.expr().method_call("cfg")
        .id("ext_cx")
        .build();

    let parse_sess_call = builder.expr().method_call("parse_sess")
        .id("ext_cx")
        .build();

    let new_parser_from_tts_path = builder.path()
        .global()
        .ids(&["syntax", "parse", "new_parser_from_tts"])
        .build();

    let new_parser_call = builder.expr().call()
        .build_path(new_parser_from_tts_path)
        .with_arg(parse_sess_call)
        .with_arg(cfg_call)
        .with_arg(tts_expr)
        .build();

    let parse_method_path = builder.path()
        .global()
        .ids(parse_method)
        .build();

    let expr = builder.expr().call()
        .build_path(parse_method_path)
        .arg().mut_addr_of().build(new_parser_call)
        .with_args(arg_exprs)
        .build();

    expand_wrapper(sp, cx_expr, expr)
}

#[cfg(feature = "with-syntex")]
pub fn register(reg: &mut syntex::Registry) {
    reg.add_macro("quote_tokens", expand_quote_tokens);
    reg.add_macro("quote_ty", expand_quote_ty);
    reg.add_macro("quote_expr", expand_quote_expr);
    reg.add_macro("quote_matcher", expand_quote_matcher);
    reg.add_macro("quote_stmt", expand_quote_stmt);
    reg.add_macro("quote_attr", expand_quote_attr);
    reg.add_macro("quote_pat", expand_quote_pat);
    reg.add_macro("quote_arm", expand_quote_arm);
    reg.add_macro("quote_block", expand_quote_block);
    reg.add_macro("quote_item", expand_quote_item);
    reg.add_macro("quote_impl_item", expand_quote_impl_item);
    //reg.add_macro("quote_where_clause", expand_quote_where_clause);
}

#[cfg(not(feature = "syntex"))]
pub fn register(reg: &mut rustc::plugin::Registry) {
    reg.register_macro("quote_tokens", expand_quote_tokens);
    reg.register_macro("quote_ty", expand_quote_ty);
    reg.register_macro("quote_expr", expand_quote_expr);
    reg.register_macro("quote_matcher", expand_quote_matcher);
    reg.register_macro("quote_stmt", expand_quote_stmt);
    reg.register_macro("quote_attr", expand_quote_attr);
    reg.register_macro("quote_pat", expand_quote_pat);
    reg.register_macro("quote_arm", expand_quote_arm);
    reg.register_macro("quote_block", expand_quote_block);
    reg.register_macro("quote_item", expand_quote_item);
    reg.register_macro("quote_impl_item", expand_quote_impl_item);
    //reg.register_macro("quote_where_clause", expand_quote_where_clause);
}