forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
2565 lines (2380 loc) · 104 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::expr::as_place::PlaceBuilder;
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 rustc_data_structures::{fx::FxIndexMap, stack::ensure_sufficient_stack};
use rustc_hir::{BindingMode, ByRef};
use rustc_middle::bug;
use rustc_middle::middle::region;
use rustc_middle::mir::{self, *};
use rustc_middle::thir::{self, *};
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty};
use rustc_span::symbol::Symbol;
use rustc_span::{BytePos, Pos, Span};
use rustc_target::abi::VariantIdx;
use tracing::{debug, instrument};
use util::visit_bindings;
// helper functions, broken out by category:
mod simplify;
mod test;
mod util;
use std::assert_matches::assert_matches;
use std::borrow::Borrow;
use std::mem;
/// Arguments to [`Builder::then_else_break_inner`] that are usually forwarded
/// to recursive invocations.
#[derive(Clone, Copy)]
struct ThenElseArgs {
/// Used as the temp scope for lowering `expr`. If absent (for match guards),
/// `self.local_scope()` is used.
temp_scope_override: Option<region::Scope>,
variable_source_info: SourceInfo,
/// Determines how bindings should be handled when lowering `let` expressions.
///
/// Forwarded to [`Builder::lower_let_expr`] when lowering [`ExprKind::Let`].
declare_let_bindings: DeclareLetBindings,
}
/// Should lowering a `let` expression also declare its bindings?
///
/// Used by [`Builder::lower_let_expr`] when lowering [`ExprKind::Let`].
#[derive(Clone, Copy)]
pub(crate) enum DeclareLetBindings {
/// Yes, declare `let` bindings as normal for `if` conditions.
Yes,
/// No, don't declare `let` bindings, because the caller declares them
/// separately due to special requirements.
///
/// Used for match guards and let-else.
No,
/// Let expressions are not permitted in this context, so it is a bug to
/// try to lower one (e.g inside lazy-boolean-or or boolean-not).
LetNotPermitted,
}
/// Used by [`Builder::bind_matched_candidate_for_arm_body`] to determine
/// whether or not to call [`Builder::storage_live_binding`] to emit
/// [`StatementKind::StorageLive`].
#[derive(Clone, Copy)]
pub(crate) enum EmitStorageLive {
/// Yes, emit `StorageLive` as normal.
Yes,
/// No, don't emit `StorageLive`. The caller has taken responsibility for
/// emitting `StorageLive` as appropriate.
No,
}
/// Used by [`Builder::storage_live_binding`] and [`Builder::bind_matched_candidate_for_arm_body`]
/// to decide whether to schedule drops.
#[derive(Clone, Copy, Debug)]
pub(crate) enum ScheduleDrops {
/// Yes, the relevant functions should also schedule drops as appropriate.
Yes,
/// No, don't schedule drops. The caller has taken responsibility for any
/// appropriate drops.
No,
}
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Lowers a condition in a way that ensures that variables bound in any let
/// expressions are definitely initialized in the if body.
///
/// If `declare_let_bindings` is false then variables created in `let`
/// expressions will not be declared. This is for if let guards on arms with
/// an or pattern, where the guard is lowered multiple times.
pub(crate) fn then_else_break(
&mut self,
block: BasicBlock,
expr_id: ExprId,
temp_scope_override: Option<region::Scope>,
variable_source_info: SourceInfo,
declare_let_bindings: DeclareLetBindings,
) -> BlockAnd<()> {
self.then_else_break_inner(
block,
expr_id,
ThenElseArgs { temp_scope_override, variable_source_info, declare_let_bindings },
)
}
fn then_else_break_inner(
&mut self,
block: BasicBlock, // Block that the condition and branch will be lowered into
expr_id: ExprId, // Condition expression to lower
args: ThenElseArgs,
) -> BlockAnd<()> {
let this = self;
let expr = &this.thir[expr_id];
let expr_span = expr.span;
match expr.kind {
ExprKind::LogicalOp { op: op @ LogicalOp::And, lhs, rhs } => {
this.visit_coverage_branch_operation(op, expr_span);
let lhs_then_block = unpack!(this.then_else_break_inner(block, lhs, args));
let rhs_then_block = unpack!(this.then_else_break_inner(lhs_then_block, rhs, args));
rhs_then_block.unit()
}
ExprKind::LogicalOp { op: op @ LogicalOp::Or, lhs, rhs } => {
this.visit_coverage_branch_operation(op, expr_span);
let local_scope = this.local_scope();
let (lhs_success_block, failure_block) =
this.in_if_then_scope(local_scope, expr_span, |this| {
this.then_else_break_inner(
block,
lhs,
ThenElseArgs {
declare_let_bindings: DeclareLetBindings::LetNotPermitted,
..args
},
)
});
let rhs_success_block = unpack!(this.then_else_break_inner(
failure_block,
rhs,
ThenElseArgs {
declare_let_bindings: DeclareLetBindings::LetNotPermitted,
..args
},
));
// Make the LHS and RHS success arms converge to a common block.
// (We can't just make LHS goto RHS, because `rhs_success_block`
// might contain statements that we don't want on the LHS path.)
let success_block = this.cfg.start_new_block();
this.cfg.goto(lhs_success_block, args.variable_source_info, success_block);
this.cfg.goto(rhs_success_block, args.variable_source_info, success_block);
success_block.unit()
}
ExprKind::Unary { op: UnOp::Not, arg } => {
// Improve branch coverage instrumentation by noting conditions
// nested within one or more `!` expressions.
// (Skipped if branch coverage is not enabled.)
if let Some(coverage_info) = this.coverage_info.as_mut() {
coverage_info.visit_unary_not(this.thir, expr_id);
}
let local_scope = this.local_scope();
let (success_block, failure_block) =
this.in_if_then_scope(local_scope, expr_span, |this| {
// Help out coverage instrumentation by injecting a dummy statement with
// the original condition's span (including `!`). This fixes #115468.
if this.tcx.sess.instrument_coverage() {
this.cfg.push_coverage_span_marker(block, this.source_info(expr_span));
}
this.then_else_break_inner(
block,
arg,
ThenElseArgs {
declare_let_bindings: DeclareLetBindings::LetNotPermitted,
..args
},
)
});
this.break_for_else(success_block, args.variable_source_info);
failure_block.unit()
}
ExprKind::Scope { region_scope, lint_level, value } => {
let region_scope = (region_scope, this.source_info(expr_span));
this.in_scope(region_scope, lint_level, |this| {
this.then_else_break_inner(block, value, args)
})
}
ExprKind::Use { source } => this.then_else_break_inner(block, source, args),
ExprKind::Let { expr, ref pat } => this.lower_let_expr(
block,
expr,
pat,
Some(args.variable_source_info.scope),
args.variable_source_info.span,
args.declare_let_bindings,
EmitStorageLive::Yes,
),
_ => {
let mut block = block;
let temp_scope = args.temp_scope_override.unwrap_or_else(|| this.local_scope());
let mutability = Mutability::Mut;
// Increment the decision depth, in case we encounter boolean expressions
// further down.
this.mcdc_increment_depth_if_enabled();
let place =
unpack!(block = this.as_temp(block, Some(temp_scope), expr_id, mutability));
this.mcdc_decrement_depth_if_enabled();
let operand = Operand::Move(Place::from(place));
let then_block = this.cfg.start_new_block();
let else_block = this.cfg.start_new_block();
let term = TerminatorKind::if_(operand, then_block, else_block);
// Record branch coverage info for this condition.
// (Does nothing if branch coverage is not enabled.)
this.visit_coverage_branch_condition(expr_id, then_block, else_block);
let source_info = this.source_info(expr_span);
this.cfg.terminate(block, source_info, term);
this.break_for_else(else_block, source_info);
then_block.unit()
}
}
}
/// 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) ]
/// [ (PlaceMention 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 PlaceMention 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
/// ([util::collect_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. Specifically we want borrowck to think that:
/// - at any point, any or none of the patterns and guards seen so far may have been tested;
/// - after the match, any of the patterns may have matched.
///
/// For example, all of these would fail to error if borrowck could see the real CFG (examples
/// taken from `tests/ui/nll/match-cfg-fake-edges.rs`):
/// ```ignore (too many errors, this is already in the test suite)
/// let x = String::new();
/// let _ = match true {
/// _ => {},
/// _ => drop(x),
/// };
/// // Borrowck must not know the second arm is never run.
/// drop(x); //~ ERROR use of moved value
///
/// let x;
/// # let y = true;
/// match y {
/// _ if { x = 2; true } => {},
/// // Borrowck must not know the guard is always run.
/// _ => drop(x), //~ ERROR used binding `x` is possibly-uninitialized
/// };
///
/// let x = String::new();
/// # let y = true;
/// match y {
/// false if { drop(x); true } => {},
/// // Borrowck must not know the guard is not run in the `true` case.
/// true => drop(x), //~ ERROR use of moved value: `x`
/// false => {},
/// };
///
/// # let mut y = (true, true);
/// let r = &mut y.1;
/// match y {
/// //~^ ERROR cannot use `y.1` because it was mutably borrowed
/// (false, true) => {}
/// // Borrowck must not know we don't test `y.1` when `y.0` is `true`.
/// (true, _) => drop(r),
/// (false, _) => {}
/// };
/// ```
///
/// We add false edges to act as if we were naively matching each arm in order. What we need is
/// a (fake) path from each candidate to the next, specifically from candidate C's pre-binding
/// block to next candidate D's pre-binding block. For maximum precision (needed for deref
/// patterns), we choose the earliest node on D's success path that doesn't also lead to C (to
/// avoid loops).
///
/// This turns out to be easy to compute: that block is the `start_block` of the first call to
/// `match_candidates` where D is the first candidate in the list.
///
/// For example:
/// ```rust
/// # let (x, y) = (true, true);
/// match (x, y) {
/// (true, true) => 1,
/// (false, true) => 2,
/// (true, false) => 3,
/// _ => 4,
/// }
/// # ;
/// ```
/// In this example, the pre-binding block of arm 1 has a false edge to the block for result
/// `false` of the first test on `x`. The other arms have false edges to the pre-binding blocks
/// of the next arm.
///
/// On top of this, we also add a false edge from the otherwise_block of each guard to the
/// aforementioned start block of the next candidate, to ensure borrock doesn't rely on which
/// guards may have run.
#[instrument(level = "debug", skip(self, arms))]
pub(crate) fn match_expr(
&mut self,
destination: Place<'tcx>,
destination_scope: Option<region::Scope>,
mut block: BasicBlock,
scrutinee_id: ExprId,
arms: &[ArmId],
span: Span,
scrutinee_span: Span,
) -> BlockAnd<()> {
let scrutinee_place =
unpack!(block = self.lower_scrutinee(block, scrutinee_id, scrutinee_span));
let mut arm_candidates = self.create_match_candidates(&scrutinee_place, arms);
let match_has_guard = arm_candidates.iter().any(|(_, candidate)| candidate.has_guard);
let mut candidates =
arm_candidates.iter_mut().map(|(_, candidate)| candidate).collect::<Vec<_>>();
let match_start_span = span.shrink_to_lo().to(scrutinee_span);
// 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 fake_borrow_temps: Vec<(Place<'tcx>, Local, FakeBorrowKind)> = if match_has_guard {
util::collect_fake_borrows(self, &candidates, scrutinee_span, scrutinee_place.base())
} else {
Vec::new()
};
self.lower_match_tree(
block,
scrutinee_span,
&scrutinee_place,
match_start_span,
&mut candidates,
false,
);
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 PlaceMention for it.
fn lower_scrutinee(
&mut self,
mut block: BasicBlock,
scrutinee_id: ExprId,
scrutinee_span: Span,
) -> BlockAnd<PlaceBuilder<'tcx>> {
let scrutinee_place_builder = unpack!(block = self.as_place_builder(block, scrutinee_id));
if let Some(scrutinee_place) = scrutinee_place_builder.try_to_place(self) {
let source_info = self.source_info(scrutinee_span);
self.cfg.push_place_mention(block, source_info, scrutinee_place);
}
block.and(scrutinee_place_builder)
}
/// Create the initial `Candidate`s for a `match` expression.
fn create_match_candidates<'pat>(
&mut self,
scrutinee: &PlaceBuilder<'tcx>,
arms: &'pat [ArmId],
) -> Vec<(&'pat Arm<'tcx>, Candidate<'pat, 'tcx>)>
where
'a: 'pat,
{
// Assemble the initial list of candidates. These top-level candidates
// are 1:1 with the original match arms, but other parts of match
// lowering also introduce subcandidates (for subpatterns), and will
// also flatten candidates in some cases. So in general a list of
// candidates does _not_ necessarily correspond to a list of arms.
arms.iter()
.copied()
.map(|arm| {
let arm = &self.thir[arm];
let arm_has_guard = arm.guard.is_some();
let arm_candidate =
Candidate::new(scrutinee.clone(), &arm.pattern, arm_has_guard, self);
(arm, arm_candidate)
})
.collect()
}
/// Lower the bindings, guards and arm bodies of a `match` expression.
///
/// The decision tree should have already been created
/// (by [Builder::lower_match_tree]).
///
/// `outer_source_info` is the SourceInfo for the whole match.
/// [Builder::lower_match_tree]).
fn lower_match_arms(
&mut self,
destination: Place<'tcx>,
destination_scope: Option<region::Scope>,
scrutinee_place_builder: PlaceBuilder<'tcx>,
scrutinee_span: Span,
arm_candidates: Vec<(&'_ Arm<'tcx>, Candidate<'_, 'tcx>)>,
outer_source_info: SourceInfo,
fake_borrow_temps: Vec<(Place<'tcx>, Local, FakeBorrowKind)>,
) -> BlockAnd<()> {
if arm_candidates.is_empty() {
// If there are no arms to schedule drops, then we have to do it
// manually.
if let Some(scope) = destination_scope {
self.schedule_drop(
outer_source_info.span,
scope,
destination.as_local().unwrap(),
DropKind::Value,
);
}
return self.cfg.start_new_block().unit();
}
let mut first_arm = true;
let arm_end_blocks: Vec<_> = arm_candidates
.into_iter()
.map(|(arm, candidate)| {
debug!("lowering arm {:?}\ncandidate = {:?}", arm, candidate);
if first_arm {
first_arm = false;
} else if let Some(scope) = destination_scope {
// Unschedule the drop from the previous arm, it will then
// be rescheduled by the end of this arm.
self.unschedule_drop(scope, destination.as_local().unwrap());
}
let arm_source_info = self.source_info(arm.span);
let arm_scope = (arm.scope, arm_source_info);
let match_scope = self.local_scope();
self.in_scope(arm_scope, arm.lint_level, |this| {
let old_dedup_scope =
mem::replace(&mut this.fixed_temps_scope, Some(arm.scope));
// `try_to_place` may fail if it is unable to resolve the given
// `PlaceBuilder` inside a closure. In this case, we don't want to include
// a scrutinee place. `scrutinee_place_builder` will fail to be resolved
// if the only match arm is a wildcard (`_`).
// Example:
// ```
// let foo = (0, 1);
// let c = || {
// match foo { _ => () };
// };
// ```
let scrutinee_place = scrutinee_place_builder.try_to_place(this);
let opt_scrutinee_place =
scrutinee_place.as_ref().map(|place| (Some(place), scrutinee_span));
let scope = this.declare_bindings(
None,
arm.span,
&arm.pattern,
arm.guard,
opt_scrutinee_place,
);
let arm_block = this.bind_pattern(
outer_source_info,
candidate,
&fake_borrow_temps,
scrutinee_span,
Some((arm, match_scope)),
EmitStorageLive::Yes,
);
this.fixed_temps_scope = old_dedup_scope;
if let Some(source_scope) = scope {
this.source_scope = source_scope;
}
this.expr_into_dest(destination, destination_scope, arm_block, arm.body)
})
})
.collect();
// all the arm blocks will rejoin here
let end_block = self.cfg.start_new_block();
let end_brace = self.source_info(
outer_source_info.span.with_lo(outer_source_info.span.hi() - BytePos::from_usize(1)),
);
for arm_block in arm_end_blocks {
let block = &self.cfg.basic_blocks[arm_block.0];
let last_location = block.statements.last().map(|s| s.source_info);
self.cfg.goto(unpack!(arm_block), last_location.unwrap_or(end_brace), end_block);
}
self.source_scope = outer_source_info.scope;
end_block.unit()
}
/// 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.
fn bind_pattern(
&mut self,
outer_source_info: SourceInfo,
candidate: Candidate<'_, 'tcx>,
fake_borrow_temps: &[(Place<'tcx>, Local, FakeBorrowKind)],
scrutinee_span: Span,
arm_match_scope: Option<(&Arm<'tcx>, region::Scope)>,
emit_storage_live: EmitStorageLive,
) -> BasicBlock {
if candidate.subcandidates.is_empty() {
// Avoid generating another `BasicBlock` when we only have one
// candidate.
self.bind_and_guard_matched_candidate(
candidate,
&[],
fake_borrow_temps,
scrutinee_span,
arm_match_scope,
ScheduleDrops::Yes,
emit_storage_live,
)
} 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 = ScheduleDrops::Yes;
let arm = arm_match_scope.unzip().0;
// We keep a stack of all of the bindings and type ascriptions
// 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_data| {
if let Some(arm) = arm {
self.clear_top_scope(arm.scope);
}
let binding_end = self.bind_and_guard_matched_candidate(
leaf_candidate,
parent_data,
fake_borrow_temps,
scrutinee_span,
arm_match_scope,
schedule_drops,
emit_storage_live,
);
if arm.is_none() {
schedule_drops = ScheduleDrops::No;
}
self.cfg.goto(binding_end, outer_source_info, target_block);
},
|inner_candidate, parent_data| {
parent_data.push(inner_candidate.extra_data);
inner_candidate.subcandidates.into_iter()
},
|parent_data| {
parent_data.pop();
},
);
target_block
}
}
pub(super) fn expr_into_pattern(
&mut self,
mut block: BasicBlock,
irrefutable_pat: &Pat<'tcx>,
initializer_id: ExprId,
) -> BlockAnd<()> {
match irrefutable_pat.kind {
// Optimize the case of `let x = ...` to write directly into `x`
PatKind::Binding { mode: BindingMode(ByRef::No, _), var, subpattern: None, .. } => {
let place = self.storage_live_binding(
block,
var,
irrefutable_pat.span,
OutsideGuard,
ScheduleDrops::Yes,
);
let region_scope = self.region_scope_tree.var_scope(var.0.local_id);
unpack!(block = self.expr_into_dest(place, region_scope, block, initializer_id));
// 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(None), 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:
box Pat {
kind:
PatKind::Binding {
mode: BindingMode(ByRef::No, _),
var,
subpattern: None,
..
},
..
},
ascription: thir::Ascription { ref annotation, variance: _ },
} => {
let region_scope = self.region_scope_tree.var_scope(var.0.local_id);
let place = self.storage_live_binding(
block,
var,
irrefutable_pat.span,
OutsideGuard,
ScheduleDrops::Yes,
);
unpack!(block = self.expr_into_dest(place, region_scope, block, initializer_id));
// Inject a fake read, see comments on `FakeReadCause::ForLet`.
let pattern_source_info = self.source_info(irrefutable_pat.span);
let cause_let = FakeReadCause::ForLet(None);
self.cfg.push_fake_read(block, pattern_source_info, cause_let, place);
let ty_source_info = self.source_info(annotation.span);
let base = self.canonical_user_type_annotations.push(annotation.clone());
self.cfg.push(
block,
Statement {
source_info: ty_source_info,
kind: StatementKind::AscribeUserType(
Box::new((place, UserTypeProjection { base, projs: Vec::new() })),
// 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::Invariant,
),
},
);
block.unit()
}
_ => {
let initializer = &self.thir[initializer_id];
let place_builder =
unpack!(block = self.lower_scrutinee(block, initializer_id, initializer.span));
self.place_into_pattern(block, irrefutable_pat, place_builder, true)
}
}
}
pub(crate) fn place_into_pattern(
&mut self,
block: BasicBlock,
irrefutable_pat: &Pat<'tcx>,
initializer: PlaceBuilder<'tcx>,
set_match_place: bool,
) -> BlockAnd<()> {
let mut candidate = Candidate::new(initializer.clone(), irrefutable_pat, false, self);
// 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 {
// `try_to_place` may fail if it is unable to resolve the given `PlaceBuilder` inside a
// closure. In this case, we don't want to include a scrutinee place.
// `scrutinee_place_builder` will fail for destructured assignments. This is because a
// closure only captures the precise places that it will read and as a result a closure
// may not capture the entire tuple/struct and rather have individual places that will
// be read in the final MIR.
// Example:
// ```
// let foo = (0, 1);
// let c = || {
// let (v1, v2) = foo;
// };
// ```
if let Some(place) = initializer.try_to_place(self) {
visit_bindings(&[&mut candidate], |binding: &Binding<'_>| {
let local = self.var_local_id(binding.var_id, OutsideGuard);
if let LocalInfo::User(BindingForm::Var(VarBindingForm {
opt_match_place: Some((ref mut match_place, _)),
..
})) = **self.local_decls[local].local_info.as_mut().assert_crate_local()
{
*match_place = Some(place);
} else {
bug!("Let binding to non-user variable.")
};
});
}
}
self.lower_match_tree(
block,
irrefutable_pat.span,
&initializer,
irrefutable_pat.span,
&mut [&mut candidate],
false,
);
self.bind_pattern(
self.source_info(irrefutable_pat.span),
candidate,
&[],
irrefutable_pat.span,
None,
EmitStorageLive::Yes,
)
.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.
#[instrument(skip(self), level = "debug")]
pub(crate) fn declare_bindings(
&mut self,
mut visibility_scope: Option<SourceScope>,
scope_span: Span,
pattern: &Pat<'tcx>,
guard: Option<ExprId>,
opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
) -> Option<SourceScope> {
self.visit_primary_bindings(
pattern,
UserTypeProjections::none(),
&mut |this, name, mode, var, span, ty, user_ty| {
if visibility_scope.is_none() {
visibility_scope =
Some(this.new_source_scope(scope_span, LintLevel::Inherited));
}
let source_info = SourceInfo { span, scope: this.source_scope };
let visibility_scope = visibility_scope.unwrap();
this.declare_binding(
source_info,
visibility_scope,
name,
mode,
var,
ty,
user_ty,
ArmHasGuard(guard.is_some()),
opt_match_place.map(|(x, y)| (x.cloned(), y)),
pattern.span,
);
},
);
if let Some(guard_expr) = guard {
self.declare_guard_bindings(guard_expr, scope_span, visibility_scope);
}
visibility_scope
}
/// Declare bindings in a guard. This has to be done when declaring bindings
/// for an arm to ensure that or patterns only have one version of each
/// variable.
pub(crate) fn declare_guard_bindings(
&mut self,
guard_expr: ExprId,
scope_span: Span,
visibility_scope: Option<SourceScope>,
) {
match self.thir.exprs[guard_expr].kind {
ExprKind::Let { expr: _, pat: ref guard_pat } => {
// FIXME: pass a proper `opt_match_place`
self.declare_bindings(visibility_scope, scope_span, guard_pat, None, None);
}
ExprKind::Scope { value, .. } => {
self.declare_guard_bindings(value, scope_span, visibility_scope);
}
ExprKind::Use { source } => {
self.declare_guard_bindings(source, scope_span, visibility_scope);
}
ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
self.declare_guard_bindings(lhs, scope_span, visibility_scope);
self.declare_guard_bindings(rhs, scope_span, visibility_scope);
}
_ => {}
}
}
/// Emits a [`StatementKind::StorageLive`] for the given var, and also
/// schedules a drop if requested (and possible).
pub(crate) fn storage_live_binding(
&mut self,
block: BasicBlock,
var: LocalVarId,
span: Span,
for_guard: ForGuard,
schedule_drop: ScheduleDrops,
) -> 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) });
// Although there is almost always scope for given variable in corner cases
// like #92893 we might get variable with no scope.
if let Some(region_scope) = self.region_scope_tree.var_scope(var.0.local_id)
&& matches!(schedule_drop, ScheduleDrops::Yes)
{
self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
}
Place::from(local_id)
}
pub(crate) fn schedule_drop_for_binding(
&mut self,
var: LocalVarId,
span: Span,
for_guard: ForGuard,
) {
let local_id = self.var_local_id(var, for_guard);
if let Some(region_scope) = self.region_scope_tree.var_scope(var.0.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,
Symbol,
BindingMode,
LocalVarId,
Span,
Ty<'tcx>,
UserTypeProjections,
),
) {
debug!(
"visit_primary_bindings: pattern={:?} pattern_user_ty={:?}",
pattern, pattern_user_ty
);
match pattern.kind {
PatKind::Binding { name, mode, var, ty, ref subpattern, is_primary, .. } => {
if is_primary {
f(self, 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.iter() {
self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
}
if let Some(subpattern) = slice {
self.visit_primary_bindings(
subpattern,
pattern_user_ty.clone().subslice(from, to),
f,
);
}
for subpattern in suffix.iter() {
self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
}
}
PatKind::Constant { .. }
| PatKind::Range { .. }
| PatKind::Wild
| PatKind::Never
| PatKind::Error(_) => {}
PatKind::Deref { ref subpattern } => {
self.visit_primary_bindings(subpattern, pattern_user_ty.deref(), f);
}
PatKind::DerefPattern { ref subpattern, .. } => {
self.visit_primary_bindings(subpattern, UserTypeProjections::none(), f);
}
PatKind::AscribeUserType {
ref subpattern,
ascription: thir::Ascription { ref annotation, 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 projection = UserTypeProjection {
base: self.canonical_user_type_annotations.push(annotation.clone()),
projs: Vec::new(),
};
let subpattern_user_ty =
pattern_user_ty.push_projection(&projection, annotation.span);
self.visit_primary_bindings(subpattern, subpattern_user_ty, f)
}
PatKind::InlineConstant { ref subpattern, .. } => {
self.visit_primary_bindings(subpattern, pattern_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);