]> git.proxmox.com Git - rustc.git/blob - src/librustc_mir/build/matches/mod.rs
New upstream version 1.34.2+dfsg1
[rustc.git] / src / librustc_mir / build / matches / mod.rs
1 //! Code related to match expressions. These are sufficiently complex to
2 //! warrant their own module and submodules. :) This main module includes the
3 //! high-level algorithm, the submodules contain the details.
4 //!
5 //! This also includes code for pattern bindings in `let` statements and
6 //! function parameters.
7
8 use crate::build::scope::{CachedBlock, DropKind};
9 use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard};
10 use crate::build::{BlockAnd, BlockAndExtension, Builder};
11 use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode};
12 use crate::hair::{self, *};
13 use rustc::mir::*;
14 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty};
15 use rustc::ty::layout::VariantIdx;
16 use rustc_data_structures::bit_set::BitSet;
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use syntax::ast::{Name, NodeId};
19 use syntax_pos::Span;
20
21 // helper functions, broken out by category:
22 mod simplify;
23 mod test;
24 mod util;
25
26 use std::convert::TryFrom;
27
28 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
29 /// Generates MIR for a `match` expression.
30 ///
31 /// The MIR that we generate for a match looks like this.
32 ///
33 /// ```text
34 /// [ 0. Pre-match ]
35 /// |
36 /// [ 1. Evaluate Scrutinee (expression being matched on) ]
37 /// [ (fake read of scrutinee) ]
38 /// |
39 /// [ 2. Decision tree -- check discriminants ] <--------+
40 /// | |
41 /// | (once a specific arm is chosen) |
42 /// | |
43 /// [pre_binding_block] [otherwise_block]
44 /// | |
45 /// [ 3. Create "guard bindings" for arm ] |
46 /// [ (create fake borrows) ] |
47 /// | |
48 /// [ 4. Execute guard code ] |
49 /// [ (read fake borrows) ] --(guard is false)-----------+
50 /// |
51 /// | (guard results in true)
52 /// |
53 /// [ 5. Create real bindings and execute arm ]
54 /// |
55 /// [ Exit match ]
56 /// ```
57 ///
58 /// All of the different arms have been stacked on top of each other to
59 /// simplify the diagram. For an arm with no guard the blocks marked 3 and
60 /// 4 and the fake borrows are omitted.
61 ///
62 /// We generate MIR in the following steps:
63 ///
64 /// 1. Evaluate the scrutinee and add the fake read of it.
65 /// 2. Create the prebinding and otherwise blocks.
66 /// 3. Create the decision tree and record the places that we bind or test.
67 /// 4. Determine the fake borrows that are needed from the above places.
68 /// Create the required temporaries for them.
69 /// 5. Create everything else: Create everything else: the guards and the
70 /// arms.
71 ///
72 /// ## Fake Reads and borrows
73 ///
74 /// Match exhaustiveness checking is not able to handle the case where the
75 /// place being matched on is mutated in the guards. There is an AST check
76 /// that tries to stop this but it is buggy and overly restrictive. Instead
77 /// we add "fake borrows" to the guards that prevent any mutation of the
78 /// place being matched. There are a some subtleties:
79 ///
80 /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
81 /// refence, the borrow isn't even tracked. As such we have to add fake
82 /// borrows of any prefixes of a place
83 /// 2. We don't want `match x { _ => (), }` to conflict with mutable
84 /// borrows of `x`, so we only add fake borrows for places which are
85 /// bound or tested by the match.
86 /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
87 /// so we use a special BorrowKind for them.
88 /// 4. The fake borrows may be of places in inactive variants, so it would
89 /// be UB to generate code for them. They therefore have to be removed
90 /// by a MIR pass run after borrow checking.
91 ///
92 /// ## False edges
93 ///
94 /// We don't want to have the exact structure of the decision tree be
95 /// visible through borrow checking. False edges ensure that the CFG as
96 /// seen by borrow checking doesn't encode this. False edges are added:
97 ///
98 /// * From each prebinding block to the next prebinding block.
99 /// * From each otherwise block to the next prebinding block.
100 pub fn match_expr(
101 &mut self,
102 destination: &Place<'tcx>,
103 span: Span,
104 mut block: BasicBlock,
105 scrutinee: ExprRef<'tcx>,
106 arms: Vec<Arm<'tcx>>,
107 ) -> BlockAnd<()> {
108 let tcx = self.hir.tcx();
109
110 // Step 1. Evaluate the scrutinee and add the fake read of it.
111
112 let scrutinee_span = scrutinee.span();
113 let scrutinee_place = unpack!(block = self.as_place(block, scrutinee));
114
115 // Matching on a `scrutinee_place` with an uninhabited type doesn't
116 // generate any memory reads by itself, and so if the place "expression"
117 // contains unsafe operations like raw pointer dereferences or union
118 // field projections, we wouldn't know to require an `unsafe` block
119 // around a `match` equivalent to `std::intrinsics::unreachable()`.
120 // See issue #47412 for this hole being discovered in the wild.
121 //
122 // HACK(eddyb) Work around the above issue by adding a dummy inspection
123 // of `scrutinee_place`, specifically by applying `ReadForMatch`.
124 //
125 // NOTE: ReadForMatch also checks that the scrutinee is initialized.
126 // This is currently needed to not allow matching on an uninitialized,
127 // uninhabited value. If we get never patterns, those will check that
128 // the place is initialized, and so this read would only be used to
129 // check safety.
130
131 let source_info = self.source_info(scrutinee_span);
132 self.cfg.push(block, Statement {
133 source_info,
134 kind: StatementKind::FakeRead(
135 FakeReadCause::ForMatchedPlace,
136 scrutinee_place.clone(),
137 ),
138 });
139
140 // Step 2. Create the otherwise and prebinding blocks.
141
142 // create binding start block for link them by false edges
143 let candidate_count = arms.iter().map(|c| c.patterns.len()).sum::<usize>();
144 let pre_binding_blocks: Vec<_> = (0..=candidate_count)
145 .map(|_| self.cfg.start_new_block())
146 .collect();
147
148 // There's one more pre_binding block than there are candidates so that
149 // every candidate can have a `next_candidate_pre_binding_block`.
150 let outer_source_info = self.source_info(span);
151 self.cfg.terminate(
152 *pre_binding_blocks.last().unwrap(),
153 outer_source_info,
154 TerminatorKind::Unreachable,
155 );
156
157 let mut match_has_guard = false;
158
159 let mut candidate_pre_binding_blocks = pre_binding_blocks.iter();
160 let mut next_candidate_pre_binding_blocks = pre_binding_blocks.iter().skip(1);
161
162 // Assemble a list of candidates: there is one candidate per pattern,
163 // which means there may be more than one candidate *per arm*.
164 let mut arm_candidates: Vec<_> = arms
165 .iter()
166 .map(|arm| {
167 let arm_has_guard = arm.guard.is_some();
168 match_has_guard |= arm_has_guard;
169 let arm_candidates: Vec<_> = arm.patterns
170 .iter()
171 .zip(candidate_pre_binding_blocks.by_ref())
172 .zip(next_candidate_pre_binding_blocks.by_ref())
173 .map(
174 |((pattern, pre_binding_block), next_candidate_pre_binding_block)| {
175 Candidate {
176 span: pattern.span,
177 match_pairs: vec![
178 MatchPair::new(scrutinee_place.clone(), pattern),
179 ],
180 bindings: vec![],
181 ascriptions: vec![],
182 otherwise_block: if arm_has_guard {
183 Some(self.cfg.start_new_block())
184 } else {
185 None
186 },
187 pre_binding_block: *pre_binding_block,
188 next_candidate_pre_binding_block:
189 *next_candidate_pre_binding_block,
190 }
191 },
192 )
193 .collect();
194 (arm, arm_candidates)
195 })
196 .collect();
197
198 // Step 3. Create the decision tree and record the places that we bind or test.
199
200 // The set of places that we are creating fake borrows of. If there are
201 // no match guards then we don't need any fake borrows, so don't track
202 // them.
203 let mut fake_borrows = if match_has_guard && tcx.generate_borrow_of_any_match_input() {
204 Some(FxHashSet::default())
205 } else {
206 None
207 };
208
209 // These candidates are kept sorted such that the highest priority
210 // candidate comes first in the list. (i.e., same order as in source)
211 // As we gnerate the decision tree,
212 let candidates = &mut arm_candidates
213 .iter_mut()
214 .flat_map(|(_, candidates)| candidates)
215 .collect::<Vec<_>>();
216
217 // this will generate code to test scrutinee_place and
218 // branch to the appropriate arm block
219 let otherwise = self.match_candidates(
220 scrutinee_span,
221 candidates,
222 block,
223 &mut fake_borrows,
224 );
225
226 if !otherwise.is_empty() {
227 // All matches are exhaustive. However, because some matches
228 // only have exponentially-large exhaustive decision trees, we
229 // sometimes generate an inexhaustive decision tree.
230 //
231 // In that case, the inexhaustive tips of the decision tree
232 // can't be reached - terminate them with an `unreachable`.
233 let mut otherwise = otherwise;
234 otherwise.sort();
235 otherwise.dedup(); // variant switches can introduce duplicate target blocks
236 for block in otherwise {
237 self.cfg
238 .terminate(block, outer_source_info, TerminatorKind::Unreachable);
239 }
240 }
241
242 // Step 4. Determine the fake borrows that are needed from the above
243 // places. Create the required temporaries for them.
244
245 let fake_borrow_temps = if let Some(ref borrows) = fake_borrows {
246 self.calculate_fake_borrows(borrows, scrutinee_span)
247 } else {
248 Vec::new()
249 };
250
251 // Step 5. Create everything else: the guards and the arms.
252
253 let outer_source_info = self.source_info(span);
254 let arm_end_blocks: Vec<_> = arm_candidates.into_iter().map(|(arm, candidates)| {
255 let mut arm_block = self.cfg.start_new_block();
256
257 let body = self.hir.mirror(arm.body.clone());
258 let scope = self.declare_bindings(
259 None,
260 body.span,
261 LintLevel::Inherited,
262 &arm.patterns[0],
263 ArmHasGuard(arm.guard.is_some()),
264 Some((Some(&scrutinee_place), scrutinee_span)),
265 );
266
267 for candidate in candidates {
268 self.bind_and_guard_matched_candidate(
269 candidate,
270 arm.guard.clone(),
271 arm_block,
272 &fake_borrow_temps,
273 scrutinee_span,
274 );
275 }
276
277 if let Some(source_scope) = scope {
278 self.source_scope = source_scope;
279 }
280
281 unpack!(arm_block = self.into(destination, arm_block, body));
282
283 arm_block
284 }).collect();
285
286 // all the arm blocks will rejoin here
287 let end_block = self.cfg.start_new_block();
288
289 for arm_block in arm_end_blocks {
290 self.cfg.terminate(
291 arm_block,
292 outer_source_info,
293 TerminatorKind::Goto { target: end_block },
294 );
295 }
296
297 self.source_scope = outer_source_info.scope;
298
299 end_block.unit()
300 }
301
302 pub(super) fn expr_into_pattern(
303 &mut self,
304 mut block: BasicBlock,
305 irrefutable_pat: Pattern<'tcx>,
306 initializer: ExprRef<'tcx>,
307 ) -> BlockAnd<()> {
308 match *irrefutable_pat.kind {
309 // Optimize the case of `let x = ...` to write directly into `x`
310 PatternKind::Binding {
311 mode: BindingMode::ByValue,
312 var,
313 subpattern: None,
314 ..
315 } => {
316 let place =
317 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
318 unpack!(block = self.into(&place, block, initializer));
319
320
321 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
322 let source_info = self.source_info(irrefutable_pat.span);
323 self.cfg.push(
324 block,
325 Statement {
326 source_info,
327 kind: StatementKind::FakeRead(FakeReadCause::ForLet, place),
328 },
329 );
330
331 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
332 block.unit()
333 }
334
335 // Optimize the case of `let x: T = ...` to write directly
336 // into `x` and then require that `T == typeof(x)`.
337 //
338 // Weirdly, this is needed to prevent the
339 // `intrinsic-move-val.rs` test case from crashing. That
340 // test works with uninitialized values in a rather
341 // dubious way, so it may be that the test is kind of
342 // broken.
343 PatternKind::AscribeUserType {
344 subpattern: Pattern {
345 kind: box PatternKind::Binding {
346 mode: BindingMode::ByValue,
347 var,
348 subpattern: None,
349 ..
350 },
351 ..
352 },
353 ascription: hair::pattern::Ascription {
354 user_ty: pat_ascription_ty,
355 variance: _,
356 user_ty_span,
357 },
358 } => {
359 let place =
360 self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
361 unpack!(block = self.into(&place, block, initializer));
362
363 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
364 let pattern_source_info = self.source_info(irrefutable_pat.span);
365 self.cfg.push(
366 block,
367 Statement {
368 source_info: pattern_source_info,
369 kind: StatementKind::FakeRead(FakeReadCause::ForLet, place.clone()),
370 },
371 );
372
373 let ty_source_info = self.source_info(user_ty_span);
374 let user_ty = box pat_ascription_ty.user_ty(
375 &mut self.canonical_user_type_annotations,
376 place.ty(&self.local_decls, self.hir.tcx()).to_ty(self.hir.tcx()),
377 ty_source_info.span,
378 );
379 self.cfg.push(
380 block,
381 Statement {
382 source_info: ty_source_info,
383 kind: StatementKind::AscribeUserType(
384 place,
385 // We always use invariant as the variance here. This is because the
386 // variance field from the ascription refers to the variance to use
387 // when applying the type to the value being matched, but this
388 // ascription applies rather to the type of the binding. e.g., in this
389 // example:
390 //
391 // ```
392 // let x: T = <expr>
393 // ```
394 //
395 // We are creating an ascription that defines the type of `x` to be
396 // exactly `T` (i.e., with invariance). The variance field, in
397 // contrast, is intended to be used to relate `T` to the type of
398 // `<expr>`.
399 ty::Variance::Invariant,
400 user_ty,
401 ),
402 },
403 );
404
405 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
406 block.unit()
407 }
408
409 _ => {
410 let place = unpack!(block = self.as_place(block, initializer));
411 self.place_into_pattern(block, irrefutable_pat, &place, true)
412 }
413 }
414 }
415
416 pub fn place_into_pattern(
417 &mut self,
418 block: BasicBlock,
419 irrefutable_pat: Pattern<'tcx>,
420 initializer: &Place<'tcx>,
421 set_match_place: bool,
422 ) -> BlockAnd<()> {
423 // create a dummy candidate
424 let mut candidate = Candidate {
425 span: irrefutable_pat.span,
426 match_pairs: vec![MatchPair::new(initializer.clone(), &irrefutable_pat)],
427 bindings: vec![],
428 ascriptions: vec![],
429
430 // since we don't call `match_candidates`, next fields are unused
431 otherwise_block: None,
432 pre_binding_block: block,
433 next_candidate_pre_binding_block: block,
434 };
435
436 // Simplify the candidate. Since the pattern is irrefutable, this should
437 // always convert all match-pairs into bindings.
438 self.simplify_candidate(&mut candidate);
439
440 if !candidate.match_pairs.is_empty() {
441 span_bug!(
442 candidate.match_pairs[0].pattern.span,
443 "match pairs {:?} remaining after simplifying \
444 irrefutable pattern",
445 candidate.match_pairs
446 );
447 }
448
449 // for matches and function arguments, the place that is being matched
450 // can be set when creating the variables. But the place for
451 // let PATTERN = ... might not even exist until we do the assignment.
452 // so we set it here instead
453 if set_match_place {
454 for binding in &candidate.bindings {
455 let local = self.var_local_id(binding.var_id, OutsideGuard);
456
457 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
458 opt_match_place: Some((ref mut match_place, _)),
459 ..
460 }))) = self.local_decls[local].is_user_variable
461 {
462 *match_place = Some(initializer.clone());
463 } else {
464 bug!("Let binding to non-user variable.")
465 }
466 }
467 }
468
469 self.ascribe_types(block, &candidate.ascriptions);
470
471 // now apply the bindings, which will also declare the variables
472 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
473
474 block.unit()
475 }
476
477 /// Declares the bindings of the given patterns and returns the visibility
478 /// scope for the bindings in these patterns, if such a scope had to be
479 /// created. NOTE: Declaring the bindings should always be done in their
480 /// drop scope.
481 pub fn declare_bindings(
482 &mut self,
483 mut visibility_scope: Option<SourceScope>,
484 scope_span: Span,
485 lint_level: LintLevel,
486 pattern: &Pattern<'tcx>,
487 has_guard: ArmHasGuard,
488 opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
489 ) -> Option<SourceScope> {
490 assert!(
491 !(visibility_scope.is_some() && lint_level.is_explicit()),
492 "can't have both a visibility and a lint scope at the same time"
493 );
494 let mut scope = self.source_scope;
495 debug!("declare_bindings: pattern={:?}", pattern);
496 self.visit_bindings(
497 &pattern,
498 UserTypeProjections::none(),
499 &mut |this, mutability, name, mode, var, span, ty, user_ty| {
500 if visibility_scope.is_none() {
501 visibility_scope =
502 Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
503 // If we have lints, create a new source scope
504 // that marks the lints for the locals. See the comment
505 // on the `source_info` field for why this is needed.
506 if lint_level.is_explicit() {
507 scope = this.new_source_scope(scope_span, lint_level, None);
508 }
509 }
510 let source_info = SourceInfo { span, scope };
511 let visibility_scope = visibility_scope.unwrap();
512 this.declare_binding(
513 source_info,
514 visibility_scope,
515 mutability,
516 name,
517 mode,
518 var,
519 ty,
520 user_ty,
521 has_guard,
522 opt_match_place.map(|(x, y)| (x.cloned(), y)),
523 pattern.span,
524 );
525 },
526 );
527 visibility_scope
528 }
529
530 pub fn storage_live_binding(
531 &mut self,
532 block: BasicBlock,
533 var: NodeId,
534 span: Span,
535 for_guard: ForGuard,
536 ) -> Place<'tcx> {
537 let local_id = self.var_local_id(var, for_guard);
538 let source_info = self.source_info(span);
539 self.cfg.push(
540 block,
541 Statement {
542 source_info,
543 kind: StatementKind::StorageLive(local_id),
544 },
545 );
546 let place = Place::Local(local_id);
547 let var_ty = self.local_decls[local_id].ty;
548 let hir_id = self.hir.tcx().hir().node_to_hir_id(var);
549 let region_scope = self.hir.region_scope_tree.var_scope(hir_id.local_id);
550 self.schedule_drop(span, region_scope, &place, var_ty, DropKind::Storage);
551 place
552 }
553
554 pub fn schedule_drop_for_binding(&mut self, var: NodeId, span: Span, for_guard: ForGuard) {
555 let local_id = self.var_local_id(var, for_guard);
556 let var_ty = self.local_decls[local_id].ty;
557 let hir_id = self.hir.tcx().hir().node_to_hir_id(var);
558 let region_scope = self.hir.region_scope_tree.var_scope(hir_id.local_id);
559 self.schedule_drop(
560 span,
561 region_scope,
562 &Place::Local(local_id),
563 var_ty,
564 DropKind::Value {
565 cached_block: CachedBlock::default(),
566 },
567 );
568 }
569
570 pub(super) fn visit_bindings(
571 &mut self,
572 pattern: &Pattern<'tcx>,
573 pattern_user_ty: UserTypeProjections<'tcx>,
574 f: &mut impl FnMut(
575 &mut Self,
576 Mutability,
577 Name,
578 BindingMode,
579 NodeId,
580 Span,
581 Ty<'tcx>,
582 UserTypeProjections<'tcx>,
583 ),
584 ) {
585 debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
586 match *pattern.kind {
587 PatternKind::Binding {
588 mutability,
589 name,
590 mode,
591 var,
592 ty,
593 ref subpattern,
594 ..
595 } => {
596 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
597 if let Some(subpattern) = subpattern.as_ref() {
598 self.visit_bindings(subpattern, pattern_user_ty, f);
599 }
600 }
601
602 PatternKind::Array {
603 ref prefix,
604 ref slice,
605 ref suffix,
606 }
607 | PatternKind::Slice {
608 ref prefix,
609 ref slice,
610 ref suffix,
611 } => {
612 let from = u32::try_from(prefix.len()).unwrap();
613 let to = u32::try_from(suffix.len()).unwrap();
614 for subpattern in prefix {
615 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
616 }
617 for subpattern in slice {
618 self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
619 }
620 for subpattern in suffix {
621 self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
622 }
623 }
624
625 PatternKind::Constant { .. } | PatternKind::Range { .. } | PatternKind::Wild => {}
626
627 PatternKind::Deref { ref subpattern } => {
628 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
629 }
630
631 PatternKind::AscribeUserType {
632 ref subpattern,
633 ascription: hair::pattern::Ascription {
634 ref user_ty,
635 user_ty_span,
636 variance: _,
637 },
638 } => {
639 // This corresponds to something like
640 //
641 // ```
642 // let A::<'a>(_): A<'static> = ...;
643 // ```
644 //
645 // Note that the variance doesn't apply here, as we are tracking the effect
646 // of `user_ty` on any bindings contained with subpattern.
647 let annotation = CanonicalUserTypeAnnotation {
648 span: user_ty_span,
649 user_ty: user_ty.user_ty,
650 inferred_ty: subpattern.ty,
651 };
652 let projection = UserTypeProjection {
653 base: self.canonical_user_type_annotations.push(annotation),
654 projs: Vec::new(),
655 };
656 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
657 self.visit_bindings(subpattern, subpattern_user_ty, f)
658 }
659
660 PatternKind::Leaf { ref subpatterns } => {
661 for subpattern in subpatterns {
662 let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
663 debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
664 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
665 }
666 }
667
668 PatternKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
669 for subpattern in subpatterns {
670 let subpattern_user_ty = pattern_user_ty.clone().variant(
671 adt_def, variant_index, subpattern.field);
672 self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
673 }
674 }
675 }
676 }
677 }
678
679 #[derive(Debug)]
680 pub struct Candidate<'pat, 'tcx: 'pat> {
681 // span of the original pattern that gave rise to this candidate
682 span: Span,
683
684 // all of these must be satisfied...
685 match_pairs: Vec<MatchPair<'pat, 'tcx>>,
686
687 // ...these bindings established...
688 bindings: Vec<Binding<'tcx>>,
689
690 // ...and these types asserted...
691 ascriptions: Vec<Ascription<'tcx>>,
692
693 // ...and the guard must be evaluated, if false branch to Block...
694 otherwise_block: Option<BasicBlock>,
695
696 // ...and the blocks for add false edges between candidates
697 pre_binding_block: BasicBlock,
698 next_candidate_pre_binding_block: BasicBlock,
699 }
700
701 #[derive(Clone, Debug)]
702 struct Binding<'tcx> {
703 span: Span,
704 source: Place<'tcx>,
705 name: Name,
706 var_id: NodeId,
707 var_ty: Ty<'tcx>,
708 mutability: Mutability,
709 binding_mode: BindingMode,
710 }
711
712 /// Indicates that the type of `source` must be a subtype of the
713 /// user-given type `user_ty`; this is basically a no-op but can
714 /// influence region inference.
715 #[derive(Clone, Debug)]
716 struct Ascription<'tcx> {
717 span: Span,
718 source: Place<'tcx>,
719 user_ty: PatternTypeProjection<'tcx>,
720 variance: ty::Variance,
721 }
722
723 #[derive(Clone, Debug)]
724 pub struct MatchPair<'pat, 'tcx: 'pat> {
725 // this place...
726 place: Place<'tcx>,
727
728 // ... must match this pattern.
729 pattern: &'pat Pattern<'tcx>,
730 }
731
732 #[derive(Clone, Debug, PartialEq)]
733 enum TestKind<'tcx> {
734 // test the branches of enum
735 Switch {
736 adt_def: &'tcx ty::AdtDef,
737 variants: BitSet<VariantIdx>,
738 },
739
740 // test the branches of enum
741 SwitchInt {
742 switch_ty: Ty<'tcx>,
743 options: Vec<u128>,
744 indices: FxHashMap<ty::Const<'tcx>, usize>,
745 },
746
747 // test for equality
748 Eq {
749 value: ty::Const<'tcx>,
750 ty: Ty<'tcx>,
751 },
752
753 // test whether the value falls within an inclusive or exclusive range
754 Range(PatternRange<'tcx>),
755
756 // test length of the slice is equal to len
757 Len {
758 len: u64,
759 op: BinOp,
760 },
761 }
762
763 #[derive(Debug)]
764 pub struct Test<'tcx> {
765 span: Span,
766 kind: TestKind<'tcx>,
767 }
768
769 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
770 /// a match arm has a guard expression attached to it.
771 #[derive(Copy, Clone, Debug)]
772 pub(crate) struct ArmHasGuard(pub bool);
773
774 ///////////////////////////////////////////////////////////////////////////
775 // Main matching algorithm
776
777 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
778 /// The main match algorithm. It begins with a set of candidates
779 /// `candidates` and has the job of generating code to determine
780 /// which of these candidates, if any, is the correct one. The
781 /// candidates are sorted such that the first item in the list
782 /// has the highest priority. When a candidate is found to match
783 /// the value, we will generate a branch to the appropriate
784 /// prebinding block.
785 ///
786 /// The return value is a list of "otherwise" blocks. These are
787 /// points in execution where we found that *NONE* of the
788 /// candidates apply. In principle, this means that the input
789 /// list was not exhaustive, though at present we sometimes are
790 /// not smart enough to recognize all exhaustive inputs.
791 ///
792 /// It might be surprising that the input can be inexhaustive.
793 /// Indeed, initially, it is not, because all matches are
794 /// exhaustive in Rust. But during processing we sometimes divide
795 /// up the list of candidates and recurse with a non-exhaustive
796 /// list. This is important to keep the size of the generated code
797 /// under control. See `test_candidates` for more details.
798 ///
799 /// If `fake_borrows` is Some, then places which need fake borrows
800 /// will be added to it.
801 fn match_candidates<'pat>(
802 &mut self,
803 span: Span,
804 candidates: &mut [&mut Candidate<'pat, 'tcx>],
805 mut block: BasicBlock,
806 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
807 ) -> Vec<BasicBlock> {
808 debug!(
809 "matched_candidate(span={:?}, block={:?}, candidates={:?})",
810 span, block, candidates
811 );
812
813 // Start by simplifying candidates. Once this process is complete, all
814 // the match pairs which remain require some form of test, whether it
815 // be a switch or pattern comparison.
816 for candidate in &mut *candidates {
817 self.simplify_candidate(candidate);
818 }
819
820 // The candidates are sorted by priority. Check to see whether the
821 // higher priority candidates (and hence at the front of the slice)
822 // have satisfied all their match pairs.
823 let fully_matched = candidates
824 .iter()
825 .take_while(|c| c.match_pairs.is_empty())
826 .count();
827 debug!(
828 "match_candidates: {:?} candidates fully matched",
829 fully_matched
830 );
831 let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
832
833 if !matched_candidates.is_empty() {
834 block = if let Some(last_otherwise_block) = self.select_matched_candidates(
835 matched_candidates,
836 block,
837 fake_borrows,
838 ) {
839 last_otherwise_block
840 } else {
841 // Any remaining candidates are unreachable.
842 if unmatched_candidates.is_empty() {
843 return Vec::new();
844 } else {
845 self.cfg.start_new_block()
846 }
847 };
848 }
849
850 // If there are no candidates that still need testing, we're
851 // done. Since all matches are exhaustive, execution should
852 // never reach this point.
853 if unmatched_candidates.is_empty() {
854 return vec![block];
855 }
856
857 // Test candidates where possible.
858 let (otherwise, untested_candidates) = self.test_candidates(
859 span,
860 unmatched_candidates,
861 block,
862 fake_borrows,
863 );
864
865 // If the target candidates were exhaustive, then we are done.
866 // But for borrowck continue build decision tree.
867 if untested_candidates.is_empty() {
868 return otherwise;
869 }
870
871 // Otherwise, let's process those remaining candidates.
872 let join_block = self.join_otherwise_blocks(span, otherwise);
873 self.match_candidates(
874 span,
875 untested_candidates,
876 join_block,
877 &mut None,
878 )
879 }
880
881 /// Link up matched candidates. For example, if we have something like
882 /// this:
883 ///
884 /// ...
885 /// Some(x) if cond => ...
886 /// Some(x) => ...
887 /// Some(x) if cond => ...
888 /// ...
889 ///
890 /// We generate real edges from:
891 /// * `block` to the prebinding_block of the first pattern,
892 /// * the otherwise block of the first pattern to the second pattern,
893 /// * the otherwise block of the third pattern to the a block with an
894 /// Unreachable terminator.
895 ///
896 /// As well as that we add fake edges from the otherwise blocks to the
897 /// prebinding block of the next candidate in the original set of
898 /// candidates.
899 fn select_matched_candidates(
900 &mut self,
901 matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
902 block: BasicBlock,
903 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
904 ) -> Option<BasicBlock> {
905 debug_assert!(
906 !matched_candidates.is_empty(),
907 "select_matched_candidates called with no candidates",
908 );
909
910 // Insert a borrows of prefixes of places that are bound and are
911 // behind a dereference projection.
912 //
913 // These borrows are taken to avoid situations like the following:
914 //
915 // match x[10] {
916 // _ if { x = &[0]; false } => (),
917 // y => (), // Out of bounds array access!
918 // }
919 //
920 // match *x {
921 // // y is bound by reference in the guard and then by copy in the
922 // // arm, so y is 2 in the arm!
923 // y if { y == 1 && (x = &2) == () } => y,
924 // _ => 3,
925 // }
926 if let Some(fake_borrows) = fake_borrows {
927 for Binding { source, .. }
928 in matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
929 {
930 let mut cursor = source;
931 while let Place::Projection(box Projection { base, elem }) = cursor {
932 cursor = base;
933 if let ProjectionElem::Deref = elem {
934 fake_borrows.insert(cursor.clone());
935 break;
936 }
937 }
938 }
939 }
940
941 let fully_matched_with_guard = matched_candidates
942 .iter()
943 .position(|c| c.otherwise_block.is_none())
944 .unwrap_or(matched_candidates.len() - 1);
945
946 let (reachable_candidates, unreachable_candidates)
947 = matched_candidates.split_at_mut(fully_matched_with_guard + 1);
948
949 let first_candidate = &reachable_candidates[0];
950
951 let candidate_source_info = self.source_info(first_candidate.span);
952
953 self.cfg.terminate(
954 block,
955 candidate_source_info,
956 TerminatorKind::Goto {
957 target: first_candidate.pre_binding_block,
958 },
959 );
960
961 for window in reachable_candidates.windows(2) {
962 if let [first_candidate, second_candidate] = window {
963 let source_info = self.source_info(first_candidate.span);
964 if let Some(otherwise_block) = first_candidate.otherwise_block {
965 self.cfg.terminate(
966 otherwise_block,
967 source_info,
968 TerminatorKind::FalseEdges {
969 real_target: second_candidate.pre_binding_block,
970 imaginary_targets: vec![
971 first_candidate.next_candidate_pre_binding_block
972 ],
973 }
974 )
975 } else {
976 bug!("candidate other than the last has no guard");
977 }
978 } else {
979 bug!("<[_]>::windows returned incorrectly sized window");
980 }
981 }
982
983 debug!("match_candidates: add false edges for unreachable {:?}", unreachable_candidates);
984 for candidate in unreachable_candidates {
985 if let Some(otherwise) = candidate.otherwise_block {
986 let source_info = self.source_info(candidate.span);
987 let unreachable = self.cfg.start_new_block();
988 self.cfg.terminate(
989 otherwise,
990 source_info,
991 TerminatorKind::FalseEdges {
992 real_target: unreachable,
993 imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
994 }
995 );
996 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
997 }
998 }
999
1000 let last_candidate = reachable_candidates.last().unwrap();
1001
1002 if let Some(otherwise) = last_candidate.otherwise_block {
1003 let source_info = self.source_info(last_candidate.span);
1004 let block = self.cfg.start_new_block();
1005 self.cfg.terminate(
1006 otherwise,
1007 source_info,
1008 TerminatorKind::FalseEdges {
1009 real_target: block,
1010 imaginary_targets: vec![last_candidate.next_candidate_pre_binding_block]
1011 }
1012 );
1013 Some(block)
1014 } else {
1015 None
1016 }
1017 }
1018
1019 fn join_otherwise_blocks(&mut self, span: Span, mut otherwise: Vec<BasicBlock>) -> BasicBlock {
1020 let source_info = self.source_info(span);
1021 otherwise.sort();
1022 otherwise.dedup(); // variant switches can introduce duplicate target blocks
1023 if otherwise.len() == 1 {
1024 otherwise[0]
1025 } else {
1026 let join_block = self.cfg.start_new_block();
1027 for block in otherwise {
1028 self.cfg.terminate(
1029 block,
1030 source_info,
1031 TerminatorKind::Goto { target: join_block },
1032 );
1033 }
1034 join_block
1035 }
1036 }
1037
1038 /// This is the most subtle part of the matching algorithm. At
1039 /// this point, the input candidates have been fully simplified,
1040 /// and so we know that all remaining match-pairs require some
1041 /// sort of test. To decide what test to do, we take the highest
1042 /// priority candidate (last one in the list) and extract the
1043 /// first match-pair from the list. From this we decide what kind
1044 /// of test is needed using `test`, defined in the `test` module.
1045 ///
1046 /// *Note:* taking the first match pair is somewhat arbitrary, and
1047 /// we might do better here by choosing more carefully what to
1048 /// test.
1049 ///
1050 /// For example, consider the following possible match-pairs:
1051 ///
1052 /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
1053 /// 2. `x @ 22` -- we will do a `SwitchInt`
1054 /// 3. `x @ 3..5` -- we will do a range test
1055 /// 4. etc.
1056 ///
1057 /// Once we know what sort of test we are going to perform, this
1058 /// Tests may also help us with other candidates. So we walk over
1059 /// the candidates (from high to low priority) and check. This
1060 /// gives us, for each outcome of the test, a transformed list of
1061 /// candidates. For example, if we are testing the current
1062 /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
1063 /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
1064 /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
1065 /// simpler (and, in fact, irrefutable).
1066 ///
1067 /// But there may also be candidates that the test just doesn't
1068 /// apply to. The classical example involves wildcards:
1069 ///
1070 /// ```
1071 /// # let (x, y, z) = (true, true, true);
1072 /// match (x, y, z) {
1073 /// (true, _, true) => true, // (0)
1074 /// (_, true, _) => true, // (1)
1075 /// (false, false, _) => false, // (2)
1076 /// (true, _, false) => false, // (3)
1077 /// }
1078 /// ```
1079 ///
1080 /// In that case, after we test on `x`, there are 2 overlapping candidate
1081 /// sets:
1082 ///
1083 /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1084 /// - If the outcome is that `x` is false, candidates 1 and 2
1085 ///
1086 /// Here, the traditional "decision tree" method would generate 2
1087 /// separate code-paths for the 2 separate cases.
1088 ///
1089 /// In some cases, this duplication can create an exponential amount of
1090 /// code. This is most easily seen by noticing that this method terminates
1091 /// with precisely the reachable arms being reachable - but that problem
1092 /// is trivially NP-complete:
1093 ///
1094 /// ```rust
1095 /// match (var0, var1, var2, var3, ..) {
1096 /// (true, _, _, false, true, ...) => false,
1097 /// (_, true, true, false, _, ...) => false,
1098 /// (false, _, false, false, _, ...) => false,
1099 /// ...
1100 /// _ => true
1101 /// }
1102 /// ```
1103 ///
1104 /// Here the last arm is reachable only if there is an assignment to
1105 /// the variables that does not match any of the literals. Therefore,
1106 /// compilation would take an exponential amount of time in some cases.
1107 ///
1108 /// That kind of exponential worst-case might not occur in practice, but
1109 /// our simplistic treatment of constants and guards would make it occur
1110 /// in very common situations - for example #29740:
1111 ///
1112 /// ```rust
1113 /// match x {
1114 /// "foo" if foo_guard => ...,
1115 /// "bar" if bar_guard => ...,
1116 /// "baz" if baz_guard => ...,
1117 /// ...
1118 /// }
1119 /// ```
1120 ///
1121 /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1122 ///
1123 /// It might seem that we would end up with 2 disjoint candidate
1124 /// sets, consisting of the first candidate or the other 3, but our
1125 /// algorithm doesn't reason about "foo" being distinct from the other
1126 /// constants; it considers the latter arms to potentially match after
1127 /// both outcomes, which obviously leads to an exponential amount
1128 /// of tests.
1129 ///
1130 /// To avoid these kinds of problems, our algorithm tries to ensure
1131 /// the amount of generated tests is linear. When we do a k-way test,
1132 /// we return an additional "unmatched" set alongside the obvious `k`
1133 /// sets. When we encounter a candidate that would be present in more
1134 /// than one of the sets, we put it and all candidates below it into the
1135 /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1136 ///
1137 /// After we perform our test, we branch into the appropriate candidate
1138 /// set and recurse with `match_candidates`. These sub-matches are
1139 /// obviously inexhaustive - as we discarded our otherwise set - so
1140 /// we set their continuation to do `match_candidates` on the
1141 /// "unmatched" set (which is again inexhaustive).
1142 ///
1143 /// If you apply this to the above test, you basically wind up
1144 /// with an if-else-if chain, testing each candidate in turn,
1145 /// which is precisely what we want.
1146 ///
1147 /// In addition to avoiding exponential-time blowups, this algorithm
1148 /// also has nice property that each guard and arm is only generated
1149 /// once.
1150 fn test_candidates<'pat, 'b, 'c>(
1151 &mut self,
1152 span: Span,
1153 mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1154 block: BasicBlock,
1155 fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1156 ) -> (Vec<BasicBlock>, &'b mut [&'c mut Candidate<'pat, 'tcx>]) {
1157 // extract the match-pair from the highest priority candidate
1158 let match_pair = &candidates.first().unwrap().match_pairs[0];
1159 let mut test = self.test(match_pair);
1160 let match_place = match_pair.place.clone();
1161
1162 // most of the time, the test to perform is simply a function
1163 // of the main candidate; but for a test like SwitchInt, we
1164 // may want to add cases based on the candidates that are
1165 // available
1166 match test.kind {
1167 TestKind::SwitchInt {
1168 switch_ty,
1169 ref mut options,
1170 ref mut indices,
1171 } => {
1172 for candidate in candidates.iter() {
1173 if !self.add_cases_to_switch(
1174 &match_place,
1175 candidate,
1176 switch_ty,
1177 options,
1178 indices,
1179 ) {
1180 break;
1181 }
1182 }
1183 }
1184 TestKind::Switch {
1185 adt_def: _,
1186 ref mut variants,
1187 } => {
1188 for candidate in candidates.iter() {
1189 if !self.add_variants_to_switch(&match_place, candidate, variants) {
1190 break;
1191 }
1192 }
1193 }
1194 _ => {}
1195 }
1196
1197 // Insert a Shallow borrow of any places that is switched on.
1198 fake_borrows.as_mut().map(|fb| {
1199 fb.insert(match_place.clone())
1200 });
1201
1202 // perform the test, branching to one of N blocks. For each of
1203 // those N possible outcomes, create a (initially empty)
1204 // vector of candidates. Those are the candidates that still
1205 // apply if the test has that particular outcome.
1206 debug!(
1207 "match_candidates: test={:?} match_pair={:?}",
1208 test, match_pair
1209 );
1210 let target_blocks = self.perform_test(block, &match_place, &test);
1211 let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1212 target_candidates.resize_with(target_blocks.len(), Default::default);
1213
1214 let total_candidate_count = candidates.len();
1215
1216 // Sort the candidates into the appropriate vector in
1217 // `target_candidates`. Note that at some point we may
1218 // encounter a candidate where the test is not relevant; at
1219 // that point, we stop sorting.
1220 while let Some(candidate) = candidates.first_mut() {
1221 if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1222 let (candidate, rest) = candidates.split_first_mut().unwrap();
1223 target_candidates[idx].push(candidate);
1224 candidates = rest;
1225 } else {
1226 break;
1227 }
1228 }
1229 // at least the first candidate ought to be tested
1230 assert!(total_candidate_count > candidates.len());
1231 debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1232 debug!("untested_candidates: {}", candidates.len());
1233
1234 // For each outcome of test, process the candidates that still
1235 // apply. Collect a list of blocks where control flow will
1236 // branch if one of the `target_candidate` sets is not
1237 // exhaustive.
1238 let otherwise: Vec<_> = target_blocks
1239 .into_iter()
1240 .zip(target_candidates)
1241 .flat_map(|(target_block, mut target_candidates)| {
1242 self.match_candidates(
1243 span,
1244 &mut *target_candidates,
1245 target_block,
1246 fake_borrows,
1247 )
1248 })
1249 .collect();
1250
1251 (otherwise, candidates)
1252 }
1253
1254 // Determine the fake borrows that are needed to ensure that the place
1255 // will evaluate to the same thing until an arm has been chosen.
1256 fn calculate_fake_borrows<'b>(
1257 &mut self,
1258 fake_borrows: &'b FxHashSet<Place<'tcx>>,
1259 temp_span: Span,
1260 ) -> Vec<(&'b Place<'tcx>, Local)> {
1261 let tcx = self.hir.tcx();
1262
1263 debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1264
1265 let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1266
1267 // Insert a Shallow borrow of the prefixes of any fake borrows.
1268 for place in fake_borrows
1269 {
1270 let mut prefix_cursor = place;
1271 while let Place::Projection(box Projection { base, elem }) = prefix_cursor {
1272 if let ProjectionElem::Deref = elem {
1273 // Insert a shallow borrow after a deref. For other
1274 // projections the borrow of prefix_cursor will
1275 // conflict with any mutation of base.
1276 all_fake_borrows.push(base);
1277 }
1278 prefix_cursor = base;
1279 }
1280
1281 all_fake_borrows.push(place);
1282 }
1283
1284 // Deduplicate and ensure a deterministic order.
1285 all_fake_borrows.sort();
1286 all_fake_borrows.dedup();
1287
1288 debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1289
1290 all_fake_borrows.into_iter().map(|matched_place| {
1291 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).to_ty(tcx);
1292 let fake_borrow_ty = tcx.mk_imm_ref(tcx.types.re_erased, fake_borrow_deref_ty);
1293 let fake_borrow_temp = self.local_decls.push(
1294 LocalDecl::new_temp(fake_borrow_ty, temp_span)
1295 );
1296
1297 (matched_place, fake_borrow_temp)
1298 }).collect()
1299 }
1300 }
1301
1302 ///////////////////////////////////////////////////////////////////////////
1303 // Pattern binding - used for `let` and function parameters as well.
1304
1305 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
1306 /// Initializes each of the bindings from the candidate by
1307 /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1308 /// any, and then branches to the arm. Returns the block for the case where
1309 /// the guard fails.
1310 ///
1311 /// Note: we check earlier that if there is a guard, there cannot be move
1312 /// bindings (unless feature(bind_by_move_pattern_guards) is used). This
1313 /// isn't really important for the self-consistency of this fn, but the
1314 /// reason for it should be clear: after we've done the assignments, if
1315 /// there were move bindings, further tests would be a use-after-move.
1316 /// bind_by_move_pattern_guards avoids this by only moving the binding once
1317 /// the guard has evaluated to true (see below).
1318 fn bind_and_guard_matched_candidate<'pat>(
1319 &mut self,
1320 candidate: Candidate<'pat, 'tcx>,
1321 guard: Option<Guard<'tcx>>,
1322 arm_block: BasicBlock,
1323 fake_borrows: &Vec<(&Place<'tcx>, Local)>,
1324 scrutinee_span: Span,
1325 ) {
1326 debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1327
1328 debug_assert!(candidate.match_pairs.is_empty());
1329
1330 let candidate_source_info = self.source_info(candidate.span);
1331
1332 let mut block = self.cfg.start_new_block();
1333 self.cfg.terminate(
1334 candidate.pre_binding_block,
1335 candidate_source_info,
1336 TerminatorKind::FalseEdges {
1337 real_target: block,
1338 imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
1339 },
1340 );
1341 self.ascribe_types(block, &candidate.ascriptions);
1342
1343 // rust-lang/rust#27282: The `autoref` business deserves some
1344 // explanation here.
1345 //
1346 // The intent of the `autoref` flag is that when it is true,
1347 // then any pattern bindings of type T will map to a `&T`
1348 // within the context of the guard expression, but will
1349 // continue to map to a `T` in the context of the arm body. To
1350 // avoid surfacing this distinction in the user source code
1351 // (which would be a severe change to the language and require
1352 // far more revision to the compiler), when `autoref` is true,
1353 // then any occurrence of the identifier in the guard
1354 // expression will automatically get a deref op applied to it.
1355 //
1356 // So an input like:
1357 //
1358 // ```
1359 // let place = Foo::new();
1360 // match place { foo if inspect(foo)
1361 // => feed(foo), ... }
1362 // ```
1363 //
1364 // will be treated as if it were really something like:
1365 //
1366 // ```
1367 // let place = Foo::new();
1368 // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1369 // => { let tmp2 = place; feed(tmp2) }, ... }
1370 //
1371 // And an input like:
1372 //
1373 // ```
1374 // let place = Foo::new();
1375 // match place { ref mut foo if inspect(foo)
1376 // => feed(foo), ... }
1377 // ```
1378 //
1379 // will be treated as if it were really something like:
1380 //
1381 // ```
1382 // let place = Foo::new();
1383 // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1384 // => { let tmp2 = &mut place; feed(tmp2) }, ... }
1385 // ```
1386 //
1387 // In short, any pattern binding will always look like *some*
1388 // kind of `&T` within the guard at least in terms of how the
1389 // MIR-borrowck views it, and this will ensure that guard
1390 // expressions cannot mutate their the match inputs via such
1391 // bindings. (It also ensures that guard expressions can at
1392 // most *copy* values from such bindings; non-Copy things
1393 // cannot be moved via pattern bindings in guard expressions.)
1394 //
1395 // ----
1396 //
1397 // Implementation notes (under assumption `autoref` is true).
1398 //
1399 // To encode the distinction above, we must inject the
1400 // temporaries `tmp1` and `tmp2`.
1401 //
1402 // There are two cases of interest: binding by-value, and binding by-ref.
1403 //
1404 // 1. Binding by-value: Things are simple.
1405 //
1406 // * Establishing `tmp1` creates a reference into the
1407 // matched place. This code is emitted by
1408 // bind_matched_candidate_for_guard.
1409 //
1410 // * `tmp2` is only initialized "lazily", after we have
1411 // checked the guard. Thus, the code that can trigger
1412 // moves out of the candidate can only fire after the
1413 // guard evaluated to true. This initialization code is
1414 // emitted by bind_matched_candidate_for_arm.
1415 //
1416 // 2. Binding by-reference: Things are tricky.
1417 //
1418 // * Here, the guard expression wants a `&&` or `&&mut`
1419 // into the original input. This means we need to borrow
1420 // the reference that we create for the arm.
1421 // * So we eagerly create the reference for the arm and then take a
1422 // reference to that.
1423 let tcx = self.hir.tcx();
1424 let autoref = tcx.all_pat_vars_are_implicit_refs_within_guards();
1425 if let Some(guard) = guard {
1426 if autoref {
1427 self.bind_matched_candidate_for_guard(
1428 block,
1429 &candidate.bindings,
1430 );
1431 let guard_frame = GuardFrame {
1432 locals: candidate
1433 .bindings
1434 .iter()
1435 .map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode))
1436 .collect(),
1437 };
1438 debug!("Entering guard building context: {:?}", guard_frame);
1439 self.guard_context.push(guard_frame);
1440 } else {
1441 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
1442 }
1443
1444 let re_erased = tcx.types.re_erased;
1445 let scrutinee_source_info = self.source_info(scrutinee_span);
1446 for &(place, temp) in fake_borrows {
1447 let borrow = Rvalue::Ref(
1448 re_erased,
1449 BorrowKind::Shallow,
1450 place.clone(),
1451 );
1452 self.cfg.push_assign(
1453 block,
1454 scrutinee_source_info,
1455 &Place::Local(temp),
1456 borrow,
1457 );
1458 }
1459
1460 // the block to branch to if the guard fails; if there is no
1461 // guard, this block is simply unreachable
1462 let guard = match guard {
1463 Guard::If(e) => self.hir.mirror(e),
1464 };
1465 let source_info = self.source_info(guard.span);
1466 let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span));
1467 let cond = unpack!(block = self.as_local_operand(block, guard));
1468 if autoref {
1469 let guard_frame = self.guard_context.pop().unwrap();
1470 debug!(
1471 "Exiting guard building context with locals: {:?}",
1472 guard_frame
1473 );
1474 }
1475
1476 for &(_, temp) in fake_borrows {
1477 self.cfg.push(block, Statement {
1478 source_info: guard_end,
1479 kind: StatementKind::FakeRead(
1480 FakeReadCause::ForMatchGuard,
1481 Place::Local(temp),
1482 ),
1483 });
1484 }
1485
1486 // We want to ensure that the matched candidates are bound
1487 // after we have confirmed this candidate *and* any
1488 // associated guard; Binding them on `block` is too soon,
1489 // because that would be before we've checked the result
1490 // from the guard.
1491 //
1492 // But binding them on `arm_block` is *too late*, because
1493 // then all of the candidates for a single arm would be
1494 // bound in the same place, that would cause a case like:
1495 //
1496 // ```rust
1497 // match (30, 2) {
1498 // (mut x, 1) | (2, mut x) if { true } => { ... }
1499 // ... // ^^^^^^^ (this is `arm_block`)
1500 // }
1501 // ```
1502 //
1503 // would yield a `arm_block` something like:
1504 //
1505 // ```
1506 // StorageLive(_4); // _4 is `x`
1507 // _4 = &mut (_1.0: i32); // this is handling `(mut x, 1)` case
1508 // _4 = &mut (_1.1: i32); // this is handling `(2, mut x)` case
1509 // ```
1510 //
1511 // and that is clearly not correct.
1512 let post_guard_block = self.cfg.start_new_block();
1513 self.cfg.terminate(
1514 block,
1515 source_info,
1516 TerminatorKind::if_(
1517 self.hir.tcx(),
1518 cond,
1519 post_guard_block,
1520 candidate.otherwise_block.unwrap()
1521 ),
1522 );
1523
1524 if autoref {
1525 let by_value_bindings = candidate.bindings.iter().filter(|binding| {
1526 if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1527 });
1528 // Read all of the by reference bindings to ensure that the
1529 // place they refer to can't be modified by the guard.
1530 for binding in by_value_bindings.clone() {
1531 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1532 let place = Place::Local(local_id);
1533 self.cfg.push(
1534 block,
1535 Statement {
1536 source_info: guard_end,
1537 kind: StatementKind::FakeRead(FakeReadCause::ForGuardBinding, place),
1538 },
1539 );
1540 }
1541 self.bind_matched_candidate_for_arm_body(
1542 post_guard_block,
1543 by_value_bindings,
1544 );
1545 }
1546
1547 self.cfg.terminate(
1548 post_guard_block,
1549 source_info,
1550 TerminatorKind::Goto { target: arm_block },
1551 );
1552 } else {
1553 assert!(candidate.otherwise_block.is_none());
1554 // (Here, it is not too early to bind the matched
1555 // candidate on `block`, because there is no guard result
1556 // that we have to inspect before we bind them.)
1557 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
1558 self.cfg.terminate(
1559 block,
1560 candidate_source_info,
1561 TerminatorKind::Goto { target: arm_block },
1562 );
1563 }
1564 }
1565
1566 /// Append `AscribeUserType` statements onto the end of `block`
1567 /// for each ascription
1568 fn ascribe_types<'pat>(
1569 &mut self,
1570 block: BasicBlock,
1571 ascriptions: &[Ascription<'tcx>],
1572 ) {
1573 for ascription in ascriptions {
1574 let source_info = self.source_info(ascription.span);
1575
1576 debug!(
1577 "adding user ascription at span {:?} of place {:?} and {:?}",
1578 source_info.span,
1579 ascription.source,
1580 ascription.user_ty,
1581 );
1582
1583 let user_ty = box ascription.user_ty.clone().user_ty(
1584 &mut self.canonical_user_type_annotations,
1585 ascription.source.ty(&self.local_decls, self.hir.tcx()).to_ty(self.hir.tcx()),
1586 source_info.span
1587 );
1588 self.cfg.push(
1589 block,
1590 Statement {
1591 source_info,
1592 kind: StatementKind::AscribeUserType(
1593 ascription.source.clone(),
1594 ascription.variance,
1595 user_ty,
1596 ),
1597 },
1598 );
1599 }
1600 }
1601
1602 // Only called when all_pat_vars_are_implicit_refs_within_guards,
1603 // and thus all code/comments assume we are in that context.
1604 fn bind_matched_candidate_for_guard(
1605 &mut self,
1606 block: BasicBlock,
1607 bindings: &[Binding<'tcx>],
1608 ) {
1609 debug!("bind_matched_candidate_for_guard(block={:?}, bindings={:?})", block, bindings);
1610
1611 // Assign each of the bindings. Since we are binding for a
1612 // guard expression, this will never trigger moves out of the
1613 // candidate.
1614 let re_erased = self.hir.tcx().types.re_erased;
1615 for binding in bindings {
1616 let source_info = self.source_info(binding.span);
1617
1618 // For each pattern ident P of type T, `ref_for_guard` is
1619 // a reference R: &T pointing to the location matched by
1620 // the pattern, and every occurrence of P within a guard
1621 // denotes *R.
1622 let ref_for_guard =
1623 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1624 // Question: Why schedule drops if bindings are all
1625 // shared-&'s?
1626 // Answer: Because schedule_drop_for_binding also emits
1627 // StorageDead's for those locals.
1628 self.schedule_drop_for_binding(binding.var_id, binding.span, RefWithinGuard);
1629 match binding.binding_mode {
1630 BindingMode::ByValue => {
1631 let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source.clone());
1632 self.cfg
1633 .push_assign(block, source_info, &ref_for_guard, rvalue);
1634 }
1635 BindingMode::ByRef(borrow_kind) => {
1636 let value_for_arm = self.storage_live_binding(
1637 block,
1638 binding.var_id,
1639 binding.span,
1640 OutsideGuard,
1641 );
1642 self.schedule_drop_for_binding(
1643 binding.var_id,
1644 binding.span,
1645 OutsideGuard,
1646 );
1647
1648 let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source.clone());
1649 self.cfg
1650 .push_assign(block, source_info, &value_for_arm, rvalue);
1651 let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1652 self.cfg
1653 .push_assign(block, source_info, &ref_for_guard, rvalue);
1654 }
1655 }
1656 }
1657 }
1658
1659 fn bind_matched_candidate_for_arm_body<'b>(
1660 &mut self,
1661 block: BasicBlock,
1662 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1663 ) where 'tcx: 'b {
1664 debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1665
1666 let re_erased = self.hir.tcx().types.re_erased;
1667 // Assign each of the bindings. This may trigger moves out of the candidate.
1668 for binding in bindings {
1669 let source_info = self.source_info(binding.span);
1670 let local =
1671 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1672 self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1673 let rvalue = match binding.binding_mode {
1674 BindingMode::ByValue => {
1675 Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1676 }
1677 BindingMode::ByRef(borrow_kind) => {
1678 Rvalue::Ref(re_erased, borrow_kind, binding.source.clone())
1679 }
1680 };
1681 self.cfg.push_assign(block, source_info, &local, rvalue);
1682 }
1683 }
1684
1685 /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1686 /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1687 /// first local is a binding for occurrences of `var` in the guard, which
1688 /// will have type `&T`. The second local is a binding for occurrences of
1689 /// `var` in the arm body, which will have type `T`.
1690 fn declare_binding(
1691 &mut self,
1692 source_info: SourceInfo,
1693 visibility_scope: SourceScope,
1694 mutability: Mutability,
1695 name: Name,
1696 mode: BindingMode,
1697 var_id: NodeId,
1698 var_ty: Ty<'tcx>,
1699 user_ty: UserTypeProjections<'tcx>,
1700 has_guard: ArmHasGuard,
1701 opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1702 pat_span: Span,
1703 ) {
1704 debug!(
1705 "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1706 visibility_scope={:?}, source_info={:?})",
1707 var_id, name, mode, var_ty, visibility_scope, source_info
1708 );
1709
1710 let tcx = self.hir.tcx();
1711 let binding_mode = match mode {
1712 BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1713 BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability.into()),
1714 };
1715 debug!("declare_binding: user_ty={:?}", user_ty);
1716 let local = LocalDecl::<'tcx> {
1717 mutability,
1718 ty: var_ty,
1719 user_ty,
1720 name: Some(name),
1721 source_info,
1722 visibility_scope,
1723 internal: false,
1724 is_block_tail: None,
1725 is_user_variable: Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1726 binding_mode,
1727 // hypothetically, `visit_bindings` could try to unzip
1728 // an outermost hir::Ty as we descend, matching up
1729 // idents in pat; but complex w/ unclear UI payoff.
1730 // Instead, just abandon providing diagnostic info.
1731 opt_ty_info: None,
1732 opt_match_place,
1733 pat_span,
1734 }))),
1735 };
1736 let for_arm_body = self.local_decls.push(local.clone());
1737 let locals = if has_guard.0 && tcx.all_pat_vars_are_implicit_refs_within_guards() {
1738 let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1739 // This variable isn't mutated but has a name, so has to be
1740 // immutable to avoid the unused mut lint.
1741 mutability: Mutability::Not,
1742 ty: tcx.mk_imm_ref(tcx.types.re_erased, var_ty),
1743 user_ty: UserTypeProjections::none(),
1744 name: Some(name),
1745 source_info,
1746 visibility_scope,
1747 internal: false,
1748 is_block_tail: None,
1749 is_user_variable: Some(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1750 });
1751 LocalsForNode::ForGuard {
1752 ref_for_guard,
1753 for_arm_body,
1754 }
1755 } else {
1756 LocalsForNode::One(for_arm_body)
1757 };
1758 debug!("declare_binding: vars={:?}", locals);
1759 self.var_indices.insert(var_id, locals);
1760 }
1761 }