-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
mod.rs
1992 lines (1847 loc) · 79.8 KB
/
mod.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
//! Code related to match expressions. These are sufficiently complex to
//! warrant their own module and submodules. :) This main module includes the
//! high-level algorithm, the submodules contain the details.
//!
//! This also includes code for pattern bindings in `let` statements and
//! function parameters.
use crate::build::scope::DropKind;
use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard};
use crate::build::{BlockAnd, BlockAndExtension, Builder};
use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode};
use crate::thir::{self, *};
use rustc_data_structures::{
fx::{FxHashSet, FxIndexMap},
stack::ensure_sufficient_stack,
};
use rustc_hir::HirId;
use rustc_index::bit_set::BitSet;
use rustc_middle::middle::region;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty};
use rustc_span::symbol::Symbol;
use rustc_span::Span;
use rustc_target::abi::VariantIdx;
use smallvec::{smallvec, SmallVec};
// helper functions, broken out by category:
mod simplify;
mod test;
mod util;
use std::borrow::Borrow;
use std::convert::TryFrom;
use std::mem;
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Generates MIR for a `match` expression.
///
/// The MIR that we generate for a match looks like this.
///
/// ```text
/// [ 0. Pre-match ]
/// |
/// [ 1. Evaluate Scrutinee (expression being matched on) ]
/// [ (fake read of scrutinee) ]
/// |
/// [ 2. Decision tree -- check discriminants ] <--------+
/// | |
/// | (once a specific arm is chosen) |
/// | |
/// [pre_binding_block] [otherwise_block]
/// | |
/// [ 3. Create "guard bindings" for arm ] |
/// [ (create fake borrows) ] |
/// | |
/// [ 4. Execute guard code ] |
/// [ (read fake borrows) ] --(guard is false)-----------+
/// |
/// | (guard results in true)
/// |
/// [ 5. Create real bindings and execute arm ]
/// |
/// [ Exit match ]
/// ```
///
/// All of the different arms have been stacked on top of each other to
/// simplify the diagram. For an arm with no guard the blocks marked 3 and
/// 4 and the fake borrows are omitted.
///
/// We generate MIR in the following steps:
///
/// 1. Evaluate the scrutinee and add the fake read of it ([Builder::lower_scrutinee]).
/// 2. Create the decision tree ([Builder::lower_match_tree]).
/// 3. Determine the fake borrows that are needed from the places that were
/// matched against and create the required temporaries for them
/// ([Builder::calculate_fake_borrows]).
/// 4. Create everything else: the guards and the arms ([Builder::lower_match_arms]).
///
/// ## False edges
///
/// We don't want to have the exact structure of the decision tree be
/// visible through borrow checking. False edges ensure that the CFG as
/// seen by borrow checking doesn't encode this. False edges are added:
///
/// * From each prebinding block to the next prebinding block.
/// * From each otherwise block to the next prebinding block.
crate fn match_expr(
&mut self,
destination: Place<'tcx>,
destination_scope: Option<region::Scope>,
span: Span,
mut block: BasicBlock,
scrutinee: ExprRef<'tcx>,
arms: Vec<Arm<'tcx>>,
) -> BlockAnd<()> {
let scrutinee_span = scrutinee.span();
let scrutinee_place =
unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,));
let mut arm_candidates = self.create_match_candidates(scrutinee_place, &arms);
let match_has_guard = arms.iter().any(|arm| arm.guard.is_some());
let mut candidates =
arm_candidates.iter_mut().map(|(_, candidate)| candidate).collect::<Vec<_>>();
let fake_borrow_temps =
self.lower_match_tree(block, scrutinee_span, match_has_guard, &mut candidates);
self.lower_match_arms(
destination,
destination_scope,
scrutinee_place,
scrutinee_span,
arm_candidates,
self.source_info(span),
fake_borrow_temps,
)
}
/// Evaluate the scrutinee and add the fake read of it.
fn lower_scrutinee(
&mut self,
mut block: BasicBlock,
scrutinee: ExprRef<'tcx>,
scrutinee_span: Span,
) -> BlockAnd<Place<'tcx>> {
let scrutinee_place = unpack!(block = self.as_place(block, scrutinee));
// Matching on a `scrutinee_place` with an uninhabited type doesn't
// generate any memory reads by itself, and so if the place "expression"
// contains unsafe operations like raw pointer dereferences or union
// field projections, we wouldn't know to require an `unsafe` block
// around a `match` equivalent to `std::intrinsics::unreachable()`.
// See issue #47412 for this hole being discovered in the wild.
//
// HACK(eddyb) Work around the above issue by adding a dummy inspection
// of `scrutinee_place`, specifically by applying `ReadForMatch`.
//
// NOTE: ReadForMatch also checks that the scrutinee is initialized.
// This is currently needed to not allow matching on an uninitialized,
// uninhabited value. If we get never patterns, those will check that
// the place is initialized, and so this read would only be used to
// check safety.
let cause_matched_place = FakeReadCause::ForMatchedPlace;
let source_info = self.source_info(scrutinee_span);
self.cfg.push_fake_read(block, source_info, cause_matched_place, scrutinee_place);
block.and(scrutinee_place)
}
/// Create the initial `Candidate`s for a `match` expression.
fn create_match_candidates<'pat>(
&mut self,
scrutinee: Place<'tcx>,
arms: &'pat [Arm<'tcx>],
) -> Vec<(&'pat Arm<'tcx>, Candidate<'pat, 'tcx>)> {
// Assemble a list of candidates: there is one candidate per pattern,
// which means there may be more than one candidate *per arm*.
arms.iter()
.map(|arm| {
let arm_has_guard = arm.guard.is_some();
let arm_candidate = Candidate::new(scrutinee, &arm.pattern, arm_has_guard);
(arm, arm_candidate)
})
.collect()
}
/// Create the decision tree for the match expression, starting from `block`.
///
/// Modifies `candidates` to store the bindings and type ascriptions for
/// that candidate.
///
/// Returns the places that need fake borrows because we bind or test them.
fn lower_match_tree<'pat>(
&mut self,
block: BasicBlock,
scrutinee_span: Span,
match_has_guard: bool,
candidates: &mut [&mut Candidate<'pat, 'tcx>],
) -> Vec<(Place<'tcx>, Local)> {
// The set of places that we are creating fake borrows of. If there are
// no match guards then we don't need any fake borrows, so don't track
// them.
let mut fake_borrows = if match_has_guard { Some(FxHashSet::default()) } else { None };
let mut otherwise = None;
// This will generate code to test scrutinee_place and
// branch to the appropriate arm block
self.match_candidates(scrutinee_span, block, &mut otherwise, candidates, &mut fake_borrows);
if let Some(otherwise_block) = otherwise {
// See the doc comment on `match_candidates` for why we may have an
// otherwise block. Match checking will ensure this is actually
// unreachable.
let source_info = self.source_info(scrutinee_span);
self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
}
// Link each leaf candidate to the `pre_binding_block` of the next one.
let mut previous_candidate: Option<&mut Candidate<'_, '_>> = None;
for candidate in candidates {
candidate.visit_leaves(|leaf_candidate| {
if let Some(ref mut prev) = previous_candidate {
prev.next_candidate_pre_binding_block = leaf_candidate.pre_binding_block;
}
previous_candidate = Some(leaf_candidate);
});
}
if let Some(ref borrows) = fake_borrows {
self.calculate_fake_borrows(borrows, scrutinee_span)
} else {
Vec::new()
}
}
/// Binds the variables and ascribes types for a given `match` arm or
/// `let` binding.
///
/// Also check if the guard matches, if it's provided.
/// `arm_scope` should be `Some` if and only if this is called for a
/// `match` arm.
crate fn bind_pattern(
&mut self,
outer_source_info: SourceInfo,
candidate: Candidate<'_, 'tcx>,
guard: Option<&Guard<'tcx>>,
fake_borrow_temps: &Vec<(Place<'tcx>, Local)>,
scrutinee_span: Span,
arm_span: Option<Span>,
arm_scope: Option<region::Scope>,
) -> BasicBlock {
if candidate.subcandidates.is_empty() {
// Avoid generating another `BasicBlock` when we only have one
// candidate.
self.bind_and_guard_matched_candidate(
candidate,
&[],
guard,
fake_borrow_temps,
scrutinee_span,
arm_span,
true,
)
} else {
// It's helpful to avoid scheduling drops multiple times to save
// drop elaboration from having to clean up the extra drops.
//
// If we are in a `let` then we only schedule drops for the first
// candidate.
//
// If we're in a `match` arm then we could have a case like so:
//
// Ok(x) | Err(x) if return => { /* ... */ }
//
// In this case we don't want a drop of `x` scheduled when we
// return: it isn't bound by move until right before enter the arm.
// To handle this we instead unschedule it's drop after each time
// we lower the guard.
let target_block = self.cfg.start_new_block();
let mut schedule_drops = true;
// We keep a stack of all of the bindings and type asciptions
// from the parent candidates that we visit, that also need to
// be bound for each candidate.
traverse_candidate(
candidate,
&mut Vec::new(),
&mut |leaf_candidate, parent_bindings| {
if let Some(arm_scope) = arm_scope {
self.clear_top_scope(arm_scope);
}
let binding_end = self.bind_and_guard_matched_candidate(
leaf_candidate,
parent_bindings,
guard,
&fake_borrow_temps,
scrutinee_span,
arm_span,
schedule_drops,
);
if arm_scope.is_none() {
schedule_drops = false;
}
self.cfg.goto(binding_end, outer_source_info, target_block);
},
|inner_candidate, parent_bindings| {
parent_bindings.push((inner_candidate.bindings, inner_candidate.ascriptions));
inner_candidate.subcandidates.into_iter()
},
|parent_bindings| {
parent_bindings.pop();
},
);
target_block
}
}
pub(super) fn expr_into_pattern(
&mut self,
mut block: BasicBlock,
irrefutable_pat: Pat<'tcx>,
initializer: ExprRef<'tcx>,
) -> BlockAnd<()> {
match *irrefutable_pat.kind {
// Optimize the case of `let x = ...` to write directly into `x`
PatKind::Binding { mode: BindingMode::ByValue, var, subpattern: None, .. } => {
let place =
self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard, true);
let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
unpack!(block = self.into(place, Some(region_scope), block, initializer));
// Inject a fake read, see comments on `FakeReadCause::ForLet`.
let source_info = self.source_info(irrefutable_pat.span);
self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet, place);
block.unit()
}
// Optimize the case of `let x: T = ...` to write directly
// into `x` and then require that `T == typeof(x)`.
//
// Weirdly, this is needed to prevent the
// `intrinsic-move-val.rs` test case from crashing. That
// test works with uninitialized values in a rather
// dubious way, so it may be that the test is kind of
// broken.
PatKind::AscribeUserType {
subpattern:
Pat {
kind:
box PatKind::Binding {
mode: BindingMode::ByValue,
var,
subpattern: None,
..
},
..
},
ascription:
thir::pattern::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
} => {
let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
let place =
self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard, true);
unpack!(block = self.into(place, Some(region_scope), block, initializer));
// Inject a fake read, see comments on `FakeReadCause::ForLet`.
let pattern_source_info = self.source_info(irrefutable_pat.span);
let cause_let = FakeReadCause::ForLet;
self.cfg.push_fake_read(block, pattern_source_info, cause_let, place);
let ty_source_info = self.source_info(user_ty_span);
let user_ty = pat_ascription_ty.user_ty(
&mut self.canonical_user_type_annotations,
place.ty(&self.local_decls, self.hir.tcx()).ty,
ty_source_info.span,
);
self.cfg.push(
block,
Statement {
source_info: ty_source_info,
kind: StatementKind::AscribeUserType(
box (place, user_ty),
// We always use invariant as the variance here. This is because the
// variance field from the ascription refers to the variance to use
// when applying the type to the value being matched, but this
// ascription applies rather to the type of the binding. e.g., in this
// example:
//
// ```
// let x: T = <expr>
// ```
//
// We are creating an ascription that defines the type of `x` to be
// exactly `T` (i.e., with invariance). The variance field, in
// contrast, is intended to be used to relate `T` to the type of
// `<expr>`.
ty::Variance::Invariant,
),
},
);
block.unit()
}
_ => {
let place = unpack!(block = self.as_place(block, initializer));
self.place_into_pattern(block, irrefutable_pat, place, true)
}
}
}
crate fn place_into_pattern(
&mut self,
block: BasicBlock,
irrefutable_pat: Pat<'tcx>,
initializer: Place<'tcx>,
set_match_place: bool,
) -> BlockAnd<()> {
let mut candidate = Candidate::new(initializer, &irrefutable_pat, false);
let fake_borrow_temps =
self.lower_match_tree(block, irrefutable_pat.span, false, &mut [&mut candidate]);
// For matches and function arguments, the place that is being matched
// can be set when creating the variables. But the place for
// let PATTERN = ... might not even exist until we do the assignment.
// so we set it here instead.
if set_match_place {
let mut candidate_ref = &candidate;
while let Some(next) = {
for binding in &candidate_ref.bindings {
let local = self.var_local_id(binding.var_id, OutsideGuard);
if let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
VarBindingForm { opt_match_place: Some((ref mut match_place, _)), .. },
)))) = self.local_decls[local].local_info
{
*match_place = Some(initializer);
} else {
bug!("Let binding to non-user variable.")
}
}
// All of the subcandidates should bind the same locals, so we
// only visit the first one.
candidate_ref.subcandidates.get(0)
} {
candidate_ref = next;
}
}
self.bind_pattern(
self.source_info(irrefutable_pat.span),
candidate,
None,
&fake_borrow_temps,
irrefutable_pat.span,
None,
None,
)
.unit()
}
/// Declares the bindings of the given patterns and returns the visibility
/// scope for the bindings in these patterns, if such a scope had to be
/// created. NOTE: Declaring the bindings should always be done in their
/// drop scope.
crate fn declare_bindings(
&mut self,
mut visibility_scope: Option<SourceScope>,
scope_span: Span,
pattern: &Pat<'tcx>,
has_guard: ArmHasGuard,
opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
) -> Option<SourceScope> {
debug!("declare_bindings: pattern={:?}", pattern);
self.visit_primary_bindings(
&pattern,
UserTypeProjections::none(),
&mut |this, mutability, name, mode, var, span, ty, user_ty| {
if visibility_scope.is_none() {
visibility_scope =
Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
}
let source_info = SourceInfo { span, scope: this.source_scope };
let visibility_scope = visibility_scope.unwrap();
this.declare_binding(
source_info,
visibility_scope,
mutability,
name,
mode,
var,
ty,
user_ty,
has_guard,
opt_match_place.map(|(x, y)| (x.cloned(), y)),
pattern.span,
);
},
);
visibility_scope
}
crate fn storage_live_binding(
&mut self,
block: BasicBlock,
var: HirId,
span: Span,
for_guard: ForGuard,
schedule_drop: bool,
) -> Place<'tcx> {
let local_id = self.var_local_id(var, for_guard);
let source_info = self.source_info(span);
self.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(local_id) });
let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
if schedule_drop {
self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
}
Place::from(local_id)
}
crate fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
let local_id = self.var_local_id(var, for_guard);
let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
self.schedule_drop(span, region_scope, local_id, DropKind::Value);
}
/// Visit all of the primary bindings in a patterns, that is, visit the
/// leftmost occurrence of each variable bound in a pattern. A variable
/// will occur more than once in an or-pattern.
pub(super) fn visit_primary_bindings(
&mut self,
pattern: &Pat<'tcx>,
pattern_user_ty: UserTypeProjections,
f: &mut impl FnMut(
&mut Self,
Mutability,
Symbol,
BindingMode,
HirId,
Span,
Ty<'tcx>,
UserTypeProjections,
),
) {
debug!(
"visit_primary_bindings: pattern={:?} pattern_user_ty={:?}",
pattern, pattern_user_ty
);
match *pattern.kind {
PatKind::Binding {
mutability,
name,
mode,
var,
ty,
ref subpattern,
is_primary,
..
} => {
if is_primary {
f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
}
if let Some(subpattern) = subpattern.as_ref() {
self.visit_primary_bindings(subpattern, pattern_user_ty, f);
}
}
PatKind::Array { ref prefix, ref slice, ref suffix }
| PatKind::Slice { ref prefix, ref slice, ref suffix } => {
let from = u64::try_from(prefix.len()).unwrap();
let to = u64::try_from(suffix.len()).unwrap();
for subpattern in prefix {
self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
}
for subpattern in slice {
self.visit_primary_bindings(
subpattern,
pattern_user_ty.clone().subslice(from, to),
f,
);
}
for subpattern in suffix {
self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
}
}
PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
PatKind::Deref { ref subpattern } => {
self.visit_primary_bindings(subpattern, pattern_user_ty.deref(), f);
}
PatKind::AscribeUserType {
ref subpattern,
ascription: thir::pattern::Ascription { ref user_ty, user_ty_span, variance: _ },
} => {
// This corresponds to something like
//
// ```
// let A::<'a>(_): A<'static> = ...;
// ```
//
// Note that the variance doesn't apply here, as we are tracking the effect
// of `user_ty` on any bindings contained with subpattern.
let annotation = CanonicalUserTypeAnnotation {
span: user_ty_span,
user_ty: user_ty.user_ty,
inferred_ty: subpattern.ty,
};
let projection = UserTypeProjection {
base: self.canonical_user_type_annotations.push(annotation),
projs: Vec::new(),
};
let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
self.visit_primary_bindings(subpattern, subpattern_user_ty, f)
}
PatKind::Leaf { ref subpatterns } => {
for subpattern in subpatterns {
let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
debug!("visit_primary_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
self.visit_primary_bindings(&subpattern.pattern, subpattern_user_ty, f);
}
}
PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
for subpattern in subpatterns {
let subpattern_user_ty =
pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field);
self.visit_primary_bindings(&subpattern.pattern, subpattern_user_ty, f);
}
}
PatKind::Or { ref pats } => {
// In cases where we recover from errors the primary bindings
// may not all be in the leftmost subpattern. For example in
// `let (x | y) = ...`, the primary binding of `y` occurs in
// the right subpattern
for subpattern in pats {
self.visit_primary_bindings(subpattern, pattern_user_ty.clone(), f);
}
}
}
}
}
#[derive(Debug)]
pub(super) struct Candidate<'pat, 'tcx> {
/// `Span` of the original pattern that gave rise to this candidate
span: Span,
/// This `Candidate` has a guard.
has_guard: bool,
/// All of these must be satisfied...
match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
/// ...these bindings established...
bindings: Vec<Binding<'tcx>>,
/// ...and these types asserted...
ascriptions: Vec<Ascription<'tcx>>,
/// ... and if this is non-empty, one of these subcandidates also has to match ...
subcandidates: Vec<Candidate<'pat, 'tcx>>,
/// ...and the guard must be evaluated, if false branch to Block...
otherwise_block: Option<BasicBlock>,
/// ...and the blocks for add false edges between candidates
pre_binding_block: Option<BasicBlock>,
next_candidate_pre_binding_block: Option<BasicBlock>,
}
impl<'tcx, 'pat> Candidate<'pat, 'tcx> {
fn new(place: Place<'tcx>, pattern: &'pat Pat<'tcx>, has_guard: bool) -> Self {
Candidate {
span: pattern.span,
has_guard,
match_pairs: smallvec![MatchPair { place, pattern }],
bindings: Vec::new(),
ascriptions: Vec::new(),
subcandidates: Vec::new(),
otherwise_block: None,
pre_binding_block: None,
next_candidate_pre_binding_block: None,
}
}
/// Visit the leaf candidates (those with no subcandidates) contained in
/// this candidate.
fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
traverse_candidate(
self,
&mut (),
&mut move |c, _| visit_leaf(c),
move |c, _| c.subcandidates.iter_mut(),
|_| {},
);
}
}
/// A depth-first traversal of the `Candidate` and all of its recursive
/// subcandidates.
fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>(
candidate: C,
context: &mut T,
visit_leaf: &mut impl FnMut(C, &mut T),
get_children: impl Copy + Fn(C, &mut T) -> I,
complete_children: impl Copy + Fn(&mut T),
) where
C: Borrow<Candidate<'pat, 'tcx>>,
I: Iterator<Item = C>,
{
if candidate.borrow().subcandidates.is_empty() {
visit_leaf(candidate, context)
} else {
for child in get_children(candidate, context) {
traverse_candidate(child, context, visit_leaf, get_children, complete_children);
}
complete_children(context)
}
}
#[derive(Clone, Debug)]
struct Binding<'tcx> {
span: Span,
source: Place<'tcx>,
name: Symbol,
var_id: HirId,
var_ty: Ty<'tcx>,
mutability: Mutability,
binding_mode: BindingMode,
}
/// Indicates that the type of `source` must be a subtype of the
/// user-given type `user_ty`; this is basically a no-op but can
/// influence region inference.
#[derive(Clone, Debug)]
struct Ascription<'tcx> {
span: Span,
source: Place<'tcx>,
user_ty: PatTyProj<'tcx>,
variance: ty::Variance,
}
#[derive(Clone, Debug)]
crate struct MatchPair<'pat, 'tcx> {
// this place...
place: Place<'tcx>,
// ... must match this pattern.
pattern: &'pat Pat<'tcx>,
}
#[derive(Clone, Debug, PartialEq)]
enum TestKind<'tcx> {
/// Test the branches of enum.
Switch {
/// The enum being tested
adt_def: &'tcx ty::AdtDef,
/// The set of variants that we should create a branch for. We also
/// create an additional "otherwise" case.
variants: BitSet<VariantIdx>,
},
/// Test what value an `integer`, `bool` or `char` has.
SwitchInt {
/// The type of the value that we're testing.
switch_ty: Ty<'tcx>,
/// The (ordered) set of values that we test for.
///
/// For integers and `char`s we create a branch to each of the values in
/// `options`, as well as an "otherwise" branch for all other values, even
/// in the (rare) case that options is exhaustive.
///
/// For `bool` we always generate two edges, one for `true` and one for
/// `false`.
options: FxIndexMap<&'tcx ty::Const<'tcx>, u128>,
},
/// Test for equality with value, possibly after an unsizing coercion to
/// `ty`,
Eq {
value: &'tcx ty::Const<'tcx>,
// Integer types are handled by `SwitchInt`, and constants with ADT
// types are converted back into patterns, so this can only be `&str`,
// `&[T]`, `f32` or `f64`.
ty: Ty<'tcx>,
},
/// Test whether the value falls within an inclusive or exclusive range
Range(PatRange<'tcx>),
/// Test length of the slice is equal to len
Len { len: u64, op: BinOp },
}
#[derive(Debug)]
crate struct Test<'tcx> {
span: Span,
kind: TestKind<'tcx>,
}
/// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
/// a match arm has a guard expression attached to it.
#[derive(Copy, Clone, Debug)]
crate struct ArmHasGuard(crate bool);
///////////////////////////////////////////////////////////////////////////
// Main matching algorithm
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// The main match algorithm. It begins with a set of candidates
/// `candidates` and has the job of generating code to determine
/// which of these candidates, if any, is the correct one. The
/// candidates are sorted such that the first item in the list
/// has the highest priority. When a candidate is found to match
/// the value, we will set and generate a branch to the appropriate
/// prebinding block.
///
/// If we find that *NONE* of the candidates apply, we branch to the
/// `otherwise_block`, setting it to `Some` if required. In principle, this
/// means that the input list was not exhaustive, though at present we
/// sometimes are not smart enough to recognize all exhaustive inputs.
///
/// It might be surprising that the input can be inexhaustive.
/// Indeed, initially, it is not, because all matches are
/// exhaustive in Rust. But during processing we sometimes divide
/// up the list of candidates and recurse with a non-exhaustive
/// list. This is important to keep the size of the generated code
/// under control. See `test_candidates` for more details.
///
/// If `fake_borrows` is Some, then places which need fake borrows
/// will be added to it.
///
/// For an example of a case where we set `otherwise_block`, even for an
/// exhaustive match consider:
///
/// ```rust
/// match x {
/// (true, true) => (),
/// (_, false) => (),
/// (false, true) => (),
/// }
/// ```
///
/// For this match, we check if `x.0` matches `true` (for the first
/// arm). If that's false, we check `x.1`. If it's `true` we check if
/// `x.0` matches `false` (for the third arm). In the (impossible at
/// runtime) case when `x.0` is now `true`, we branch to
/// `otherwise_block`.
fn match_candidates<'pat>(
&mut self,
span: Span,
start_block: BasicBlock,
otherwise_block: &mut Option<BasicBlock>,
candidates: &mut [&mut Candidate<'pat, 'tcx>],
fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
) {
debug!(
"matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
span, candidates, start_block, otherwise_block,
);
// Start by simplifying candidates. Once this process is complete, all
// the match pairs which remain require some form of test, whether it
// be a switch or pattern comparison.
let mut split_or_candidate = false;
for candidate in &mut *candidates {
split_or_candidate |= self.simplify_candidate(candidate);
}
ensure_sufficient_stack(|| {
if split_or_candidate {
// At least one of the candidates has been split into subcandidates.
// We need to change the candidate list to include those.
let mut new_candidates = Vec::new();
for candidate in candidates {
candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate));
}
self.match_simplified_candidates(
span,
start_block,
otherwise_block,
&mut *new_candidates,
fake_borrows,
);
} else {
self.match_simplified_candidates(
span,
start_block,
otherwise_block,
candidates,
fake_borrows,
);
}
});
}
fn match_simplified_candidates(
&mut self,
span: Span,
start_block: BasicBlock,
otherwise_block: &mut Option<BasicBlock>,
candidates: &mut [&mut Candidate<'_, 'tcx>],
fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
) {
// The candidates are sorted by priority. Check to see whether the
// higher priority candidates (and hence at the front of the slice)
// have satisfied all their match pairs.
let fully_matched = candidates.iter().take_while(|c| c.match_pairs.is_empty()).count();
debug!("match_candidates: {:?} candidates fully matched", fully_matched);
let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
let block = if !matched_candidates.is_empty() {
let otherwise_block =
self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
if let Some(last_otherwise_block) = otherwise_block {
last_otherwise_block
} else {
// Any remaining candidates are unreachable.
if unmatched_candidates.is_empty() {
return;
}
self.cfg.start_new_block()
}
} else {
start_block
};
// If there are no candidates that still need testing, we're
// done. Since all matches are exhaustive, execution should
// never reach this point.
if unmatched_candidates.is_empty() {
let source_info = self.source_info(span);
if let Some(otherwise) = *otherwise_block {
self.cfg.goto(block, source_info, otherwise);
} else {
*otherwise_block = Some(block);
}
return;
}
// Test for the remaining candidates.
self.test_candidates_with_or(
span,
unmatched_candidates,
block,
otherwise_block,
fake_borrows,
);
}
/// Link up matched candidates. For example, if we have something like
/// this:
///
/// ```rust
/// ...
/// Some(x) if cond => ...
/// Some(x) => ...
/// Some(x) if cond => ...
/// ...
/// ```
///
/// We generate real edges from:
/// * `start_block` to the `prebinding_block` of the first pattern,
/// * the otherwise block of the first pattern to the second pattern,
/// * the otherwise block of the third pattern to the a block with an
/// Unreachable terminator.
///
/// As well as that we add fake edges from the otherwise blocks to the
/// prebinding block of the next candidate in the original set of
/// candidates.
fn select_matched_candidates(
&mut self,
matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
start_block: BasicBlock,
fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
) -> Option<BasicBlock> {
debug_assert!(
!matched_candidates.is_empty(),
"select_matched_candidates called with no candidates",
);
debug_assert!(
matched_candidates.iter().all(|c| c.subcandidates.is_empty()),
"subcandidates should be empty in select_matched_candidates",
);
// Insert a borrows of prefixes of places that are bound and are
// behind a dereference projection.
//
// These borrows are taken to avoid situations like the following:
//
// match x[10] {
// _ if { x = &[0]; false } => (),
// y => (), // Out of bounds array access!
// }
//
// match *x {
// // y is bound by reference in the guard and then by copy in the
// // arm, so y is 2 in the arm!
// y if { y == 1 && (x = &2) == () } => y,
// _ => 3,
// }
if let Some(fake_borrows) = fake_borrows {
for Binding { source, .. } in
matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
{
if let Some(i) =
source.projection.iter().rposition(|elem| elem == ProjectionElem::Deref)
{
let proj_base = &source.projection[..i];