/
_match.rs
2297 lines (2145 loc) · 85.3 KB
/
_match.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.
/*!
*
* # 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, 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.
*
* Some relevant helper functions that manage bindings:
* - `create_bindings_map()`
* - `store_non_ref_bindings()`
* - `insert_lllocals()`
*
*
* ## Notes on vector pattern matching.
*
* Vector pattern matching is surprisingly tricky. The problem is that
* the structure of the vector isn't fully known, and slice matches
* can be done on subparts of it.
*
* The way that vector pattern matches are dealt with, then, is as
* follows. First, we make the actual condition associated with a
* vector pattern simply a vector length comparison. So the pattern
* [1, .. x] gets the condition "vec len >= 1", and the pattern
* [.. x] gets the condition "vec len >= 0". The problem here is that
* having the condition "vec len >= 1" hold clearly does not mean that
* only a pattern that has exactly that condition will match. This
* means that it may well be the case that a condition holds, but none
* of the patterns matching that condition match; to deal with this,
* when doing vector length matches, we have match failures proceed to
* the next condition to check.
*
* There are a couple more subtleties to deal with. While the "actual"
* condition associated with vector length tests is simply a test on
* the vector length, the actual vec_len Opt entry contains more
* information used to restrict which matches are associated with it.
* So that all matches in a submatch are matching against the same
* values from inside the vector, they are split up by how many
* elements they match at the front and at the back of the vector. In
* order to make sure that arms are properly checked in order, even
* with the overmatching conditions, each vec_len Opt entry is
* associated with a range of matches.
* Consider the following:
*
* match &[1, 2, 3] {
* [1, 1, .. _] => 0,
* [1, 2, 2, .. _] => 1,
* [1, 2, 3, .. _] => 2,
* [1, 2, .. _] => 3,
* _ => 4
* }
* The proper arm to match is arm 2, but arms 0 and 3 both have the
* condition "len >= 2". If arm 3 was lumped in with arm 0, then the
* wrong branch would be taken. Instead, vec_len Opts are associated
* with a contiguous range of matches that have the same "shape".
* This is sort of ugly and requires a bunch of special handling of
* vec_len options.
*
*/
#![allow(non_camel_case_types)]
use back::abi;
use driver::session::FullDebugInfo;
use lib::llvm::{llvm, ValueRef, BasicBlockRef};
use middle::const_eval;
use middle::borrowck::root_map_key;
use middle::lang_items::{UniqStrEqFnLangItem, StrEqFnLangItem};
use middle::pat_util::*;
use middle::resolve::DefMap;
use middle::trans::adt;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::cleanup;
use middle::trans::cleanup::CleanupMethods;
use middle::trans::common::*;
use middle::trans::consts;
use middle::trans::controlflow;
use middle::trans::datum;
use middle::trans::datum::*;
use middle::trans::expr::Dest;
use middle::trans::expr;
use middle::trans::glue;
use middle::trans::tvec;
use middle::trans::type_of;
use middle::trans::debuginfo;
use middle::ty;
use util::common::indenter;
use util::ppaux::{Repr, vec_map_to_str};
use collections::HashMap;
use std::cell::Cell;
use std::rc::Rc;
use syntax::ast;
use syntax::ast::Ident;
use syntax::ast_util::path_to_ident;
use syntax::ast_util;
use syntax::codemap::{Span, DUMMY_SP};
use syntax::parse::token::InternedString;
// An option identifying a literal: either a unit-like struct or an
// expression.
enum Lit {
UnitLikeStructLit(ast::NodeId), // the node ID of the pattern
ExprLit(@ast::Expr),
ConstLit(ast::DefId), // the def ID of the constant
}
#[deriving(Eq)]
pub enum VecLenOpt {
vec_len_eq,
vec_len_ge(/* length of prefix */uint)
}
// An option identifying a branch (either a literal, an enum variant or a
// range)
enum Opt {
lit(Lit),
var(ty::Disr, Rc<adt::Repr>),
range(@ast::Expr, @ast::Expr),
vec_len(/* length */ uint, VecLenOpt, /*range of matches*/(uint, uint))
}
fn lit_to_expr(tcx: &ty::ctxt, a: &Lit) -> @ast::Expr {
match *a {
ExprLit(existing_a_expr) => existing_a_expr,
ConstLit(a_const) => const_eval::lookup_const_by_id(tcx, a_const).unwrap(),
UnitLikeStructLit(_) => fail!("lit_to_expr: unexpected struct lit"),
}
}
fn opt_eq(tcx: &ty::ctxt, a: &Opt, b: &Opt) -> bool {
match (a, b) {
(&lit(UnitLikeStructLit(a)), &lit(UnitLikeStructLit(b))) => a == b,
(&lit(a), &lit(b)) => {
let a_expr = lit_to_expr(tcx, &a);
let b_expr = lit_to_expr(tcx, &b);
match const_eval::compare_lit_exprs(tcx, a_expr, b_expr) {
Some(val1) => val1 == 0,
None => fail!("compare_list_exprs: type mismatch"),
}
}
(&range(a1, a2), &range(b1, b2)) => {
let m1 = const_eval::compare_lit_exprs(tcx, a1, b1);
let m2 = const_eval::compare_lit_exprs(tcx, a2, b2);
match (m1, m2) {
(Some(val1), Some(val2)) => (val1 == 0 && val2 == 0),
_ => fail!("compare_list_exprs: type mismatch"),
}
}
(&var(a, _), &var(b, _)) => a == b,
(&vec_len(a1, a2, _), &vec_len(b1, b2, _)) =>
a1 == b1 && a2 == b2,
_ => false
}
}
fn opt_overlap(tcx: &ty::ctxt, a: &Opt, b: &Opt) -> bool {
match (a, b) {
(&lit(a), &lit(b)) => {
let a_expr = lit_to_expr(tcx, &a);
let b_expr = lit_to_expr(tcx, &b);
match const_eval::compare_lit_exprs(tcx, a_expr, b_expr) {
Some(val1) => val1 == 0,
None => fail!("opt_overlap: type mismatch"),
}
}
(&range(a1, a2), &range(b1, b2)) => {
let m1 = const_eval::compare_lit_exprs(tcx, a1, b2);
let m2 = const_eval::compare_lit_exprs(tcx, b1, a2);
match (m1, m2) {
// two ranges [a1, a2] and [b1, b2] overlap iff:
// a1 <= b2 && b1 <= a2
(Some(val1), Some(val2)) => (val1 <= 0 && val2 <= 0),
_ => fail!("opt_overlap: type mismatch"),
}
}
(&range(a1, a2), &lit(b)) | (&lit(b), &range(a1, a2)) => {
let b_expr = lit_to_expr(tcx, &b);
let m1 = const_eval::compare_lit_exprs(tcx, a1, b_expr);
let m2 = const_eval::compare_lit_exprs(tcx, a2, b_expr);
match (m1, m2) {
// b is in range [a1, a2] iff a1 <= b and b <= a2
(Some(val1), Some(val2)) => (val1 <= 0 && 0 <= val2),
_ => fail!("opt_overlap: type mismatch"),
}
}
_ => fail!("opt_overlap: expect lit or range")
}
}
pub enum opt_result<'a> {
single_result(Result<'a>),
lower_bound(Result<'a>),
range_result(Result<'a>, Result<'a>),
}
fn trans_opt<'a>(bcx: &'a Block<'a>, o: &Opt) -> opt_result<'a> {
let _icx = push_ctxt("match::trans_opt");
let ccx = bcx.ccx();
let mut bcx = bcx;
match *o {
lit(ExprLit(lit_expr)) => {
let lit_datum = unpack_datum!(bcx, expr::trans(bcx, lit_expr));
let lit_datum = lit_datum.assert_rvalue(bcx); // literals are rvalues
let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
return single_result(rslt(bcx, lit_datum.val));
}
lit(UnitLikeStructLit(pat_id)) => {
let struct_ty = ty::node_id_to_type(bcx.tcx(), pat_id);
let datum = datum::rvalue_scratch_datum(bcx, struct_ty, "");
return single_result(rslt(bcx, datum.val));
}
lit(ConstLit(lit_id)) => {
let (llval, _) = consts::get_const_val(bcx.ccx(), lit_id);
return single_result(rslt(bcx, llval));
}
var(disr_val, ref repr) => {
return adt::trans_case(bcx, &**repr, disr_val);
}
range(l1, l2) => {
let (l1, _) = consts::const_expr(ccx, l1, true);
let (l2, _) = consts::const_expr(ccx, l2, true);
return range_result(rslt(bcx, l1), rslt(bcx, l2));
}
vec_len(n, vec_len_eq, _) => {
return single_result(rslt(bcx, C_int(ccx, n as int)));
}
vec_len(n, vec_len_ge(_), _) => {
return lower_bound(rslt(bcx, C_int(ccx, n as int)));
}
}
}
fn variant_opt(bcx: &Block, pat_id: ast::NodeId) -> Opt {
let ccx = bcx.ccx();
let def = ccx.tcx.def_map.borrow().get_copy(&pat_id);
match def {
ast::DefVariant(enum_id, var_id, _) => {
let variants = ty::enum_variants(ccx.tcx(), enum_id);
for v in (*variants).iter() {
if var_id == v.id {
return var(v.disr_val,
adt::represent_node(bcx, pat_id))
}
}
unreachable!();
}
ast::DefFn(..) |
ast::DefStruct(_) => {
return lit(UnitLikeStructLit(pat_id));
}
_ => {
ccx.sess().bug("non-variant or struct in variant_opt()");
}
}
}
#[deriving(Clone)]
enum TransBindingMode {
TrByValue(/*llbinding:*/ ValueRef),
TrByRef,
}
/**
* 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 */
#[deriving(Clone)]
struct BindingInfo {
llmatch: ValueRef,
trmode: TransBindingMode,
id: ast::NodeId,
span: Span,
ty: ty::t,
}
type BindingsMap = HashMap<Ident, BindingInfo>;
struct ArmData<'a, 'b> {
bodycx: &'b Block<'b>,
arm: &'a ast::Arm,
bindings_map: BindingsMap
}
/**
* Info about Match.
* If all `pats` are matched then arm `data` will be executed.
* As we proceed `bound_ptrs` are filled with pointers to values to be bound,
* these pointers are stored in llmatch variables just before executing `data` arm.
*/
struct Match<'a, 'b> {
pats: Vec<@ast::Pat>,
data: &'a ArmData<'a, 'b>,
bound_ptrs: Vec<(Ident, ValueRef)>
}
impl<'a, 'b> Repr for Match<'a, 'b> {
fn repr(&self, tcx: &ty::ctxt) -> ~str {
if tcx.sess.verbose() {
// for many programs, this just take too long to serialize
self.pats.repr(tcx)
} else {
format!("{} pats", self.pats.len())
}
}
}
fn has_nested_bindings(m: &[Match], col: uint) -> bool {
for br in m.iter() {
match br.pats.get(col).node {
ast::PatIdent(_, _, Some(_)) => return true,
_ => ()
}
}
return false;
}
fn expand_nested_bindings<'a, 'b>(
bcx: &'b Block<'b>,
m: &'a [Match<'a, 'b>],
col: uint,
val: ValueRef)
-> Vec<Match<'a, 'b>> {
debug!("expand_nested_bindings(bcx={}, m={}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
col,
bcx.val_to_str(val));
let _indenter = indenter();
m.iter().map(|br| {
match br.pats.get(col).node {
ast::PatIdent(_, ref path, Some(inner)) => {
let pats = Vec::from_slice(br.pats.slice(0u, col))
.append((vec!(inner))
.append(br.pats.slice(col + 1u, br.pats.len())).as_slice());
let mut bound_ptrs = br.bound_ptrs.clone();
bound_ptrs.push((path_to_ident(path), val));
Match {
pats: pats,
data: &*br.data,
bound_ptrs: bound_ptrs
}
}
_ => Match {
pats: br.pats.clone(),
data: &*br.data,
bound_ptrs: br.bound_ptrs.clone()
}
}
}).collect()
}
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,
format!("expected an identifier pattern but found p: {}",
p.repr(bcx.tcx())));
}
}
type enter_pat<'a> = |@ast::Pat|: 'a -> Option<Vec<@ast::Pat>>;
fn enter_match<'a, 'b>(
bcx: &'b Block<'b>,
dm: &DefMap,
m: &'a [Match<'a, 'b>],
col: uint,
val: ValueRef,
e: enter_pat)
-> Vec<Match<'a, 'b>> {
debug!("enter_match(bcx={}, m={}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
col,
bcx.val_to_str(val));
let _indenter = indenter();
m.iter().filter_map(|br| {
e(*br.pats.get(col)).map(|sub| {
let pats = sub.append(br.pats.slice(0u, col))
.append(br.pats.slice(col + 1u, br.pats.len()));
let this = *br.pats.get(col);
let mut bound_ptrs = br.bound_ptrs.clone();
match this.node {
ast::PatIdent(_, ref path, None) => {
if pat_is_binding(dm, this) {
bound_ptrs.push((path_to_ident(path), val));
}
}
_ => {}
}
Match {
pats: pats,
data: br.data,
bound_ptrs: bound_ptrs
}
})
}).collect()
}
fn enter_default<'a, 'b>(
bcx: &'b Block<'b>,
dm: &DefMap,
m: &'a [Match<'a, 'b>],
col: uint,
val: ValueRef,
chk: &FailureHandler)
-> Vec<Match<'a, 'b>> {
debug!("enter_default(bcx={}, m={}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
col,
bcx.val_to_str(val));
let _indenter = indenter();
// Collect all of the matches that can match against anything.
let matches = enter_match(bcx, dm, m, col, val, |p| {
match p.node {
ast::PatWild | ast::PatWildMulti | ast::PatTup(_) => Some(Vec::new()),
ast::PatIdent(_, _, None) if pat_is_binding(dm, p) => Some(Vec::new()),
_ => None
}
});
// Ok, now, this is pretty subtle. A "default" match is a match
// that needs to be considered if none of the actual checks on the
// value being considered succeed. The subtlety lies in that sometimes
// identifier/wildcard matches are *not* default matches. Consider:
// "match x { _ if something => foo, true => bar, false => baz }".
// There is a wildcard match, but it is *not* a default case. The boolean
// case on the value being considered is exhaustive. If the case is
// exhaustive, then there are no defaults.
//
// We detect whether the case is exhaustive in the following
// somewhat kludgy way: if the last wildcard/binding match has a
// guard, then by non-redundancy, we know that there aren't any
// non guarded matches, and thus by exhaustiveness, we know that
// we don't need any default cases. If the check *isn't* nonexhaustive
// (because chk is Some), then we need the defaults anyways.
let is_exhaustive = match matches.last() {
Some(m) if m.data.arm.guard.is_some() && chk.is_infallible() => true,
_ => false
};
if is_exhaustive { Vec::new() } else { matches }
}
// <pcwalton> nmatsakis: what does enter_opt do?
// <pcwalton> in trans/match
// <pcwalton> trans/match.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<'a, 'b>(
bcx: &'b Block<'b>,
m: &'a [Match<'a, 'b>],
opt: &Opt,
col: uint,
variant_size: uint,
val: ValueRef)
-> Vec<Match<'a, 'b>> {
debug!("enter_opt(bcx={}, m={}, opt={:?}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
*opt,
col,
bcx.val_to_str(val));
let _indenter = indenter();
let tcx = bcx.tcx();
let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
let mut i = 0;
// By the virtue of fact that we are in `trans` already, `enter_opt` is able
// to prune sub-match tree aggressively based on exact equality. But when it
// comes to literal or range, that strategy may lead to wrong result if there
// are guard function or multiple patterns inside tuple; in that case, pruning
// based on the overlap of patterns is required.
//
// Ideally, when constructing the sub-match tree for certain arm, only those
// arms beneath it matter. But that isn't how algorithm works right now and
// all other arms are taken into consideration when computing `guarded` below.
// That is ok since each round of `compile_submatch` guarantees to trim one
// "column" of arm patterns and the algorithm will converge.
let guarded = m.iter().any(|x| x.data.arm.guard.is_some());
let multi_pats = m.len() > 0 && m[0].pats.len() > 1;
enter_match(bcx, &tcx.def_map, m, col, val, |p| {
let answer = match p.node {
ast::PatEnum(..) |
ast::PatIdent(_, _, None) if pat_is_const(&tcx.def_map, p) => {
let const_def = tcx.def_map.borrow().get_copy(&p.id);
let const_def_id = ast_util::def_id_of_def(const_def);
let konst = lit(ConstLit(const_def_id));
match guarded || multi_pats {
false if opt_eq(tcx, &konst, opt) => Some(Vec::new()),
true if opt_overlap(tcx, &konst, opt) => Some(Vec::new()),
_ => None,
}
}
ast::PatEnum(_, ref subpats) => {
if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
// FIXME: Must we clone?
match *subpats {
None => Some(Vec::from_elem(variant_size, dummy)),
Some(ref subpats) => {
Some((*subpats).iter().map(|x| *x).collect())
}
}
} else {
None
}
}
ast::PatIdent(_, _, None)
if pat_is_variant_or_struct(&tcx.def_map, p) => {
if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
Some(Vec::new())
} else {
None
}
}
ast::PatLit(l) => {
let lit_expr = lit(ExprLit(l));
match guarded || multi_pats {
false if opt_eq(tcx, &lit_expr, opt) => Some(Vec::new()),
true if opt_overlap(tcx, &lit_expr, opt) => Some(Vec::new()),
_ => None,
}
}
ast::PatRange(l1, l2) => {
let rng = range(l1, l2);
match guarded || multi_pats {
false if opt_eq(tcx, &rng, opt) => Some(Vec::new()),
true if opt_overlap(tcx, &rng, opt) => Some(Vec::new()),
_ => None,
}
}
ast::PatStruct(_, ref field_pats, _) => {
if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
// Look up the struct variant ID.
let struct_id;
match tcx.def_map.borrow().get_copy(&p.id) {
ast::DefVariant(_, 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 mut reordered_patterns = Vec::new();
let r = ty::lookup_struct_fields(tcx, struct_id);
for field in r.iter() {
match field_pats.iter().find(|p| p.ident.name
== field.name) {
None => reordered_patterns.push(dummy),
Some(fp) => reordered_patterns.push(fp.pat)
}
}
Some(reordered_patterns)
} else {
None
}
}
ast::PatVec(ref before, slice, ref after) => {
let (lo, hi) = match *opt {
vec_len(_, _, (lo, hi)) => (lo, hi),
_ => tcx.sess.span_bug(p.span,
"vec pattern but not vec opt")
};
match slice {
Some(slice) if i >= lo && i <= hi => {
let n = before.len() + after.len();
let this_opt = vec_len(n, vec_len_ge(before.len()),
(lo, hi));
if opt_eq(tcx, &this_opt, opt) {
let mut new_before = Vec::new();
for pat in before.iter() {
new_before.push(*pat);
}
new_before.push(slice);
for pat in after.iter() {
new_before.push(*pat);
}
Some(new_before)
} else {
None
}
}
None if i >= lo && i <= hi => {
let n = before.len();
if opt_eq(tcx, &vec_len(n, vec_len_eq, (lo,hi)), opt) {
let mut new_before = Vec::new();
for pat in before.iter() {
new_before.push(*pat);
}
Some(new_before)
} else {
None
}
}
_ => None
}
}
_ => {
assert_is_binding_or_wild(bcx, p);
// In most cases, a binding/wildcard match be
// considered to match against any Opt. However, when
// doing vector pattern matching, submatches are
// considered even if the eventual match might be from
// a different submatch. Thus, when a submatch fails
// when doing a vector match, we proceed to the next
// submatch. Thus, including a default match would
// cause the default match to fire spuriously.
match *opt {
vec_len(..) => None,
_ => Some(Vec::from_elem(variant_size, dummy))
}
}
};
i += 1;
answer
})
}
fn enter_rec_or_struct<'a, 'b>(
bcx: &'b Block<'b>,
dm: &DefMap,
m: &'a [Match<'a, 'b>],
col: uint,
fields: &[ast::Ident],
val: ValueRef)
-> Vec<Match<'a, 'b>> {
debug!("enter_rec_or_struct(bcx={}, m={}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
col,
bcx.val_to_str(val));
let _indenter = indenter();
let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
enter_match(bcx, dm, m, col, val, |p| {
match p.node {
ast::PatStruct(_, ref fpats, _) => {
let mut pats = Vec::new();
for fname in fields.iter() {
match fpats.iter().find(|p| p.ident.name == fname.name) {
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<'a, 'b>(
bcx: &'b Block<'b>,
dm: &DefMap,
m: &'a [Match<'a, 'b>],
col: uint,
val: ValueRef,
n_elts: uint)
-> Vec<Match<'a, 'b>> {
debug!("enter_tup(bcx={}, m={}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
col,
bcx.val_to_str(val));
let _indenter = indenter();
let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
enter_match(bcx, dm, m, col, val, |p| {
match p.node {
ast::PatTup(ref elts) => {
let mut new_elts = Vec::new();
for elt in elts.iter() {
new_elts.push((*elt).clone())
}
Some(new_elts)
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(Vec::from_elem(n_elts, dummy))
}
}
})
}
fn enter_tuple_struct<'a, 'b>(
bcx: &'b Block<'b>,
dm: &DefMap,
m: &'a [Match<'a, 'b>],
col: uint,
val: ValueRef,
n_elts: uint)
-> Vec<Match<'a, 'b>> {
debug!("enter_tuple_struct(bcx={}, m={}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
col,
bcx.val_to_str(val));
let _indenter = indenter();
let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
enter_match(bcx, dm, m, col, val, |p| {
match p.node {
ast::PatEnum(_, Some(ref elts)) => {
Some(elts.iter().map(|x| (*x)).collect())
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(Vec::from_elem(n_elts, dummy))
}
}
})
}
fn enter_uniq<'a, 'b>(
bcx: &'b Block<'b>,
dm: &DefMap,
m: &'a [Match<'a, 'b>],
col: uint,
val: ValueRef)
-> Vec<Match<'a, 'b>> {
debug!("enter_uniq(bcx={}, m={}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
col,
bcx.val_to_str(val));
let _indenter = indenter();
let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: DUMMY_SP};
enter_match(bcx, dm, m, col, val, |p| {
match p.node {
ast::PatUniq(sub) => {
Some(vec!(sub))
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(vec!(dummy))
}
}
})
}
fn enter_region<'a, 'b>(
bcx: &'b Block<'b>,
dm: &DefMap,
m: &'a [Match<'a, 'b>],
col: uint,
val: ValueRef)
-> Vec<Match<'a, 'b>> {
debug!("enter_region(bcx={}, m={}, col={}, val={})",
bcx.to_str(),
m.repr(bcx.tcx()),
col,
bcx.val_to_str(val));
let _indenter = indenter();
let dummy = @ast::Pat { id: 0, node: ast::PatWild, span: DUMMY_SP };
enter_match(bcx, dm, m, col, val, |p| {
match p.node {
ast::PatRegion(sub) => {
Some(vec!(sub))
}
_ => {
assert_is_binding_or_wild(bcx, p);
Some(vec!(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(bcx: &Block, m: &[Match], col: uint) -> Vec<Opt> {
let ccx = bcx.ccx();
fn add_to_set(tcx: &ty::ctxt, set: &mut Vec<Opt>, val: Opt) {
if set.iter().any(|l| opt_eq(tcx, l, &val)) {return;}
set.push(val);
}
// Vector comparisons are special in that since the actual
// conditions over-match, we need to be careful about them. This
// means that in order to properly handle things in order, we need
// to not always merge conditions.
fn add_veclen_to_set(set: &mut Vec<Opt> , i: uint,
len: uint, vlo: VecLenOpt) {
match set.last() {
// If the last condition in the list matches the one we want
// to add, then extend its range. Otherwise, make a new
// vec_len with a range just covering the new entry.
Some(&vec_len(len2, vlo2, (start, end)))
if len == len2 && vlo == vlo2 => {
let length = set.len();
*set.get_mut(length - 1) =
vec_len(len, vlo, (start, end+1))
}
_ => set.push(vec_len(len, vlo, (i, i)))
}
}
let mut found = Vec::new();
for (i, br) in m.iter().enumerate() {
let cur = *br.pats.get(col);
match cur.node {
ast::PatLit(l) => {
add_to_set(ccx.tcx(), &mut found, lit(ExprLit(l)));
}
ast::PatIdent(..) => {
// This is one of: an enum variant, a unit-like struct, or a
// variable binding.
let opt_def = ccx.tcx.def_map.borrow().find_copy(&cur.id);
match opt_def {
Some(ast::DefVariant(..)) => {
add_to_set(ccx.tcx(), &mut found,
variant_opt(bcx, cur.id));
}
Some(ast::DefStruct(..)) => {
add_to_set(ccx.tcx(), &mut found,
lit(UnitLikeStructLit(cur.id)));
}
Some(ast::DefStatic(const_did, false)) => {
add_to_set(ccx.tcx(), &mut found,
lit(ConstLit(const_did)));
}
_ => {}