-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy path_match.rs
2010 lines (1868 loc) · 80.5 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(usize, usize) }
//! match foo {
//! A => ...,
//! B(x) => ...,
//! C(1, 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 `1`
//! 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 an LLVM value which points at an alloca
//! called `llmatch`. For by value bindings that are Copy, we also create
//! an extra alloca that we copy the matched value to so that any changes
//! we do to our copy is not reflected in the original and vice-versa.
//! We don't do this if it's a move since the original value can't be used
//! and thus allowing us to cheat in not creating an extra alloca.
//!
//! 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.
//!
//! 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 then load a second time to get the actual value (the
//! one of type `D`). 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 second half of tuple) |
//! +--------------------------------------------+
//! |
//! +--------------------------------------+
//! | *llbinding_d = **llmatch_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_d |
//! | check condition |
//! | if false { 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). Note that guards and moves are
//! just plain incompatible.
//!
//! Some relevant helper functions that manage bindings:
//! - `create_bindings_map()`
//! - `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.
pub use self::BranchKind::*;
pub use self::OptResult::*;
pub use self::TransBindingMode::*;
use self::Opt::*;
use self::FailureHandler::*;
use llvm::{ValueRef, BasicBlockRef};
use rustc_const_eval::check_match::{self, Constructor, StaticInliner};
use rustc_const_eval::{compare_lit_exprs, eval_const_expr};
use rustc::hir::def::{Def, DefMap};
use rustc::hir::def_id::DefId;
use middle::expr_use_visitor as euv;
use middle::lang_items::StrEqFnLangItem;
use middle::mem_categorization as mc;
use middle::mem_categorization::Categorization;
use rustc::hir::pat_util::*;
use rustc::ty::subst::Substs;
use adt;
use base::*;
use build::{AddCase, And, Br, CondBr, GEPi, InBoundsGEP, Load, PointerCast};
use build::{Not, Store, Sub, add_comment};
use build;
use callee::{Callee, ArgVals};
use cleanup::{self, CleanupMethods, DropHintMethods};
use common::*;
use consts;
use datum::*;
use debuginfo::{self, DebugLoc, ToDebugLoc};
use expr::{self, Dest};
use monomorphize;
use tvec;
use type_of;
use Disr;
use value::Value;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::traits::ProjectionMode;
use session::config::NoDebugInfo;
use util::common::indenter;
use util::nodemap::FnvHashMap;
use util::ppaux;
use std;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::fmt;
use std::rc::Rc;
use rustc::hir::{self, PatKind};
use syntax::ast::{self, DUMMY_NODE_ID, NodeId};
use syntax_pos::Span;
use rustc::hir::fold::Folder;
use syntax::ptr::P;
#[derive(Copy, Clone, Debug)]
struct ConstantExpr<'a>(&'a hir::Expr);
impl<'a> ConstantExpr<'a> {
fn eq<'b, 'tcx>(self, other: ConstantExpr<'a>, tcx: TyCtxt<'b, 'tcx, 'tcx>) -> bool {
match compare_lit_exprs(tcx, self.0, other.0) {
Some(result) => result == Ordering::Equal,
None => bug!("compare_list_exprs: type mismatch"),
}
}
}
// An option identifying a branch (either a literal, an enum variant or a range)
#[derive(Debug)]
enum Opt<'a, 'tcx> {
ConstantValue(ConstantExpr<'a>, DebugLoc),
ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>, DebugLoc),
Variant(Disr, Rc<adt::Repr<'tcx>>, DefId, DebugLoc),
SliceLengthEqual(usize, DebugLoc),
SliceLengthGreaterOrEqual(/* prefix length */ usize,
/* suffix length */ usize,
DebugLoc),
}
impl<'a, 'b, 'tcx> Opt<'a, 'tcx> {
fn eq(&self, other: &Opt<'a, 'tcx>, tcx: TyCtxt<'b, 'tcx, 'tcx>) -> bool {
match (self, other) {
(&ConstantValue(a, _), &ConstantValue(b, _)) => a.eq(b, tcx),
(&ConstantRange(a1, a2, _), &ConstantRange(b1, b2, _)) => {
a1.eq(b1, tcx) && a2.eq(b2, tcx)
}
(&Variant(a_disr, ref a_repr, a_def, _),
&Variant(b_disr, ref b_repr, b_def, _)) => {
a_disr == b_disr && *a_repr == *b_repr && a_def == b_def
}
(&SliceLengthEqual(a, _), &SliceLengthEqual(b, _)) => a == b,
(&SliceLengthGreaterOrEqual(a1, a2, _),
&SliceLengthGreaterOrEqual(b1, b2, _)) => {
a1 == b1 && a2 == b2
}
_ => false
}
}
fn trans<'blk>(&self, mut bcx: Block<'blk, 'tcx>) -> OptResult<'blk, 'tcx> {
use consts::TrueConst::Yes;
let _icx = push_ctxt("match::trans_opt");
let ccx = bcx.ccx();
match *self {
ConstantValue(ConstantExpr(lit_expr), _) => {
let lit_ty = bcx.tcx().node_id_to_type(lit_expr.id);
let expr = consts::const_expr(ccx, &lit_expr, bcx.fcx.param_substs, None, Yes);
let llval = match expr {
Ok((llval, _)) => llval,
Err(err) => bcx.ccx().sess().span_fatal(lit_expr.span, &err.description()),
};
let lit_datum = immediate_rvalue(llval, lit_ty);
let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
SingleResult(Result::new(bcx, lit_datum.val))
}
ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2), _) => {
let l1 = match consts::const_expr(ccx, &l1, bcx.fcx.param_substs, None, Yes) {
Ok((l1, _)) => l1,
Err(err) => bcx.ccx().sess().span_fatal(l1.span, &err.description()),
};
let l2 = match consts::const_expr(ccx, &l2, bcx.fcx.param_substs, None, Yes) {
Ok((l2, _)) => l2,
Err(err) => bcx.ccx().sess().span_fatal(l2.span, &err.description()),
};
RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
}
Variant(disr_val, ref repr, _, _) => {
SingleResult(Result::new(bcx, adt::trans_case(bcx, &repr, disr_val)))
}
SliceLengthEqual(length, _) => {
SingleResult(Result::new(bcx, C_uint(ccx, length)))
}
SliceLengthGreaterOrEqual(prefix, suffix, _) => {
LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
}
}
}
fn debug_loc(&self) -> DebugLoc {
match *self {
ConstantValue(_,debug_loc) |
ConstantRange(_, _, debug_loc) |
Variant(_, _, _, debug_loc) |
SliceLengthEqual(_, debug_loc) |
SliceLengthGreaterOrEqual(_, _, debug_loc) => debug_loc
}
}
}
#[derive(Copy, Clone, PartialEq)]
pub enum BranchKind {
NoBranch,
Single,
Switch,
Compare,
CompareSliceLength
}
pub enum OptResult<'blk, 'tcx: 'blk> {
SingleResult(Result<'blk, 'tcx>),
RangeResult(Result<'blk, 'tcx>, Result<'blk, 'tcx>),
LowerBound(Result<'blk, 'tcx>)
}
#[derive(Clone, Copy, PartialEq)]
pub enum TransBindingMode {
/// By-value binding for a copy type: copies from matched data
/// into a fresh LLVM alloca.
TrByCopy(/* llbinding */ ValueRef),
/// By-value binding for a non-copy type where we copy into a
/// fresh LLVM alloca; this most accurately reflects the language
/// semantics (e.g. it properly handles overwrites of the matched
/// input), but potentially injects an unwanted copy.
TrByMoveIntoCopy(/* llbinding */ ValueRef),
/// Binding a non-copy type by reference under the hood; this is
/// a codegen optimization to avoid unnecessary memory traffic.
TrByMoveRef,
/// By-ref binding exposed in the original source input.
TrByRef,
}
impl TransBindingMode {
/// if binding by making a fresh copy; returns the alloca that it
/// will copy into; otherwise None.
fn alloca_if_copy(&self) -> Option<ValueRef> {
match *self {
TrByCopy(llbinding) | TrByMoveIntoCopy(llbinding) => Some(llbinding),
TrByMoveRef | TrByRef => None,
}
}
}
/// 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
#[derive(Clone, Copy)]
pub struct BindingInfo<'tcx> {
pub llmatch: ValueRef,
pub trmode: TransBindingMode,
pub id: ast::NodeId,
pub span: Span,
pub ty: Ty<'tcx>,
}
type BindingsMap<'tcx> = FnvHashMap<ast::Name, BindingInfo<'tcx>>;
struct ArmData<'p, 'blk, 'tcx: 'blk> {
bodycx: Block<'blk, 'tcx>,
arm: &'p hir::Arm,
bindings_map: BindingsMap<'tcx>
}
/// 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, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
pats: Vec<&'p hir::Pat>,
data: &'a ArmData<'p, 'blk, 'tcx>,
bound_ptrs: Vec<(ast::Name, ValueRef)>,
// Thread along renamings done by the check_match::StaticInliner, so we can
// map back to original NodeIds
pat_renaming_map: Option<&'a FnvHashMap<(NodeId, Span), NodeId>>
}
impl<'a, 'p, 'blk, 'tcx> fmt::Debug for Match<'a, 'p, 'blk, 'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if ppaux::verbose() {
// for many programs, this just take too long to serialize
write!(f, "{:?}", self.pats)
} else {
write!(f, "{} pats", self.pats.len())
}
}
}
fn has_nested_bindings(m: &[Match], col: usize) -> bool {
for br in m {
if let PatKind::Binding(_, _, Some(..)) = br.pats[col].node {
return true
}
}
false
}
// As noted in `fn match_datum`, we should eventually pass around a
// `Datum<Lvalue>` for the `val`; but until we get to that point, this
// `MatchInput` struct will serve -- it has everything `Datum<Lvalue>`
// does except for the type field.
#[derive(Copy, Clone)]
pub struct MatchInput { val: ValueRef, lval: Lvalue }
impl<'tcx> Datum<'tcx, Lvalue> {
pub fn match_input(&self) -> MatchInput {
MatchInput {
val: self.val,
lval: self.kind,
}
}
}
impl fmt::Debug for MatchInput {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&Value(self.val), f)
}
}
impl MatchInput {
fn from_val(val: ValueRef) -> MatchInput {
MatchInput {
val: val,
lval: Lvalue::new("MatchInput::from_val"),
}
}
fn to_datum<'tcx>(self, ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
Datum::new(self.val, ty, self.lval)
}
}
fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
m: &[Match<'a, 'p, 'blk, 'tcx>],
col: usize,
val: MatchInput)
-> Vec<Match<'a, 'p, 'blk, 'tcx>> {
debug!("expand_nested_bindings(bcx={}, m={:?}, col={}, val={:?})",
bcx.to_str(), m, col, val);
let _indenter = indenter();
m.iter().map(|br| {
let mut bound_ptrs = br.bound_ptrs.clone();
let mut pat = br.pats[col];
loop {
pat = match pat.node {
PatKind::Binding(_, ref path, Some(ref inner)) => {
bound_ptrs.push((path.node, val.val));
&inner
},
_ => break
}
}
let mut pats = br.pats.clone();
pats[col] = pat;
Match {
pats: pats,
data: &br.data,
bound_ptrs: bound_ptrs,
pat_renaming_map: br.pat_renaming_map,
}
}).collect()
}
fn enter_match<'a, 'b, 'p, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
m: &[Match<'a, 'p, 'blk, 'tcx>],
col: usize,
val: MatchInput,
mut e: F)
-> Vec<Match<'a, 'p, 'blk, 'tcx>> where
F: FnMut(&[(&'p hir::Pat, Option<Ty<'tcx>>)])
-> Option<Vec<(&'p hir::Pat, Option<Ty<'tcx>>)>>,
{
debug!("enter_match(bcx={}, m={:?}, col={}, val={:?})",
bcx.to_str(), m, col, val);
let _indenter = indenter();
m.iter().filter_map(|br| {
let pats : Vec<_> = br.pats.iter().map(|p| (*p, None)).collect();
e(&pats).map(|pats| {
let this = br.pats[col];
let mut bound_ptrs = br.bound_ptrs.clone();
match this.node {
PatKind::Binding(_, ref path, None) => {
bound_ptrs.push((path.node, val.val));
}
PatKind::Vec(ref before, Some(ref slice), ref after) => {
if let PatKind::Binding(_, ref path, None) = slice.node {
let subslice_val = bind_subslice_pat(
bcx, this.id, val,
before.len(), after.len());
bound_ptrs.push((path.node, subslice_val));
}
}
_ => {}
}
Match {
pats: pats.into_iter().map(|p| p.0).collect(),
data: br.data,
bound_ptrs: bound_ptrs,
pat_renaming_map: br.pat_renaming_map,
}
})
}).collect()
}
fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
m: &[Match<'a, 'p, 'blk, 'tcx>],
col: usize,
val: MatchInput)
-> Vec<Match<'a, 'p, 'blk, 'tcx>> {
debug!("enter_default(bcx={}, m={:?}, col={}, val={:?})",
bcx.to_str(), m, col, val);
let _indenter = indenter();
// Collect all of the matches that can match against anything.
enter_match(bcx, m, col, val, |pats| {
match pats[col].0.node {
PatKind::Binding(..) | PatKind::Wild => {
let mut r = pats[..col].to_vec();
r.extend_from_slice(&pats[col + 1..]);
Some(r)
}
_ => None
}
})
}
// <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
/// The above is now outdated in that enter_match() now takes a function that
/// takes the complete row of patterns rather than just the first one.
/// Also, most of the enter_() family functions have been unified with
/// the check_match specialization step.
fn enter_opt<'a, 'p, 'blk, 'tcx>(
bcx: Block<'blk, 'tcx>,
_: ast::NodeId,
m: &[Match<'a, 'p, 'blk, 'tcx>],
opt: &Opt,
col: usize,
variant_size: usize,
val: MatchInput)
-> Vec<Match<'a, 'p, 'blk, 'tcx>> {
debug!("enter_opt(bcx={}, m={:?}, opt={:?}, col={}, val={:?})",
bcx.to_str(), m, *opt, col, val);
let _indenter = indenter();
let ctor = match opt {
&ConstantValue(ConstantExpr(expr), _) => Constructor::ConstantValue(
eval_const_expr(bcx.tcx(), &expr)
),
&ConstantRange(ConstantExpr(lo), ConstantExpr(hi), _) => Constructor::ConstantRange(
eval_const_expr(bcx.tcx(), &lo),
eval_const_expr(bcx.tcx(), &hi)
),
&SliceLengthEqual(n, _) =>
Constructor::Slice(n),
&SliceLengthGreaterOrEqual(before, after, _) =>
Constructor::SliceWithSubslice(before, after),
&Variant(_, _, def_id, _) =>
Constructor::Variant(def_id)
};
let param_env = bcx.tcx().empty_parameter_environment();
let mcx = check_match::MatchCheckCtxt {
tcx: bcx.tcx(),
param_env: param_env,
};
enter_match(bcx, m, col, val, |pats|
check_match::specialize(&mcx, &pats[..], &ctor, col, variant_size)
)
}
// 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_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
m: &[Match<'a, 'p, 'blk, 'tcx>],
col: usize)
-> Vec<Opt<'p, 'tcx>> {
let tcx = bcx.tcx();
let mut found: Vec<Opt> = vec![];
for br in m {
let cur = br.pats[col];
let debug_loc = match br.pat_renaming_map {
Some(pat_renaming_map) => {
match pat_renaming_map.get(&(cur.id, cur.span)) {
Some(&id) => DebugLoc::At(id, cur.span),
None => DebugLoc::At(cur.id, cur.span),
}
}
None => DebugLoc::None
};
let opt = match cur.node {
PatKind::Lit(ref l) => {
ConstantValue(ConstantExpr(&l), debug_loc)
}
PatKind::Path(..) | PatKind::TupleStruct(..) | PatKind::Struct(..) => {
match tcx.expect_def(cur.id) {
Def::Variant(enum_id, var_id) => {
let variant = tcx.lookup_adt_def(enum_id).variant_with_id(var_id);
Variant(Disr::from(variant.disr_val),
adt::represent_node(bcx, cur.id),
var_id,
debug_loc)
}
_ => continue
}
}
PatKind::Range(ref l1, ref l2) => {
ConstantRange(ConstantExpr(&l1), ConstantExpr(&l2), debug_loc)
}
PatKind::Vec(ref before, None, ref after) => {
SliceLengthEqual(before.len() + after.len(), debug_loc)
}
PatKind::Vec(ref before, Some(_), ref after) => {
SliceLengthGreaterOrEqual(before.len(), after.len(), debug_loc)
}
_ => continue
};
if !found.iter().any(|x| x.eq(&opt, tcx)) {
found.push(opt);
}
}
found
}
struct ExtractedBlock<'blk, 'tcx: 'blk> {
vals: Vec<ValueRef>,
bcx: Block<'blk, 'tcx>,
}
fn extract_variant_args<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
repr: &adt::Repr<'tcx>,
disr_val: Disr,
val: MatchInput)
-> ExtractedBlock<'blk, 'tcx> {
let _icx = push_ctxt("match::extract_variant_args");
// Assume enums are always sized for now.
let val = adt::MaybeSizedValue::sized(val.val);
let args = (0..adt::num_args(repr, disr_val)).map(|i| {
adt::trans_field_ptr(bcx, repr, val, disr_val, i)
}).collect();
ExtractedBlock { vals: args, bcx: bcx }
}
/// Helper for converting from the ValueRef that we pass around in the match code, which is always
/// an lvalue, into a Datum. Eventually we should just pass around a Datum and be done with it.
fn match_datum<'tcx>(val: MatchInput, left_ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
val.to_datum(left_ty)
}
fn bind_subslice_pat(bcx: Block,
pat_id: ast::NodeId,
val: MatchInput,
offset_left: usize,
offset_right: usize) -> ValueRef {
let _icx = push_ctxt("match::bind_subslice_pat");
let vec_ty = node_id_type(bcx, pat_id);
let vec_ty_contents = match vec_ty.sty {
ty::TyBox(ty) => ty,
ty::TyRef(_, mt) | ty::TyRawPtr(mt) => mt.ty,
_ => vec_ty
};
let unit_ty = vec_ty_contents.sequence_element_type(bcx.tcx());
let vec_datum = match_datum(val, vec_ty);
let (base, len) = vec_datum.get_vec_base_and_len(bcx);
let slice_begin = InBoundsGEP(bcx, base, &[C_uint(bcx.ccx(), offset_left)]);
let diff = offset_left + offset_right;
if let ty::TyArray(ty, n) = vec_ty_contents.sty {
let array_ty = bcx.tcx().mk_array(ty, n-diff);
let llty_array = type_of::type_of(bcx.ccx(), array_ty);
return PointerCast(bcx, slice_begin, llty_array.ptr_to());
}
let slice_len_offset = C_uint(bcx.ccx(), diff);
let slice_len = Sub(bcx, len, slice_len_offset, DebugLoc::None);
let slice_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReErased),
bcx.tcx().mk_slice(unit_ty));
let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
Store(bcx, slice_begin, expr::get_dataptr(bcx, scratch.val));
Store(bcx, slice_len, expr::get_meta(bcx, scratch.val));
scratch.val
}
fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
left_ty: Ty<'tcx>,
before: usize,
after: usize,
val: MatchInput)
-> ExtractedBlock<'blk, 'tcx> {
let _icx = push_ctxt("match::extract_vec_elems");
let vec_datum = match_datum(val, left_ty);
let (base, len) = vec_datum.get_vec_base_and_len(bcx);
let mut elems = vec![];
elems.extend((0..before).map(|i| GEPi(bcx, base, &[i])));
elems.extend((0..after).rev().map(|i| {
InBoundsGEP(bcx, base, &[
Sub(bcx, len, C_uint(bcx.ccx(), i + 1), DebugLoc::None)
])
}));
ExtractedBlock { vals: elems, bcx: bcx }
}
// 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, $col:expr, $pattern:pat) => (
($m).iter().any(|br| {
match br.pats[$col].node {
$pattern => true,
_ => false
}
})
)
}
fn any_uniq_pat(m: &[Match], col: usize) -> bool {
any_pat!(m, col, PatKind::Box(_))
}
fn any_region_pat(m: &[Match], col: usize) -> bool {
any_pat!(m, col, PatKind::Ref(..))
}
fn any_irrefutable_adt_pat(tcx: TyCtxt, m: &[Match], col: usize) -> bool {
m.iter().any(|br| {
let pat = br.pats[col];
match pat.node {
PatKind::Tuple(..) => true,
PatKind::Struct(..) | PatKind::TupleStruct(..) | PatKind::Path(..) => {
match tcx.expect_def(pat.id) {
Def::Struct(..) | Def::TyAlias(..) | Def::AssociatedTy(..) => true,
_ => false,
}
}
_ => false
}
})
}
/// What to do when the pattern match fails.
enum FailureHandler {
Infallible,
JumpToBasicBlock(BasicBlockRef),
Unreachable
}
impl FailureHandler {
fn is_fallible(&self) -> bool {
match *self {
Infallible => false,
_ => true
}
}
fn is_infallible(&self) -> bool {
!self.is_fallible()
}
fn handle_fail(&self, bcx: Block) {
match *self {
Infallible =>
bug!("attempted to panic in a non-panicking panic handler!"),
JumpToBasicBlock(basic_block) =>
Br(bcx, basic_block, DebugLoc::None),
Unreachable =>
build::Unreachable(bcx)
}
}
}
fn pick_column_to_specialize(def_map: &RefCell<DefMap>, m: &[Match]) -> Option<usize> {
fn pat_score(def_map: &RefCell<DefMap>, pat: &hir::Pat) -> usize {
match pat.node {
PatKind::Binding(_, _, Some(ref inner)) => pat_score(def_map, &inner),
_ if pat_is_refutable(&def_map.borrow(), pat) => 1,
_ => 0
}
}
let column_score = |m: &[Match], col: usize| -> usize {
let total_score = m.iter()
.map(|row| row.pats[col])
.map(|pat| pat_score(def_map, pat))
.sum();
// Irrefutable columns always go first, they'd only be duplicated in the branches.
if total_score == 0 {
std::usize::MAX
} else {
total_score
}
};
let column_contains_any_nonwild_patterns = |&col: &usize| -> bool {
m.iter().any(|row| match row.pats[col].node {
PatKind::Wild => false,
_ => true
})
};
(0..m[0].pats.len())
.filter(column_contains_any_nonwild_patterns)
.map(|col| (col, column_score(m, col)))
.max_by_key(|&(_, score)| score)
.map(|(col, _)| col)
}
// Compiles a comparison between two things.
fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
lhs: ValueRef,
rhs: ValueRef,
rhs_t: Ty<'tcx>,
debug_loc: DebugLoc)
-> Result<'blk, 'tcx> {
fn compare_str<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
lhs_data: ValueRef,
lhs_len: ValueRef,
rhs_data: ValueRef,
rhs_len: ValueRef,
rhs_t: Ty<'tcx>,
debug_loc: DebugLoc)
-> Result<'blk, 'tcx> {
let did = langcall(bcx.tcx(),
None,
&format!("comparison of `{}`", rhs_t),
StrEqFnLangItem);
let args = [lhs_data, lhs_len, rhs_data, rhs_len];
Callee::def(bcx.ccx(), did, bcx.tcx().mk_substs(Substs::empty()))
.call(bcx, debug_loc, ArgVals(&args), None)
}
let _icx = push_ctxt("compare_values");
if rhs_t.is_scalar() {
let cmp = compare_scalar_types(cx, lhs, rhs, rhs_t, hir::BiEq, debug_loc);
return Result::new(cx, cmp);
}
match rhs_t.sty {
ty::TyRef(_, mt) => match mt.ty.sty {
ty::TyStr => {
let lhs_data = Load(cx, expr::get_dataptr(cx, lhs));
let lhs_len = Load(cx, expr::get_meta(cx, lhs));
let rhs_data = Load(cx, expr::get_dataptr(cx, rhs));
let rhs_len = Load(cx, expr::get_meta(cx, rhs));
compare_str(cx, lhs_data, lhs_len, rhs_data, rhs_len, rhs_t, debug_loc)
}
ty::TyArray(ty, _) | ty::TySlice(ty) => match ty.sty {
ty::TyUint(ast::UintTy::U8) => {
// NOTE: cast &[u8] and &[u8; N] to &str and abuse the str_eq lang item,
// which calls memcmp().
let pat_len = val_ty(rhs).element_type().array_length();
let ty_str_slice = cx.tcx().mk_static_str();
let rhs_data = GEPi(cx, rhs, &[0, 0]);
let rhs_len = C_uint(cx.ccx(), pat_len);
let lhs_data;
let lhs_len;
if val_ty(lhs) == val_ty(rhs) {
// Both the discriminant and the pattern are thin pointers
lhs_data = GEPi(cx, lhs, &[0, 0]);
lhs_len = C_uint(cx.ccx(), pat_len);
} else {
// The discriminant is a fat pointer
let llty_str_slice = type_of::type_of(cx.ccx(), ty_str_slice).ptr_to();
let lhs_str = PointerCast(cx, lhs, llty_str_slice);
lhs_data = Load(cx, expr::get_dataptr(cx, lhs_str));
lhs_len = Load(cx, expr::get_meta(cx, lhs_str));
}
compare_str(cx, lhs_data, lhs_len, rhs_data, rhs_len, rhs_t, debug_loc)
},
_ => bug!("only byte strings supported in compare_values"),
},
_ => bug!("only string and byte strings supported in compare_values"),
},
_ => bug!("only scalars, byte strings, and strings supported in compare_values"),
}
}
/// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
bindings_map: &BindingsMap<'tcx>,
cs: Option<cleanup::ScopeId>)
-> Block<'blk, 'tcx> {
for (&name, &binding_info) in bindings_map {
let (llval, aliases_other_state) = match binding_info.trmode {
// By value mut binding for a copy type: load from the ptr
// into the matched value and copy to our alloca
TrByCopy(llbinding) |
TrByMoveIntoCopy(llbinding) => {
let llval = Load(bcx, binding_info.llmatch);
let lvalue = match binding_info.trmode {
TrByCopy(..) =>
Lvalue::new("_match::insert_lllocals"),
TrByMoveIntoCopy(..) => {
// match_input moves from the input into a
// separate stack slot.
//
// E.g. consider moving the value `D(A)` out
// of the tuple `(D(A), D(B))` and into the
// local variable `x` via the pattern `(x,_)`,
// leaving the remainder of the tuple `(_,
// D(B))` still to be dropped in the future.
//
// Thus, here we must zero the place that we
// are moving *from*, because we do not yet
// track drop flags for a fragmented parent
// match input expression.
//
// Longer term we will be able to map the move
// into `(x, _)` up to the parent path that
// owns the whole tuple, and mark the
// corresponding stack-local drop-flag
// tracking the first component of the tuple.
let hint_kind = HintKind::ZeroAndMaintain;
Lvalue::new_with_hint("_match::insert_lllocals (match_input)",
bcx, binding_info.id, hint_kind)
}
_ => bug!(),
};
let datum = Datum::new(llval, binding_info.ty, lvalue);
call_lifetime_start(bcx, llbinding);
bcx = datum.store_to(bcx, llbinding);
if let Some(cs) = cs {
bcx.fcx.schedule_lifetime_end(cs, llbinding);
}
(llbinding, false)
},
// By value move bindings: load from the ptr into the matched value