/
alt.rs
1621 lines (1501 loc) · 56.5 KB
/
alt.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
/*!
*
* # Compilation of match statements
*
* I will endeavor to explain the code as best I can. I have only a loose
* understanding of some parts of it.
*
* ## Matching
*
* The basic state of the code is maintained in an array `m` of `@Match`
* objects. Each `@Match` describes some list of patterns, all of which must
* match against the current list of values. If those patterns match, then
* the arm listed in the match is the correct arm. A given arm may have
* multiple corresponding match entries, one for each alternative that
* remains. As we proceed these sets of matches are adjusted by the various
* `enter_XXX()` functions, each of which adjusts the set of options given
* some information about the value which has been matched.
*
* So, initially, there is one value and N matches, each of which have one
* constituent pattern. N here is usually the number of arms but may be
* greater, if some arms have multiple alternatives. For example, here:
*
* enum Foo { A, B(int), C(uint, uint) }
* match foo {
* A => ...,
* B(x) => ...,
* C(1u, 2) => ...,
* C(_) => ...
* }
*
* The value would be `foo`. There would be four matches, each of which
* contains one pattern (and, in one case, a guard). We could collect the
* various options and then compile the code for the case where `foo` is an
* `A`, a `B`, and a `C`. When we generate the code for `C`, we would (1)
* drop the two matches that do not match a `C` and (2) expand the other two
* into two patterns each. In the first case, the two patterns would be `1u`
* and `2`, and the in the second case the _ pattern would be expanded into
* `_` and `_`. The two values are of course the arguments to `C`.
*
* Here is a quick guide to the various functions:
*
* - `compile_submatch()`: The main workhouse. It takes a list of values and
* a list of matches and finds the various possibilities that could occur.
*
* - `enter_XXX()`: modifies the list of matches based on some information
* about the value that has been matched. For example,
* `enter_rec_or_struct()` adjusts the values given that a record or struct
* has been matched. This is an infallible pattern, so *all* of the matches
* must be either wildcards or record/struct patterns. `enter_opt()`
* handles the fallible cases, and it is correspondingly more complex.
*
* ## Bindings
*
* We store information about the bound variables for each arm as part of the
* per-arm `ArmData` struct. There is a mapping from identifiers to
* `BindingInfo` structs. These structs contain the mode/id/type of the
* binding, but they also contain up to two LLVM values, called `llmatch` and
* `llbinding` respectively (the `llbinding`, as will be described shortly, is
* optional and only present for by-value bindings---therefore it is bundled
* up as part of the `TransBindingMode` type). Both point at allocas.
*
* The `llmatch` binding always stores a pointer into the value being matched
* which points at the data for the binding. If the value being matched has
* type `T`, then, `llmatch` will point at an alloca of type `T*` (and hence
* `llmatch` has type `T**`). So, if you have a pattern like:
*
* let a: A = ...;
* let b: B = ...;
* match (a, b) { (ref c, copy d) => { ... } }
*
* For `c` and `d`, we would generate allocas of type `C*` and `D*`
* respectively. These are called the `llmatch`. As we match, when we come
* up against an identifier, we store the current pointer into the
* corresponding alloca.
*
* In addition, for each by-value binding (copy or move), we will create a
* second alloca (`llbinding`) that will hold the final value. In this
* example, that means that `d` would have this second alloca of type `D` (and
* hence `llbinding` has type `D*`).
*
* Once a pattern is completely matched, and assuming that there is no guard
* pattern, we will branch to a block that leads to the body itself. For any
* by-value bindings, this block will first load the ptr from `llmatch` (the
* one of type `D*`) and copy/move the value into `llbinding` (the one of type
* `D`). The second alloca then becomes the value of the local variable. For
* by ref bindings, the value of the local variable is simply the first
* alloca.
*
* So, for the example above, we would generate a setup kind of like this:
*
* +-------+
* | Entry |
* +-------+
* |
* +-------------------------------------------+
* | llmatch_c = (addr of first half of tuple) |
* | llmatch_d = (addr of first half of tuple) |
* +-------------------------------------------+
* |
* +--------------------------------------+
* | *llbinding_d = **llmatch_dlbinding_d |
* +--------------------------------------+
*
* If there is a guard, the situation is slightly different, because we must
* execute the guard code. Moreover, we need to do so once for each of the
* alternatives that lead to the arm, because if the guard fails, they may
* have different points from which to continue the search. Therefore, in that
* case, we generate code that looks more like:
*
* +-------+
* | Entry |
* +-------+
* |
* +-------------------------------------------+
* | llmatch_c = (addr of first half of tuple) |
* | llmatch_d = (addr of first half of tuple) |
* +-------------------------------------------+
* |
* +-------------------------------------------------+
* | *llbinding_d = **llmatch_dlbinding_d |
* | check condition |
* | if false { free *llbinding_d, goto next case } |
* | if true { goto body } |
* +-------------------------------------------------+
*
* The handling for the cleanups is a bit... sensitive. Basically, the body
* is the one that invokes `add_clean()` for each binding. During the guard
* evaluation, we add temporary cleanups and revoke them after the guard is
* evaluated (it could fail, after all). Presuming the guard fails, we drop
* the various values we copied explicitly. Note that guards and moves are
* just plain incompatible.
*
*/
use lib::llvm::llvm;
use lib::llvm::{ValueRef, BasicBlockRef};
use pat_util::*;
use build::*;
use base::*;
use syntax::ast;
use syntax::ast_util;
use syntax::ast_util::{dummy_sp, path_to_ident};
use syntax::ast::def_id;
use syntax::codemap::span;
use syntax::print::pprust::pat_to_str;
use middle::resolve::DefMap;
use back::abi;
use std::map::HashMap;
use dvec::DVec;
use datum::*;
use common::*;
use expr::Dest;
use util::common::indenter;
fn macros() { include!("macros.rs"); } // FIXME(#3114): Macro import/export.
// An option identifying a literal: either a unit-like struct or an
// expression.
enum Lit {
UnitLikeStructLit(ast::node_id), // the node ID of the pattern
ExprLit(@ast::expr),
ConstLit(ast::def_id), // the def ID of the constant
}
// An option identifying a branch (either a literal, a enum variant or a
// range)
enum Opt {
lit(Lit),
var(/* disr val */int, /* variant dids */{enm: def_id, var: def_id}),
range(@ast::expr, @ast::expr)
}
fn opt_eq(tcx: ty::ctxt, a: &Opt, b: &Opt) -> bool {
match (*a, *b) {
(lit(a), lit(b)) => {
match (a, b) {
(UnitLikeStructLit(a), UnitLikeStructLit(b)) => a == b,
_ => {
let a_expr;
match a {
ExprLit(existing_a_expr) => a_expr = existing_a_expr,
ConstLit(a_const) => {
let e = const_eval::lookup_const_by_id(tcx, a_const);
a_expr = e.get();
}
UnitLikeStructLit(_) => {
fail ~"UnitLikeStructLit should have been handled \
above"
}
}
let b_expr;
match b {
ExprLit(existing_b_expr) => b_expr = existing_b_expr,
ConstLit(b_const) => {
let e = const_eval::lookup_const_by_id(tcx, b_const);
b_expr = e.get();
}
UnitLikeStructLit(_) => {
fail ~"UnitLikeStructLit should have been handled \
above"
}
}
const_eval::compare_lit_exprs(tcx, a_expr, b_expr) == 0
}
}
}
(range(a1, a2), range(b1, b2)) => {
const_eval::compare_lit_exprs(tcx, a1, b1) == 0 &&
const_eval::compare_lit_exprs(tcx, a2, b2) == 0
}
(var(a, _), var(b, _)) => a == b,
_ => false
}
}
enum opt_result {
single_result(Result),
range_result(Result, Result),
}
fn trans_opt(bcx: block, o: &Opt) -> opt_result {
let _icx = bcx.insn_ctxt("alt::trans_opt");
let ccx = bcx.ccx();
let mut bcx = bcx;
match *o {
lit(ExprLit(lit_expr)) => {
let datumblock = expr::trans_to_datum(bcx, lit_expr);
return single_result(datumblock.to_result());
}
lit(UnitLikeStructLit(pat_id)) => {
let struct_ty = ty::node_id_to_type(bcx.tcx(), pat_id);
let datumblock = datum::scratch_datum(bcx, struct_ty, true);
return single_result(datumblock.to_result(bcx));
}
lit(ConstLit(lit_id)) => {
let llval = consts::get_const_val(bcx.ccx(), lit_id);
return single_result(rslt(bcx, llval));
}
var(disr_val, _) => {
return single_result(rslt(bcx, C_int(ccx, disr_val)));
}
range(l1, l2) => {
return range_result(rslt(bcx, consts::const_expr(ccx, l1)),
rslt(bcx, consts::const_expr(ccx, l2)));
}
}
}
fn variant_opt(tcx: ty::ctxt, pat_id: ast::node_id) -> Opt {
match tcx.def_map.get(pat_id) {
ast::def_variant(enum_id, var_id) => {
let variants = ty::enum_variants(tcx, enum_id);
for vec::each(*variants) |v| {
if var_id == v.id {
return var(v.disr_val, {enm: enum_id, var: var_id});
}
}
core::util::unreachable();
}
ast::def_class(_) => {
return lit(UnitLikeStructLit(pat_id));
}
_ => {
tcx.sess.bug(~"non-variant or struct in variant_opt()");
}
}
}
enum TransBindingMode {
TrByValue(/*ismove:*/ bool, /*llbinding:*/ ValueRef),
TrByRef,
TrByImplicitRef
}
/**
* Information about a pattern binding:
* - `llmatch` is a pointer to a stack slot. The stack slot contains a
* pointer into the value being matched. Hence, llmatch has type `T**`
* where `T` is the value being matched.
* - `trmode` is the trans binding mode
* - `id` is the node id of the binding
* - `ty` is the Rust type of the binding */
struct BindingInfo {
llmatch: ValueRef,
trmode: TransBindingMode,
id: ast::node_id,
ty: ty::t,
}
type BindingsMap = HashMap<ident, BindingInfo>;
struct ArmData {
bodycx: block,
arm: &ast::arm,
bindings_map: BindingsMap
}
struct Match {
pats: ~[@ast::pat],
data: @ArmData
}
fn match_to_str(bcx: block, m: &Match) -> ~str {
if bcx.sess().verbose() {
// for many programs, this just take too long to serialize
fmt!("%?", m.pats.map(|p| pat_to_str(*p, bcx.sess().intr())))
} else {
fmt!("%u pats", m.pats.len())
}
}
fn matches_to_str(bcx: block, m: &[@Match]) -> ~str {
fmt!("%?", m.map(|n| match_to_str(bcx, *n)))
}
fn has_nested_bindings(m: &[@Match], col: uint) -> bool {
for vec::each(m) |br| {
match br.pats[col].node {
ast::pat_ident(_, _, Some(_)) => return true,
_ => ()
}
}
return false;
}
fn expand_nested_bindings(bcx: block, m: &[@Match/&r],
col: uint, val: ValueRef)
-> ~[@Match/&r]
{
debug!("expand_nested_bindings(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
do m.map |br| {
match br.pats[col].node {
ast::pat_ident(_, path, Some(inner)) => {
let pats = vec::append(
vec::slice(br.pats, 0u, col),
vec::append(~[inner],
vec::view(br.pats, col + 1u, br.pats.len())));
let binding_info =
br.data.bindings_map.get(path_to_ident(path));
Store(bcx, val, binding_info.llmatch);
@Match {pats: pats, data: br.data}
}
_ => {
*br
}
}
}
}
type enter_pat = fn(@ast::pat) -> Option<~[@ast::pat]>;
fn assert_is_binding_or_wild(bcx: block, p: @ast::pat) {
if !pat_is_binding_or_wild(bcx.tcx().def_map, p) {
bcx.sess().span_bug(
p.span,
fmt!("Expected an identifier pattern but found p: %s",
pat_to_str(p, bcx.sess().intr())));
}
}
fn enter_match(bcx: block, dm: DefMap, m: &[@Match/&r],
col: uint, val: ValueRef, e: enter_pat)
-> ~[@Match/&r]
{
debug!("enter_match(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
let mut result = ~[];
for vec::each(m) |br| {
match e(br.pats[col]) {
Some(sub) => {
let pats =
vec::append(
vec::append(sub, vec::view(br.pats, 0u, col)),
vec::view(br.pats, col + 1u, br.pats.len()));
let self = br.pats[col];
match self.node {
ast::pat_ident(_, path, None) => {
if pat_is_binding(dm, self) {
let binding_info =
br.data.bindings_map.get(path_to_ident(path));
Store(bcx, val, binding_info.llmatch);
}
}
_ => {}
}
result.push(@Match {pats: pats, data: br.data});
}
None => ()
}
}
debug!("result=%s", matches_to_str(bcx, result));
return result;
}
fn enter_default(bcx: block, dm: DefMap, m: &[@Match/&r],
col: uint, val: ValueRef)
-> ~[@Match/&r]
{
debug!("enter_default(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
ast::pat_wild | ast::pat_rec(_, _) | ast::pat_tup(_) |
ast::pat_struct(*) => Some(~[]),
ast::pat_ident(_, _, None) if pat_is_binding(dm, p) => Some(~[]),
_ => None
}
}
}
// <pcwalton> nmatsakis: what does enter_opt do?
// <pcwalton> in trans/alt
// <pcwalton> trans/alt.rs is like stumbling around in a dark cave
// <nmatsakis> pcwalton: the enter family of functions adjust the set of
// patterns as needed
// <nmatsakis> yeah, at some point I kind of achieved some level of
// understanding
// <nmatsakis> anyhow, they adjust the patterns given that something of that
// kind has been found
// <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
// said
// <nmatsakis> enter_match() kind of embodies the generic code
// <nmatsakis> it is provided with a function that tests each pattern to see
// if it might possibly apply and so forth
// <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
// <nmatsakis> then _ would be expanded to (_, _)
// <nmatsakis> one spot for each of the sub-patterns
// <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
// cases
// <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
// are infallible patterns
// <nmatsakis> so all patterns must either be records (resp. tuples) or
// wildcards
fn enter_opt(bcx: block, m: &[@Match/&r], opt: &Opt, col: uint,
variant_size: uint, val: ValueRef)
-> ~[@Match/&r]
{
debug!("enter_opt(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
let tcx = bcx.tcx();
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, tcx.def_map, m, col, val) |p| {
match p.node {
ast::pat_enum(_, subpats) => {
if opt_eq(tcx, &variant_opt(tcx, p.id), opt) {
Some(option::get_default(subpats,
vec::from_elem(variant_size,
dummy)))
} else {
None
}
}
ast::pat_ident(_, _, None)
if pat_is_variant_or_struct(tcx.def_map, p) => {
if opt_eq(tcx, &variant_opt(tcx, p.id), opt) {
Some(~[])
} else {
None
}
}
ast::pat_ident(_, _, None) if pat_is_const(tcx.def_map, p) => {
let const_def = tcx.def_map.get(p.id);
let const_def_id = ast_util::def_id_of_def(const_def);
if opt_eq(tcx, &lit(ConstLit(const_def_id)), opt) {
Some(~[])
} else {
None
}
}
ast::pat_lit(l) => {
if opt_eq(tcx, &lit(ExprLit(l)), opt) {Some(~[])} else {None}
}
ast::pat_range(l1, l2) => {
if opt_eq(tcx, &range(l1, l2), opt) {Some(~[])} else {None}
}
ast::pat_struct(_, field_pats, _) => {
if opt_eq(tcx, &variant_opt(tcx, p.id), opt) {
// Look up the struct variant ID.
let struct_id;
match tcx.def_map.get(p.id) {
ast::def_variant(_, found_struct_id) => {
struct_id = found_struct_id;
}
_ => {
tcx.sess.span_bug(p.span, ~"expected enum \
variant def");
}
}
// Reorder the patterns into the same order they were
// specified in the struct definition. Also fill in
// unspecified fields with dummy.
let reordered_patterns = dvec::DVec();
for ty::lookup_class_fields(tcx, struct_id).each |field| {
match field_pats.find(|p| p.ident == field.ident) {
None => reordered_patterns.push(dummy),
Some(fp) => reordered_patterns.push(fp.pat)
}
}
Some(dvec::unwrap(move reordered_patterns))
} else {
None
}
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(vec::from_elem(variant_size, dummy))
}
}
}
}
fn enter_rec_or_struct(bcx: block, dm: DefMap, m: &[@Match/&r], col: uint,
fields: ~[ast::ident], val: ValueRef) -> ~[@Match/&r] {
debug!("enter_rec_or_struct(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
ast::pat_rec(fpats, _) | ast::pat_struct(_, fpats, _) => {
let mut pats = ~[];
for vec::each(fields) |fname| {
match fpats.find(|p| p.ident == *fname) {
None => pats.push(dummy),
Some(pat) => pats.push(pat.pat)
}
}
Some(pats)
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(vec::from_elem(fields.len(), dummy))
}
}
}
}
fn enter_tup(bcx: block, dm: DefMap, m: &[@Match/&r],
col: uint, val: ValueRef, n_elts: uint)
-> ~[@Match/&r]
{
debug!("enter_tup(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
ast::pat_tup(elts) => {
Some(elts)
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(vec::from_elem(n_elts, dummy))
}
}
}
}
fn enter_tuple_struct(bcx: block, dm: DefMap, m: &[@Match/&r], col: uint,
val: ValueRef, n_elts: uint)
-> ~[@Match/&r]
{
debug!("enter_tuple_struct(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
ast::pat_enum(_, Some(elts)) => Some(elts),
_ => {
assert_is_binding_or_wild(bcx, p);
Some(vec::from_elem(n_elts, dummy))
}
}
}
}
fn enter_box(bcx: block, dm: DefMap, m: &[@Match/&r],
col: uint, val: ValueRef)
-> ~[@Match/&r]
{
debug!("enter_box(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
ast::pat_box(sub) => {
Some(~[sub])
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(~[dummy])
}
}
}
}
fn enter_uniq(bcx: block, dm: DefMap, m: &[@Match/&r],
col: uint, val: ValueRef)
-> ~[@Match/&r]
{
debug!("enter_uniq(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
ast::pat_uniq(sub) => {
Some(~[sub])
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(~[dummy])
}
}
}
}
fn enter_region(bcx: block, dm: DefMap, m: &[@Match/&r],
col: uint, val: ValueRef)
-> ~[@Match/&r]
{
debug!("enter_region(bcx=%s, m=%s, col=%u, val=%?)",
bcx.to_str(),
matches_to_str(bcx, m),
col,
bcx.val_str(val));
let _indenter = indenter();
let dummy = @{id: 0, node: ast::pat_wild, span: dummy_sp()};
do enter_match(bcx, dm, m, col, val) |p| {
match p.node {
ast::pat_region(sub) => {
Some(~[sub])
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(~[dummy])
}
}
}
}
// Returns the options in one column of matches. An option is something that
// needs to be conditionally matched at runtime; for example, the discriminant
// on a set of enum variants or a literal.
fn get_options(ccx: @crate_ctxt, m: &[@Match], col: uint) -> ~[Opt] {
fn add_to_set(tcx: ty::ctxt, set: &DVec<Opt>, val: Opt) {
if set.any(|l| opt_eq(tcx, l, &val)) {return;}
set.push(val);
}
let found = DVec();
for vec::each(m) |br| {
let cur = br.pats[col];
match cur.node {
ast::pat_lit(l) => {
add_to_set(ccx.tcx, &found, lit(ExprLit(l)));
}
ast::pat_ident(*) => {
// This is one of: an enum variant, a unit-like struct, or a
// variable binding.
match ccx.tcx.def_map.find(cur.id) {
Some(ast::def_variant(*)) => {
add_to_set(ccx.tcx, &found,
variant_opt(ccx.tcx, cur.id));
}
Some(ast::def_class(*)) => {
add_to_set(ccx.tcx, &found,
lit(UnitLikeStructLit(cur.id)));
}
Some(ast::def_const(const_did)) => {
add_to_set(ccx.tcx, &found,
lit(ConstLit(const_did)));
}
_ => {}
}
}
ast::pat_enum(*) | ast::pat_struct(*) => {
// This could be one of: a tuple-like enum variant, a
// struct-like enum variant, or a struct.
match ccx.tcx.def_map.find(cur.id) {
Some(ast::def_variant(*)) => {
add_to_set(ccx.tcx, &found,
variant_opt(ccx.tcx, cur.id));
}
_ => {}
}
}
ast::pat_range(l1, l2) => {
add_to_set(ccx.tcx, &found, range(l1, l2));
}
_ => {}
}
}
return dvec::unwrap(move found);
}
fn extract_variant_args(bcx: block, pat_id: ast::node_id,
vdefs: {enm: def_id, var: def_id},
val: ValueRef)
-> {vals: ~[ValueRef], bcx: block}
{
let _icx = bcx.insn_ctxt("alt::extract_variant_args");
let ccx = bcx.fcx.ccx;
let enum_ty_substs = match ty::get(node_id_type(bcx, pat_id)).sty {
ty::ty_enum(id, substs) => { assert id == vdefs.enm; substs.tps }
_ => bcx.sess().bug(~"extract_variant_args: pattern has non-enum type")
};
let mut blobptr = val;
let variants = ty::enum_variants(ccx.tcx, vdefs.enm);
let size = ty::enum_variant_with_id(ccx.tcx, vdefs.enm,
vdefs.var).args.len();
if size > 0u && (*variants).len() != 1u {
let enumptr =
PointerCast(bcx, val, T_opaque_enum_ptr(ccx));
blobptr = GEPi(bcx, enumptr, [0u, 1u]);
}
let vdefs_tg = vdefs.enm;
let vdefs_var = vdefs.var;
let args = do vec::from_fn(size) |i| {
GEP_enum(bcx, blobptr, vdefs_tg, vdefs_var,
enum_ty_substs, i)
};
return {vals: args, bcx: bcx};
}
// NB: This function does not collect fields from struct-like enum variants.
fn collect_record_or_struct_fields(bcx: block, m: &[@Match], col: uint) ->
~[ast::ident] {
let mut fields: ~[ast::ident] = ~[];
for vec::each(m) |br| {
match br.pats[col].node {
ast::pat_rec(fs, _) => extend(&mut fields, fs),
ast::pat_struct(_, fs, _) => {
match ty::get(node_id_type(bcx, br.pats[col].id)).sty {
ty::ty_class(*) => extend(&mut fields, fs),
_ => ()
}
}
_ => ()
}
}
return fields;
fn extend(idents: &mut ~[ast::ident], field_pats: &[ast::field_pat]) {
for field_pats.each |field_pat| {
let field_ident = field_pat.ident;
if !vec::any(*idents, |x| *x == field_ident) {
idents.push(field_ident);
}
}
}
}
fn root_pats_as_necessary(bcx: block, m: &[@Match],
col: uint, val: ValueRef)
{
for vec::each(m) |br| {
let pat_id = br.pats[col].id;
match bcx.ccx().maps.root_map.find({id:pat_id, derefs:0u}) {
None => (),
Some(scope_id) => {
// Note: the scope_id will always be the id of the alt. See
// the extended comment in rustc::middle::borrowck::preserve()
// for details (look for the case covering cat_discr).
let datum = Datum {val: val, ty: node_id_type(bcx, pat_id),
mode: ByRef, source: FromLvalue};
datum.root(bcx, scope_id);
return; // if we kept going, we'd only re-root the same value
}
}
}
}
// Macro for deciding whether any of the remaining matches fit a given kind of
// pattern. Note that, because the macro is well-typed, either ALL of the
// matches should fit that sort of pattern or NONE (however, some of the
// matches may be wildcards like _ or identifiers).
macro_rules! any_pat (
($m:expr, $pattern:pat) => (
vec::any($m, |br| {
match br.pats[col].node {
$pattern => true,
_ => false
}
})
)
)
fn any_box_pat(m: &[@Match], col: uint) -> bool {
any_pat!(m, ast::pat_box(_))
}
fn any_uniq_pat(m: &[@Match], col: uint) -> bool {
any_pat!(m, ast::pat_uniq(_))
}
fn any_region_pat(m: &[@Match], col: uint) -> bool {
any_pat!(m, ast::pat_region(_))
}
fn any_tup_pat(m: &[@Match], col: uint) -> bool {
any_pat!(m, ast::pat_tup(_))
}
fn any_tuple_struct_pat(bcx: block, m: &[@Match], col: uint) -> bool {
vec::any(m, |br| {
let pat = br.pats[col];
match pat.node {
ast::pat_enum(_, Some(_)) => {
match bcx.tcx().def_map.find(pat.id) {
Some(ast::def_class(*)) => true,
_ => false
}
}
_ => false
}
})
}
type mk_fail = fn@() -> BasicBlockRef;
fn pick_col(m: &[@Match]) -> uint {
fn score(p: @ast::pat) -> uint {
match p.node {
ast::pat_lit(_) | ast::pat_enum(_, _) | ast::pat_range(_, _) => 1u,
ast::pat_ident(_, _, Some(p)) => score(p),
_ => 0u
}
}
let scores = vec::to_mut(vec::from_elem(m[0].pats.len(), 0u));
for vec::each(m) |br| {
let mut i = 0u;
for vec::each(br.pats) |p| { scores[i] += score(*p); i += 1u; }
}
let mut max_score = 0u;
let mut best_col = 0u;
let mut i = 0u;
for vec::each(scores) |score| {
let score = *score;
// Irrefutable columns always go first, they'd only be duplicated in
// the branches.
if score == 0u { return i; }
// If no irrefutable ones are found, we pick the one with the biggest
// branching factor.
if score > max_score { max_score = score; best_col = i; }
i += 1u;
}
return best_col;
}
enum branch_kind { no_branch, single, switch, compare, }
impl branch_kind : cmp::Eq {
pure fn eq(&self, other: &branch_kind) -> bool {
((*self) as uint) == ((*other) as uint)
}
pure fn ne(&self, other: &branch_kind) -> bool { !(*self).eq(other) }
}
// Compiles a comparison between two things.
fn compare_values(cx: block, lhs: ValueRef, rhs: ValueRef, rhs_t: ty::t) ->
Result {
let _icx = cx.insn_ctxt("compare_values");
if ty::type_is_scalar(rhs_t) {
let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::eq);
return rslt(rs.bcx, rs.val);
}
match ty::get(rhs_t).sty {
ty::ty_estr(ty::vstore_uniq) => {
let scratch_result = scratch_datum(cx, ty::mk_bool(cx.tcx()),
false);
let scratch_lhs = alloca(cx, val_ty(lhs));
Store(cx, lhs, scratch_lhs);
let scratch_rhs = alloca(cx, val_ty(rhs));
Store(cx, rhs, scratch_rhs);
let did = cx.tcx().lang_items.uniq_str_eq_fn.get();
let bcx = callee::trans_rtcall_or_lang_call(cx, did,
~[scratch_lhs,
scratch_rhs],
expr::SaveIn(
scratch_result.val));
return scratch_result.to_result(bcx);
}
_ => {
cx.tcx().sess.bug(~"only scalars and unique strings supported in \
compare_values");
}
}
}
fn store_non_ref_bindings(bcx: block,
data: &ArmData,
opt_temp_cleanups: Option<&DVec<ValueRef>>)
-> block
{
/*!
*
* For each copy/move binding, copy the value from the value
* being matched into its final home. This code executes once
* one of the patterns for a given arm has completely matched.
* It adds temporary cleanups to the `temp_cleanups` array,
* if one is provided.
*/
let mut bcx = bcx;
for data.bindings_map.each_value |binding_info| {
match binding_info.trmode {
TrByValue(is_move, lldest) => {
let llval = Load(bcx, binding_info.llmatch); // get a T*
let datum = Datum {val: llval, ty: binding_info.ty,
mode: ByRef, source: FromLvalue};
bcx = {
if is_move {
datum.move_to(bcx, INIT, lldest)
} else {
datum.copy_to(bcx, INIT, lldest)
}
};
for opt_temp_cleanups.each |temp_cleanups| {
add_clean_temp_mem(bcx, lldest, binding_info.ty);
temp_cleanups.push(lldest);
}
}
TrByRef | TrByImplicitRef => {}
}
}
return bcx;
}
fn insert_lllocals(bcx: block,
data: &ArmData,
add_cleans: bool) -> block {
/*!
*
* For each binding in `data.bindings_map`, adds an appropriate entry into
* the `fcx.lllocals` map. If add_cleans is true, then adds cleanups for
* the bindings. */
for data.bindings_map.each_value |binding_info| {
let llval = match binding_info.trmode {
// By value bindings: use the stack slot that we
// copied/moved the value into