forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexpand.rs
2279 lines (2050 loc) · 87.4 KB
/
expand.rs
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 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.
use ast::{Block, Crate, DeclLocal, ExprMac, PatMac};
use ast::{Local, Ident, MacInvocTT};
use ast::{ItemMac, MacStmtWithSemicolon, Mrk, Stmt, StmtDecl, StmtMac};
use ast::{StmtExpr, StmtSemi};
use ast::TokenTree;
use ast;
use ext::mtwt;
use ext::build::AstBuilder;
use attr;
use attr::AttrMetaMethods;
use codemap;
use codemap::{Span, Spanned, ExpnInfo, NameAndSpan, MacroBang, MacroAttribute};
use codemap::{CompilerExpansion, CompilerExpansionFormat};
use ext::base::*;
use feature_gate::{self, Features, GatedCfg};
use fold;
use fold::*;
use parse;
use parse::token::{fresh_mark, fresh_name, intern};
use parse::token;
use ptr::P;
use util::small_vector::SmallVector;
use visit;
use visit::Visitor;
use std_inject;
// Given suffix ["b","c","d"], returns path `::std::b::c::d` when
// `fld.cx.use_std`, and `::core::b::c::d` otherwise.
fn mk_core_path(fld: &mut MacroExpander,
span: Span,
suffix: &[&'static str]) -> ast::Path {
let idents = fld.cx.std_path(suffix);
fld.cx.path_global(span, idents)
}
pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
fn push_compiler_expansion(fld: &mut MacroExpander, span: Span,
expansion_type: CompilerExpansionFormat) {
fld.cx.bt_push(ExpnInfo {
call_site: span,
callee: NameAndSpan {
format: CompilerExpansion(expansion_type),
// This does *not* mean code generated after
// `push_compiler_expansion` is automatically exempt
// from stability lints; must also tag such code with
// an appropriate span from `fld.cx.backtrace()`.
allow_internal_unstable: true,
span: None,
},
});
}
// Sets the expn_id so that we can use unstable methods.
fn allow_unstable(fld: &mut MacroExpander, span: Span) -> Span {
Span { expn_id: fld.cx.backtrace(), ..span }
}
let expr_span = e.span;
return e.and_then(|ast::Expr {id, node, span}| match node {
// expr_mac should really be expr_ext or something; it's the
// entry-point for all syntax extensions.
ast::ExprMac(mac) => {
let expanded_expr = match expand_mac_invoc(mac, span,
|r| r.make_expr(),
mark_expr, fld) {
Some(expr) => expr,
None => {
return DummyResult::raw_expr(span);
}
};
// Keep going, outside-in.
let fully_expanded = fld.fold_expr(expanded_expr);
let span = fld.new_span(span);
fld.cx.bt_pop();
fully_expanded.map(|e| ast::Expr {
id: ast::DUMMY_NODE_ID,
node: e.node,
span: span,
})
}
// Desugar ExprBox: `in (PLACE) EXPR`
ast::ExprBox(Some(placer), value_expr) => {
// to:
//
// let p = PLACE;
// let mut place = Placer::make_place(p);
// let raw_place = Place::pointer(&mut place);
// push_unsafe!({
// std::intrinsics::move_val_init(raw_place, pop_unsafe!( EXPR ));
// InPlace::finalize(place)
// })
// Ensure feature-gate is enabled
feature_gate::check_for_placement_in(
fld.cx.ecfg.features,
&fld.cx.parse_sess.span_diagnostic,
expr_span);
push_compiler_expansion(fld, expr_span, CompilerExpansionFormat::PlacementIn);
let value_span = value_expr.span;
let placer_span = placer.span;
let placer_expr = fld.fold_expr(placer);
let value_expr = fld.fold_expr(value_expr);
let placer_ident = token::gensym_ident("placer");
let agent_ident = token::gensym_ident("place");
let p_ptr_ident = token::gensym_ident("p_ptr");
let placer = fld.cx.expr_ident(span, placer_ident);
let agent = fld.cx.expr_ident(span, agent_ident);
let p_ptr = fld.cx.expr_ident(span, p_ptr_ident);
let make_place = ["ops", "Placer", "make_place"];
let place_pointer = ["ops", "Place", "pointer"];
let move_val_init = ["intrinsics", "move_val_init"];
let inplace_finalize = ["ops", "InPlace", "finalize"];
let make_call = |fld: &mut MacroExpander, p, args| {
// We feed in the `expr_span` because codemap's span_allows_unstable
// allows the call_site span to inherit the `allow_internal_unstable`
// setting.
let span_unstable = allow_unstable(fld, expr_span);
let path = mk_core_path(fld, span_unstable, p);
let path = fld.cx.expr_path(path);
let expr_span_unstable = allow_unstable(fld, span);
fld.cx.expr_call(expr_span_unstable, path, args)
};
let stmt_let = |fld: &mut MacroExpander, bind, expr| {
fld.cx.stmt_let(placer_span, false, bind, expr)
};
let stmt_let_mut = |fld: &mut MacroExpander, bind, expr| {
fld.cx.stmt_let(placer_span, true, bind, expr)
};
// let placer = <placer_expr> ;
let s1 = stmt_let(fld, placer_ident, placer_expr);
// let mut place = Placer::make_place(placer);
let s2 = {
let call = make_call(fld, &make_place, vec![placer]);
stmt_let_mut(fld, agent_ident, call)
};
// let p_ptr = Place::pointer(&mut place);
let s3 = {
let args = vec![fld.cx.expr_mut_addr_of(placer_span, agent.clone())];
let call = make_call(fld, &place_pointer, args);
stmt_let(fld, p_ptr_ident, call)
};
// pop_unsafe!(EXPR));
let pop_unsafe_expr = pop_unsafe_expr(fld.cx, value_expr, value_span);
// push_unsafe!({
// ptr::write(p_ptr, pop_unsafe!(<value_expr>));
// InPlace::finalize(place)
// })
let expr = {
let call_move_val_init = StmtSemi(make_call(
fld, &move_val_init, vec![p_ptr, pop_unsafe_expr]), ast::DUMMY_NODE_ID);
let call_move_val_init = codemap::respan(value_span, call_move_val_init);
let call = make_call(fld, &inplace_finalize, vec![agent]);
Some(push_unsafe_expr(fld.cx, vec![P(call_move_val_init)], call, span))
};
let block = fld.cx.block_all(span, vec![s1, s2, s3], expr);
let result = fld.cx.expr_block(block);
fld.cx.bt_pop();
result
}
// Issue #22181:
// Eventually a desugaring for `box EXPR`
// (similar to the desugaring above for `in PLACE BLOCK`)
// should go here, desugaring
//
// to:
//
// let mut place = BoxPlace::make_place();
// let raw_place = Place::pointer(&mut place);
// let value = $value;
// unsafe {
// ::std::ptr::write(raw_place, value);
// Boxed::finalize(place)
// }
//
// But for now there are type-inference issues doing that.
ast::ExprWhile(cond, body, opt_ident) => {
let cond = fld.fold_expr(cond);
let (body, opt_ident) = expand_loop_block(body, opt_ident, fld);
fld.cx.expr(span, ast::ExprWhile(cond, body, opt_ident))
}
// Desugar ExprWhileLet
// From: `[opt_ident]: while let <pat> = <expr> <body>`
ast::ExprWhileLet(pat, expr, body, opt_ident) => {
// to:
//
// [opt_ident]: loop {
// match <expr> {
// <pat> => <body>,
// _ => break
// }
// }
push_compiler_expansion(fld, span, CompilerExpansionFormat::WhileLet);
// `<pat> => <body>`
let pat_arm = {
let body_expr = fld.cx.expr_block(body);
fld.cx.arm(pat.span, vec![pat], body_expr)
};
// `_ => break`
let break_arm = {
let pat_under = fld.cx.pat_wild(span);
let break_expr = fld.cx.expr_break(span);
fld.cx.arm(span, vec![pat_under], break_expr)
};
// `match <expr> { ... }`
let arms = vec![pat_arm, break_arm];
let match_expr = fld.cx.expr(span,
ast::ExprMatch(expr, arms, ast::MatchSource::WhileLetDesugar));
// `[opt_ident]: loop { ... }`
let loop_block = fld.cx.block_expr(match_expr);
let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
let result = fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident));
fld.cx.bt_pop();
result
}
// Desugar ExprIfLet
// From: `if let <pat> = <expr> <body> [<elseopt>]`
ast::ExprIfLet(pat, expr, body, mut elseopt) => {
// to:
//
// match <expr> {
// <pat> => <body>,
// [_ if <elseopt_if_cond> => <elseopt_if_body>,]
// _ => [<elseopt> | ()]
// }
push_compiler_expansion(fld, span, CompilerExpansionFormat::IfLet);
// `<pat> => <body>`
let pat_arm = {
let body_expr = fld.cx.expr_block(body);
fld.cx.arm(pat.span, vec![pat], body_expr)
};
// `[_ if <elseopt_if_cond> => <elseopt_if_body>,]`
let else_if_arms = {
let mut arms = vec![];
loop {
let elseopt_continue = elseopt
.and_then(|els| els.and_then(|els| match els.node {
// else if
ast::ExprIf(cond, then, elseopt) => {
let pat_under = fld.cx.pat_wild(span);
arms.push(ast::Arm {
attrs: vec![],
pats: vec![pat_under],
guard: Some(cond),
body: fld.cx.expr_block(then)
});
elseopt.map(|elseopt| (elseopt, true))
}
_ => Some((P(els), false))
}));
match elseopt_continue {
Some((e, true)) => {
elseopt = Some(e);
}
Some((e, false)) => {
elseopt = Some(e);
break;
}
None => {
elseopt = None;
break;
}
}
}
arms
};
let contains_else_clause = elseopt.is_some();
// `_ => [<elseopt> | ()]`
let else_arm = {
let pat_under = fld.cx.pat_wild(span);
let else_expr = elseopt.unwrap_or_else(|| fld.cx.expr_tuple(span, vec![]));
fld.cx.arm(span, vec![pat_under], else_expr)
};
let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
arms.push(pat_arm);
arms.extend(else_if_arms);
arms.push(else_arm);
let match_expr = fld.cx.expr(span,
ast::ExprMatch(expr, arms,
ast::MatchSource::IfLetDesugar {
contains_else_clause: contains_else_clause,
}));
let result = fld.fold_expr(match_expr);
fld.cx.bt_pop();
result
}
// Desugar support for ExprIfLet in the ExprIf else position
ast::ExprIf(cond, blk, elseopt) => {
let elseopt = elseopt.map(|els| els.and_then(|els| match els.node {
ast::ExprIfLet(..) => {
push_compiler_expansion(fld, span, CompilerExpansionFormat::IfLet);
// wrap the if-let expr in a block
let span = els.span;
let blk = P(ast::Block {
stmts: vec![],
expr: Some(P(els)),
id: ast::DUMMY_NODE_ID,
rules: ast::DefaultBlock,
span: span
});
let result = fld.cx.expr_block(blk);
fld.cx.bt_pop();
result
}
_ => P(els)
}));
let if_expr = fld.cx.expr(span, ast::ExprIf(cond, blk, elseopt));
if_expr.map(|e| noop_fold_expr(e, fld))
}
ast::ExprLoop(loop_block, opt_ident) => {
let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident))
}
// Desugar ExprForLoop
// From: `[opt_ident]: for <pat> in <head> <body>`
ast::ExprForLoop(pat, head, body, opt_ident) => {
// to:
//
// {
// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
// mut iter => {
// [opt_ident]: loop {
// match ::std::iter::Iterator::next(&mut iter) {
// ::std::option::Option::Some(<pat>) => <body>,
// ::std::option::Option::None => break
// }
// }
// }
// };
// result
// }
push_compiler_expansion(fld, span, CompilerExpansionFormat::ForLoop);
let span = fld.new_span(span);
// expand <head>
let head = fld.fold_expr(head);
let iter = token::gensym_ident("iter");
let pat_span = fld.new_span(pat.span);
// `::std::option::Option::Some(<pat>) => <body>`
let pat_arm = {
let body_expr = fld.cx.expr_block(body);
let pat = fld.fold_pat(pat);
let some_pat = fld.cx.pat_some(pat_span, pat);
fld.cx.arm(pat_span, vec![some_pat], body_expr)
};
// `::std::option::Option::None => break`
let break_arm = {
let break_expr = fld.cx.expr_break(span);
fld.cx.arm(span, vec![fld.cx.pat_none(span)], break_expr)
};
// `match ::std::iter::Iterator::next(&mut iter) { ... }`
let match_expr = {
let next_path = {
let strs = fld.cx.std_path(&["iter", "Iterator", "next"]);
fld.cx.path_global(span, strs)
};
let ref_mut_iter = fld.cx.expr_mut_addr_of(span, fld.cx.expr_ident(span, iter));
let next_expr =
fld.cx.expr_call(span, fld.cx.expr_path(next_path), vec![ref_mut_iter]);
let arms = vec![pat_arm, break_arm];
fld.cx.expr(pat_span,
ast::ExprMatch(next_expr, arms, ast::MatchSource::ForLoopDesugar))
};
// `[opt_ident]: loop { ... }`
let loop_block = fld.cx.block_expr(match_expr);
let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
let loop_expr = fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident));
// `mut iter => { ... }`
let iter_arm = {
let iter_pat =
fld.cx.pat_ident_binding_mode(span, iter, ast::BindByValue(ast::MutMutable));
fld.cx.arm(span, vec![iter_pat], loop_expr)
};
// `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
let into_iter_expr = {
let into_iter_path = {
let strs = fld.cx.std_path(&["iter", "IntoIterator",
"into_iter"]);
fld.cx.path_global(span, strs)
};
fld.cx.expr_call(span, fld.cx.expr_path(into_iter_path), vec![head])
};
let match_expr = fld.cx.expr_match(span, into_iter_expr, vec![iter_arm]);
// `{ let result = ...; result }`
let result_ident = token::gensym_ident("result");
let result = fld.cx.expr_block(
fld.cx.block_all(
span,
vec![fld.cx.stmt_let(span, false, result_ident, match_expr)],
Some(fld.cx.expr_ident(span, result_ident))));
fld.cx.bt_pop();
result
}
ast::ExprClosure(capture_clause, fn_decl, block) => {
push_compiler_expansion(fld, span, CompilerExpansionFormat::Closure);
let (rewritten_fn_decl, rewritten_block)
= expand_and_rename_fn_decl_and_block(fn_decl, block, fld);
let new_node = ast::ExprClosure(capture_clause,
rewritten_fn_decl,
rewritten_block);
let result = P(ast::Expr{id:id, node: new_node, span: fld.new_span(span)});
fld.cx.bt_pop();
result
}
_ => {
P(noop_fold_expr(ast::Expr {
id: id,
node: node,
span: span
}, fld))
}
});
fn push_unsafe_expr(cx: &mut ExtCtxt, stmts: Vec<P<ast::Stmt>>,
expr: P<ast::Expr>, span: Span)
-> P<ast::Expr> {
let rules = ast::PushUnsafeBlock(ast::CompilerGenerated);
cx.expr_block(P(ast::Block {
rules: rules, span: span, id: ast::DUMMY_NODE_ID,
stmts: stmts, expr: Some(expr),
}))
}
fn pop_unsafe_expr(cx: &mut ExtCtxt, expr: P<ast::Expr>, span: Span)
-> P<ast::Expr> {
let rules = ast::PopUnsafeBlock(ast::CompilerGenerated);
cx.expr_block(P(ast::Block {
rules: rules, span: span, id: ast::DUMMY_NODE_ID,
stmts: vec![], expr: Some(expr),
}))
}
}
/// Expand a (not-ident-style) macro invocation. Returns the result
/// of expansion and the mark which must be applied to the result.
/// Our current interface doesn't allow us to apply the mark to the
/// result until after calling make_expr, make_items, etc.
fn expand_mac_invoc<T, F, G>(mac: ast::Mac,
span: codemap::Span,
parse_thunk: F,
mark_thunk: G,
fld: &mut MacroExpander)
-> Option<T> where
F: for<'a> FnOnce(Box<MacResult+'a>) -> Option<T>,
G: FnOnce(T, Mrk) -> T,
{
match mac.node {
// it would almost certainly be cleaner to pass the whole
// macro invocation in, rather than pulling it apart and
// marking the tts and the ctxt separately. This also goes
// for the other three macro invocation chunks of code
// in this file.
// Token-tree macros:
MacInvocTT(pth, tts, _) => {
if pth.segments.len() > 1 {
fld.cx.span_err(pth.span,
"expected macro name without module \
separators");
// let compilation continue
return None;
}
let extname = pth.segments[0].identifier.name;
match fld.cx.syntax_env.find(&extname) {
None => {
fld.cx.span_err(
pth.span,
&format!("macro undefined: '{}!'",
&extname));
// let compilation continue
None
}
Some(rc) => match *rc {
NormalTT(ref expandfun, exp_span, allow_internal_unstable) => {
fld.cx.bt_push(ExpnInfo {
call_site: span,
callee: NameAndSpan {
format: MacroBang(extname),
span: exp_span,
allow_internal_unstable: allow_internal_unstable,
},
});
let fm = fresh_mark();
let marked_before = mark_tts(&tts[..], fm);
// The span that we pass to the expanders we want to
// be the root of the call stack. That's the most
// relevant span and it's the actual invocation of
// the macro.
let mac_span = fld.cx.original_span();
let opt_parsed = {
let expanded = expandfun.expand(fld.cx,
mac_span,
&marked_before[..]);
parse_thunk(expanded)
};
let parsed = match opt_parsed {
Some(e) => e,
None => {
fld.cx.span_err(
pth.span,
&format!("non-expression macro in expression position: {}",
extname
));
return None;
}
};
Some(mark_thunk(parsed,fm))
}
_ => {
fld.cx.span_err(
pth.span,
&format!("'{}' is not a tt-style macro",
extname));
None
}
}
}
}
}
}
/// Rename loop label and expand its loop body
///
/// The renaming procedure for loop is different in the sense that the loop
/// body is in a block enclosed by loop head so the renaming of loop label
/// must be propagated to the enclosed context.
fn expand_loop_block(loop_block: P<Block>,
opt_ident: Option<Ident>,
fld: &mut MacroExpander) -> (P<Block>, Option<Ident>) {
match opt_ident {
Some(label) => {
let new_label = fresh_name(&label);
let rename = (label, new_label);
// The rename *must not* be added to the pending list of current
// syntax context otherwise an unrelated `break` or `continue` in
// the same context will pick that up in the deferred renaming pass
// and be renamed incorrectly.
let mut rename_list = vec!(rename);
let mut rename_fld = IdentRenamer{renames: &mut rename_list};
let renamed_ident = rename_fld.fold_ident(label);
// The rename *must* be added to the enclosed syntax context for
// `break` or `continue` to pick up because by definition they are
// in a block enclosed by loop head.
fld.cx.syntax_env.push_frame();
fld.cx.syntax_env.info().pending_renames.push(rename);
let expanded_block = expand_block_elts(loop_block, fld);
fld.cx.syntax_env.pop_frame();
(expanded_block, Some(renamed_ident))
}
None => (fld.fold_block(loop_block), opt_ident)
}
}
// eval $e with a new exts frame.
// must be a macro so that $e isn't evaluated too early.
macro_rules! with_exts_frame {
($extsboxexpr:expr,$macros_escape:expr,$e:expr) =>
({$extsboxexpr.push_frame();
$extsboxexpr.info().macros_escape = $macros_escape;
let result = $e;
$extsboxexpr.pop_frame();
result
})
}
// When we enter a module, record it, for the sake of `module!`
pub fn expand_item(it: P<ast::Item>, fld: &mut MacroExpander)
-> SmallVector<P<ast::Item>> {
let it = expand_item_modifiers(it, fld);
expand_annotatable(Annotatable::Item(it), fld)
.into_iter().map(|i| i.expect_item()).collect()
}
/// Expand item_underscore
fn expand_item_underscore(item: ast::Item_, fld: &mut MacroExpander) -> ast::Item_ {
match item {
ast::ItemFn(decl, unsafety, constness, abi, generics, body) => {
let (rewritten_fn_decl, rewritten_body)
= expand_and_rename_fn_decl_and_block(decl, body, fld);
let expanded_generics = fold::noop_fold_generics(generics,fld);
ast::ItemFn(rewritten_fn_decl, unsafety, constness, abi,
expanded_generics, rewritten_body)
}
_ => noop_fold_item_underscore(item, fld)
}
}
// does this attribute list contain "macro_use" ?
fn contains_macro_use(fld: &mut MacroExpander, attrs: &[ast::Attribute]) -> bool {
for attr in attrs {
let mut is_use = attr.check_name("macro_use");
if attr.check_name("macro_escape") {
fld.cx.span_warn(attr.span, "macro_escape is a deprecated synonym for macro_use");
is_use = true;
if let ast::AttrInner = attr.node.style {
fld.cx.fileline_help(attr.span, "consider an outer attribute, \
#[macro_use] mod ...");
}
};
if is_use {
match attr.node.value.node {
ast::MetaWord(..) => (),
_ => fld.cx.span_err(attr.span, "arguments to macro_use are not allowed here"),
}
return true;
}
}
false
}
// Support for item-position macro invocations, exactly the same
// logic as for expression-position macro invocations.
pub fn expand_item_mac(it: P<ast::Item>,
fld: &mut MacroExpander) -> SmallVector<P<ast::Item>> {
let (extname, path_span, tts) = match it.node {
ItemMac(codemap::Spanned {
node: MacInvocTT(ref pth, ref tts, _),
..
}) => {
(pth.segments[0].identifier.name, pth.span, (*tts).clone())
}
_ => fld.cx.span_bug(it.span, "invalid item macro invocation")
};
let fm = fresh_mark();
let items = {
let expanded = match fld.cx.syntax_env.find(&extname) {
None => {
fld.cx.span_err(path_span,
&format!("macro undefined: '{}!'",
extname));
// let compilation continue
return SmallVector::zero();
}
Some(rc) => match *rc {
NormalTT(ref expander, span, allow_internal_unstable) => {
if it.ident.name != parse::token::special_idents::invalid.name {
fld.cx
.span_err(path_span,
&format!("macro {}! expects no ident argument, given '{}'",
extname,
it.ident));
return SmallVector::zero();
}
fld.cx.bt_push(ExpnInfo {
call_site: it.span,
callee: NameAndSpan {
format: MacroBang(extname),
span: span,
allow_internal_unstable: allow_internal_unstable,
}
});
// mark before expansion:
let marked_before = mark_tts(&tts[..], fm);
expander.expand(fld.cx, it.span, &marked_before[..])
}
IdentTT(ref expander, span, allow_internal_unstable) => {
if it.ident.name == parse::token::special_idents::invalid.name {
fld.cx.span_err(path_span,
&format!("macro {}! expects an ident argument",
extname));
return SmallVector::zero();
}
fld.cx.bt_push(ExpnInfo {
call_site: it.span,
callee: NameAndSpan {
format: MacroBang(extname),
span: span,
allow_internal_unstable: allow_internal_unstable,
}
});
// mark before expansion:
let marked_tts = mark_tts(&tts[..], fm);
expander.expand(fld.cx, it.span, it.ident, marked_tts)
}
MacroRulesTT => {
if it.ident.name == parse::token::special_idents::invalid.name {
fld.cx.span_err(path_span,
&format!("macro_rules! expects an ident argument")
);
return SmallVector::zero();
}
fld.cx.bt_push(ExpnInfo {
call_site: it.span,
callee: NameAndSpan {
format: MacroBang(extname),
span: None,
// `macro_rules!` doesn't directly allow
// unstable (this is orthogonal to whether
// the macro it creates allows it)
allow_internal_unstable: false,
}
});
// DON'T mark before expansion.
let allow_internal_unstable = attr::contains_name(&it.attrs,
"allow_internal_unstable");
// ensure any #[allow_internal_unstable]s are
// detected (including nested macro definitions
// etc.)
if allow_internal_unstable && !fld.cx.ecfg.enable_allow_internal_unstable() {
feature_gate::emit_feature_err(
&fld.cx.parse_sess.span_diagnostic,
"allow_internal_unstable",
it.span,
feature_gate::EXPLAIN_ALLOW_INTERNAL_UNSTABLE)
}
let def = ast::MacroDef {
ident: it.ident,
attrs: it.attrs.clone(),
id: ast::DUMMY_NODE_ID,
span: it.span,
imported_from: None,
export: attr::contains_name(&it.attrs, "macro_export"),
use_locally: true,
allow_internal_unstable: allow_internal_unstable,
body: tts,
};
fld.cx.insert_macro(def);
// macro_rules! has a side effect but expands to nothing.
fld.cx.bt_pop();
return SmallVector::zero();
}
_ => {
fld.cx.span_err(it.span,
&format!("{}! is not legal in item position",
extname));
return SmallVector::zero();
}
}
};
expanded.make_items()
};
let items = match items {
Some(items) => {
items.into_iter()
.map(|i| mark_item(i, fm))
.flat_map(|i| fld.fold_item(i).into_iter())
.collect()
}
None => {
fld.cx.span_err(path_span,
&format!("non-item macro in item position: {}",
extname));
return SmallVector::zero();
}
};
fld.cx.bt_pop();
items
}
/// Expand a stmt
fn expand_stmt(stmt: P<Stmt>, fld: &mut MacroExpander) -> SmallVector<P<Stmt>> {
let stmt = stmt.and_then(|stmt| stmt);
let (mac, style) = match stmt.node {
StmtMac(mac, style) => (mac, style),
_ => return expand_non_macro_stmt(stmt, fld)
};
let maybe_new_items =
expand_mac_invoc(mac.and_then(|m| m), stmt.span,
|r| r.make_stmts(),
|stmts, mark| stmts.move_map(|m| mark_stmt(m, mark)),
fld);
let mut fully_expanded = match maybe_new_items {
Some(stmts) => {
// Keep going, outside-in.
let new_items = stmts.into_iter().flat_map(|s| {
fld.fold_stmt(s).into_iter()
}).collect();
fld.cx.bt_pop();
new_items
}
None => SmallVector::zero()
};
// If this is a macro invocation with a semicolon, then apply that
// semicolon to the final statement produced by expansion.
if style == MacStmtWithSemicolon {
if let Some(stmt) = fully_expanded.pop() {
let new_stmt = stmt.map(|Spanned {node, span}| {
Spanned {
node: match node {
StmtExpr(e, stmt_id) => StmtSemi(e, stmt_id),
_ => node /* might already have a semi */
},
span: span
}
});
fully_expanded.push(new_stmt);
}
}
fully_expanded
}
// expand a non-macro stmt. this is essentially the fallthrough for
// expand_stmt, above.
fn expand_non_macro_stmt(Spanned {node, span: stmt_span}: Stmt, fld: &mut MacroExpander)
-> SmallVector<P<Stmt>> {
// is it a let?
match node {
StmtDecl(decl, node_id) => decl.and_then(|Spanned {node: decl, span}| match decl {
DeclLocal(local) => {
// take it apart:
let rewritten_local = local.map(|Local {id, pat, ty, init, span}| {
// expand the ty since TyFixedLengthVec contains an Expr
// and thus may have a macro use
let expanded_ty = ty.map(|t| fld.fold_ty(t));
// expand the pat (it might contain macro uses):
let expanded_pat = fld.fold_pat(pat);
// find the PatIdents in the pattern:
// oh dear heaven... this is going to include the enum
// names, as well... but that should be okay, as long as
// the new names are gensyms for the old ones.
// generate fresh names, push them to a new pending list
let idents = pattern_bindings(&*expanded_pat);
let mut new_pending_renames =
idents.iter().map(|ident| (*ident, fresh_name(ident))).collect();
// rewrite the pattern using the new names (the old
// ones have already been applied):
let rewritten_pat = {
// nested binding to allow borrow to expire:
let mut rename_fld = IdentRenamer{renames: &mut new_pending_renames};
rename_fld.fold_pat(expanded_pat)
};
// add them to the existing pending renames:
fld.cx.syntax_env.info().pending_renames
.extend(new_pending_renames);
Local {
id: id,
ty: expanded_ty,
pat: rewritten_pat,
// also, don't forget to expand the init:
init: init.map(|e| fld.fold_expr(e)),
span: span
}
});
SmallVector::one(P(Spanned {
node: StmtDecl(P(Spanned {
node: DeclLocal(rewritten_local),
span: span
}),
node_id),
span: stmt_span
}))
}
_ => {
noop_fold_stmt(Spanned {
node: StmtDecl(P(Spanned {
node: decl,
span: span
}),
node_id),
span: stmt_span
}, fld)
}
}),
_ => {
noop_fold_stmt(Spanned {
node: node,
span: stmt_span
}, fld)
}
}
}
// expand the arm of a 'match', renaming for macro hygiene
fn expand_arm(arm: ast::Arm, fld: &mut MacroExpander) -> ast::Arm {
// expand pats... they might contain macro uses:
let expanded_pats = arm.pats.move_map(|pat| fld.fold_pat(pat));
if expanded_pats.is_empty() {
panic!("encountered match arm with 0 patterns");
}
// all of the pats must have the same set of bindings, so use the
// first one to extract them and generate new names:
let idents = pattern_bindings(&*expanded_pats[0]);
let new_renames = idents.into_iter().map(|id| (id, fresh_name(&id))).collect();
// apply the renaming, but only to the PatIdents:
let mut rename_pats_fld = PatIdentRenamer{renames:&new_renames};
let rewritten_pats = expanded_pats.move_map(|pat| rename_pats_fld.fold_pat(pat));
// apply renaming and then expansion to the guard and the body:
let mut rename_fld = IdentRenamer{renames:&new_renames};
let rewritten_guard =
arm.guard.map(|g| fld.fold_expr(rename_fld.fold_expr(g)));
let rewritten_body = fld.fold_expr(rename_fld.fold_expr(arm.body));
ast::Arm {
attrs: fold::fold_attrs(arm.attrs, fld),
pats: rewritten_pats,
guard: rewritten_guard,
body: rewritten_body,
}
}
/// A visitor that extracts the PatIdent (binding) paths
/// from a given thingy and puts them in a mutable
/// array
#[derive(Clone)]
struct PatIdentFinder {
ident_accumulator: Vec<ast::Ident>
}
impl<'v> Visitor<'v> for PatIdentFinder {
fn visit_pat(&mut self, pattern: &ast::Pat) {
match *pattern {
ast::Pat { id: _, node: ast::PatIdent(_, ref path1, ref inner), span: _ } => {
self.ident_accumulator.push(path1.node);
// visit optional subpattern of PatIdent:
if let Some(ref subpat) = *inner {
self.visit_pat(&**subpat)
}
}
// use the default traversal for non-PatIdents
_ => visit::walk_pat(self, pattern)
}
}