]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/matches/mod.rs
Auto merge of #94477 - matthiaskrgr:rollup-8h29qek, r=matthiaskrgr
[rust.git] / compiler / rustc_mir_build / src / 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::expr::as_place::PlaceBuilder;
9 use crate::build::scope::DropKind;
10 use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard};
11 use crate::build::{BlockAnd, BlockAndExtension, Builder};
12 use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode};
13 use rustc_data_structures::{
14     fx::{FxHashSet, FxIndexMap},
15     stack::ensure_sufficient_stack,
16 };
17 use rustc_hir::HirId;
18 use rustc_index::bit_set::BitSet;
19 use rustc_middle::middle::region;
20 use rustc_middle::mir::*;
21 use rustc_middle::thir::{self, *};
22 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty};
23 use rustc_span::symbol::Symbol;
24 use rustc_span::{BytePos, Pos, Span};
25 use rustc_target::abi::VariantIdx;
26 use smallvec::{smallvec, SmallVec};
27
28 // helper functions, broken out by category:
29 mod simplify;
30 mod test;
31 mod util;
32
33 use std::borrow::Borrow;
34 use std::convert::TryFrom;
35 use std::mem;
36
37 impl<'a, 'tcx> Builder<'a, 'tcx> {
38     pub(crate) fn then_else_break(
39         &mut self,
40         mut block: BasicBlock,
41         expr: &Expr<'tcx>,
42         temp_scope_override: Option<region::Scope>,
43         break_scope: region::Scope,
44         variable_scope_span: Span,
45     ) -> BlockAnd<()> {
46         let this = self;
47         let expr_span = expr.span;
48
49         match expr.kind {
50             ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
51                 let lhs_then_block = unpack!(this.then_else_break(
52                     block,
53                     &this.thir[lhs],
54                     temp_scope_override,
55                     break_scope,
56                     variable_scope_span,
57                 ));
58
59                 let rhs_then_block = unpack!(this.then_else_break(
60                     lhs_then_block,
61                     &this.thir[rhs],
62                     temp_scope_override,
63                     break_scope,
64                     variable_scope_span,
65                 ));
66
67                 rhs_then_block.unit()
68             }
69             ExprKind::Scope { region_scope, lint_level, value } => {
70                 let region_scope = (region_scope, this.source_info(expr_span));
71                 this.in_scope(region_scope, lint_level, |this| {
72                     this.then_else_break(
73                         block,
74                         &this.thir[value],
75                         temp_scope_override,
76                         break_scope,
77                         variable_scope_span,
78                     )
79                 })
80             }
81             ExprKind::Let { expr, ref pat } => {
82                 this.lower_let_expr(block, &this.thir[expr], pat, break_scope, variable_scope_span)
83             }
84             _ => {
85                 let temp_scope = temp_scope_override.unwrap_or_else(|| this.local_scope());
86                 let mutability = Mutability::Mut;
87                 let place =
88                     unpack!(block = this.as_temp(block, Some(temp_scope), expr, mutability));
89                 let operand = Operand::Move(Place::from(place));
90
91                 let then_block = this.cfg.start_new_block();
92                 let else_block = this.cfg.start_new_block();
93                 let term = TerminatorKind::if_(this.tcx, operand, then_block, else_block);
94
95                 let source_info = this.source_info(expr_span);
96                 this.cfg.terminate(block, source_info, term);
97                 this.break_for_else(else_block, break_scope, source_info);
98
99                 then_block.unit()
100             }
101         }
102     }
103
104     /// Generates MIR for a `match` expression.
105     ///
106     /// The MIR that we generate for a match looks like this.
107     ///
108     /// ```text
109     /// [ 0. Pre-match ]
110     ///        |
111     /// [ 1. Evaluate Scrutinee (expression being matched on) ]
112     /// [ (fake read of scrutinee) ]
113     ///        |
114     /// [ 2. Decision tree -- check discriminants ] <--------+
115     ///        |                                             |
116     ///        | (once a specific arm is chosen)             |
117     ///        |                                             |
118     /// [pre_binding_block]                           [otherwise_block]
119     ///        |                                             |
120     /// [ 3. Create "guard bindings" for arm ]               |
121     /// [ (create fake borrows) ]                            |
122     ///        |                                             |
123     /// [ 4. Execute guard code ]                            |
124     /// [ (read fake borrows) ] --(guard is false)-----------+
125     ///        |
126     ///        | (guard results in true)
127     ///        |
128     /// [ 5. Create real bindings and execute arm ]
129     ///        |
130     /// [ Exit match ]
131     /// ```
132     ///
133     /// All of the different arms have been stacked on top of each other to
134     /// simplify the diagram. For an arm with no guard the blocks marked 3 and
135     /// 4 and the fake borrows are omitted.
136     ///
137     /// We generate MIR in the following steps:
138     ///
139     /// 1. Evaluate the scrutinee and add the fake read of it ([Builder::lower_scrutinee]).
140     /// 2. Create the decision tree ([Builder::lower_match_tree]).
141     /// 3. Determine the fake borrows that are needed from the places that were
142     ///    matched against and create the required temporaries for them
143     ///    ([Builder::calculate_fake_borrows]).
144     /// 4. Create everything else: the guards and the arms ([Builder::lower_match_arms]).
145     ///
146     /// ## False edges
147     ///
148     /// We don't want to have the exact structure of the decision tree be
149     /// visible through borrow checking. False edges ensure that the CFG as
150     /// seen by borrow checking doesn't encode this. False edges are added:
151     ///
152     /// * From each pre-binding block to the next pre-binding block.
153     /// * From each otherwise block to the next pre-binding block.
154     crate fn match_expr(
155         &mut self,
156         destination: Place<'tcx>,
157         span: Span,
158         mut block: BasicBlock,
159         scrutinee: &Expr<'tcx>,
160         arms: &[ArmId],
161     ) -> BlockAnd<()> {
162         let scrutinee_span = scrutinee.span;
163         let scrutinee_place =
164             unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,));
165
166         let mut arm_candidates = self.create_match_candidates(scrutinee_place.clone(), &arms);
167
168         let match_has_guard = arms.iter().copied().any(|arm| self.thir[arm].guard.is_some());
169         let mut candidates =
170             arm_candidates.iter_mut().map(|(_, candidate)| candidate).collect::<Vec<_>>();
171
172         let match_start_span = span.shrink_to_lo().to(scrutinee.span);
173
174         let fake_borrow_temps = self.lower_match_tree(
175             block,
176             scrutinee_span,
177             match_start_span,
178             match_has_guard,
179             &mut candidates,
180         );
181
182         self.lower_match_arms(
183             destination,
184             scrutinee_place,
185             scrutinee_span,
186             arm_candidates,
187             self.source_info(span),
188             fake_borrow_temps,
189         )
190     }
191
192     /// Evaluate the scrutinee and add the fake read of it.
193     fn lower_scrutinee(
194         &mut self,
195         mut block: BasicBlock,
196         scrutinee: &Expr<'tcx>,
197         scrutinee_span: Span,
198     ) -> BlockAnd<PlaceBuilder<'tcx>> {
199         let scrutinee_place_builder = unpack!(block = self.as_place_builder(block, scrutinee));
200         // Matching on a `scrutinee_place` with an uninhabited type doesn't
201         // generate any memory reads by itself, and so if the place "expression"
202         // contains unsafe operations like raw pointer dereferences or union
203         // field projections, we wouldn't know to require an `unsafe` block
204         // around a `match` equivalent to `std::intrinsics::unreachable()`.
205         // See issue #47412 for this hole being discovered in the wild.
206         //
207         // HACK(eddyb) Work around the above issue by adding a dummy inspection
208         // of `scrutinee_place`, specifically by applying `ReadForMatch`.
209         //
210         // NOTE: ReadForMatch also checks that the scrutinee is initialized.
211         // This is currently needed to not allow matching on an uninitialized,
212         // uninhabited value. If we get never patterns, those will check that
213         // the place is initialized, and so this read would only be used to
214         // check safety.
215         let cause_matched_place = FakeReadCause::ForMatchedPlace(None);
216         let source_info = self.source_info(scrutinee_span);
217
218         if let Ok(scrutinee_builder) =
219             scrutinee_place_builder.clone().try_upvars_resolved(self.tcx, self.typeck_results)
220         {
221             let scrutinee_place = scrutinee_builder.into_place(self.tcx, self.typeck_results);
222             self.cfg.push_fake_read(block, source_info, cause_matched_place, scrutinee_place);
223         }
224
225         block.and(scrutinee_place_builder)
226     }
227
228     /// Create the initial `Candidate`s for a `match` expression.
229     fn create_match_candidates<'pat>(
230         &mut self,
231         scrutinee: PlaceBuilder<'tcx>,
232         arms: &'pat [ArmId],
233     ) -> Vec<(&'pat Arm<'tcx>, Candidate<'pat, 'tcx>)>
234     where
235         'a: 'pat,
236     {
237         // Assemble a list of candidates: there is one candidate per pattern,
238         // which means there may be more than one candidate *per arm*.
239         arms.iter()
240             .copied()
241             .map(|arm| {
242                 let arm = &self.thir[arm];
243                 let arm_has_guard = arm.guard.is_some();
244                 let arm_candidate = Candidate::new(scrutinee.clone(), &arm.pattern, arm_has_guard);
245                 (arm, arm_candidate)
246             })
247             .collect()
248     }
249
250     /// Create the decision tree for the match expression, starting from `block`.
251     ///
252     /// Modifies `candidates` to store the bindings and type ascriptions for
253     /// that candidate.
254     ///
255     /// Returns the places that need fake borrows because we bind or test them.
256     fn lower_match_tree<'pat>(
257         &mut self,
258         block: BasicBlock,
259         scrutinee_span: Span,
260         match_start_span: Span,
261         match_has_guard: bool,
262         candidates: &mut [&mut Candidate<'pat, 'tcx>],
263     ) -> Vec<(Place<'tcx>, Local)> {
264         // The set of places that we are creating fake borrows of. If there are
265         // no match guards then we don't need any fake borrows, so don't track
266         // them.
267         let mut fake_borrows = match_has_guard.then(FxHashSet::default);
268
269         let mut otherwise = None;
270
271         // This will generate code to test scrutinee_place and
272         // branch to the appropriate arm block
273         self.match_candidates(
274             match_start_span,
275             scrutinee_span,
276             block,
277             &mut otherwise,
278             candidates,
279             &mut fake_borrows,
280         );
281
282         if let Some(otherwise_block) = otherwise {
283             // See the doc comment on `match_candidates` for why we may have an
284             // otherwise block. Match checking will ensure this is actually
285             // unreachable.
286             let source_info = self.source_info(scrutinee_span);
287             self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
288         }
289
290         // Link each leaf candidate to the `pre_binding_block` of the next one.
291         let mut previous_candidate: Option<&mut Candidate<'_, '_>> = None;
292
293         for candidate in candidates {
294             candidate.visit_leaves(|leaf_candidate| {
295                 if let Some(ref mut prev) = previous_candidate {
296                     prev.next_candidate_pre_binding_block = leaf_candidate.pre_binding_block;
297                 }
298                 previous_candidate = Some(leaf_candidate);
299             });
300         }
301
302         if let Some(ref borrows) = fake_borrows {
303             self.calculate_fake_borrows(borrows, scrutinee_span)
304         } else {
305             Vec::new()
306         }
307     }
308
309     /// Lower the bindings, guards and arm bodies of a `match` expression.
310     ///
311     /// The decision tree should have already been created
312     /// (by [Builder::lower_match_tree]).
313     ///
314     /// `outer_source_info` is the SourceInfo for the whole match.
315     fn lower_match_arms(
316         &mut self,
317         destination: Place<'tcx>,
318         scrutinee_place_builder: PlaceBuilder<'tcx>,
319         scrutinee_span: Span,
320         arm_candidates: Vec<(&'_ Arm<'tcx>, Candidate<'_, 'tcx>)>,
321         outer_source_info: SourceInfo,
322         fake_borrow_temps: Vec<(Place<'tcx>, Local)>,
323     ) -> BlockAnd<()> {
324         let arm_end_blocks: Vec<_> = arm_candidates
325             .into_iter()
326             .map(|(arm, candidate)| {
327                 debug!("lowering arm {:?}\ncandidate = {:?}", arm, candidate);
328
329                 let arm_source_info = self.source_info(arm.span);
330                 let arm_scope = (arm.scope, arm_source_info);
331                 let match_scope = self.local_scope();
332                 self.in_scope(arm_scope, arm.lint_level, |this| {
333                     // `try_upvars_resolved` may fail if it is unable to resolve the given
334                     // `PlaceBuilder` inside a closure. In this case, we don't want to include
335                     // a scrutinee place. `scrutinee_place_builder` will fail to be resolved
336                     // if the only match arm is a wildcard (`_`).
337                     // Example:
338                     // ```
339                     // let foo = (0, 1);
340                     // let c = || {
341                     //    match foo { _ => () };
342                     // };
343                     // ```
344                     let mut opt_scrutinee_place: Option<(Option<&Place<'tcx>>, Span)> = None;
345                     let scrutinee_place: Place<'tcx>;
346                     if let Ok(scrutinee_builder) = scrutinee_place_builder
347                         .clone()
348                         .try_upvars_resolved(this.tcx, this.typeck_results)
349                     {
350                         scrutinee_place =
351                             scrutinee_builder.into_place(this.tcx, this.typeck_results);
352                         opt_scrutinee_place = Some((Some(&scrutinee_place), scrutinee_span));
353                     }
354                     let scope = this.declare_bindings(
355                         None,
356                         arm.span,
357                         &arm.pattern,
358                         ArmHasGuard(arm.guard.is_some()),
359                         opt_scrutinee_place,
360                     );
361
362                     let arm_block = this.bind_pattern(
363                         outer_source_info,
364                         candidate,
365                         arm.guard.as_ref(),
366                         &fake_borrow_temps,
367                         scrutinee_span,
368                         Some(arm.span),
369                         Some(arm.scope),
370                         Some(match_scope),
371                     );
372
373                     if let Some(source_scope) = scope {
374                         this.source_scope = source_scope;
375                     }
376
377                     this.expr_into_dest(destination, arm_block, &&this.thir[arm.body])
378                 })
379             })
380             .collect();
381
382         // all the arm blocks will rejoin here
383         let end_block = self.cfg.start_new_block();
384
385         let end_brace = self.source_info(
386             outer_source_info.span.with_lo(outer_source_info.span.hi() - BytePos::from_usize(1)),
387         );
388         for arm_block in arm_end_blocks {
389             let block = &self.cfg.basic_blocks[arm_block.0];
390             let last_location = block.statements.last().map(|s| s.source_info);
391
392             self.cfg.goto(unpack!(arm_block), last_location.unwrap_or(end_brace), end_block);
393         }
394
395         self.source_scope = outer_source_info.scope;
396
397         end_block.unit()
398     }
399
400     /// Binds the variables and ascribes types for a given `match` arm or
401     /// `let` binding.
402     ///
403     /// Also check if the guard matches, if it's provided.
404     /// `arm_scope` should be `Some` if and only if this is called for a
405     /// `match` arm.
406     fn bind_pattern(
407         &mut self,
408         outer_source_info: SourceInfo,
409         candidate: Candidate<'_, 'tcx>,
410         guard: Option<&Guard<'tcx>>,
411         fake_borrow_temps: &Vec<(Place<'tcx>, Local)>,
412         scrutinee_span: Span,
413         arm_span: Option<Span>,
414         arm_scope: Option<region::Scope>,
415         match_scope: Option<region::Scope>,
416     ) -> BasicBlock {
417         if candidate.subcandidates.is_empty() {
418             // Avoid generating another `BasicBlock` when we only have one
419             // candidate.
420             self.bind_and_guard_matched_candidate(
421                 candidate,
422                 &[],
423                 guard,
424                 fake_borrow_temps,
425                 scrutinee_span,
426                 arm_span,
427                 match_scope,
428                 true,
429             )
430         } else {
431             // It's helpful to avoid scheduling drops multiple times to save
432             // drop elaboration from having to clean up the extra drops.
433             //
434             // If we are in a `let` then we only schedule drops for the first
435             // candidate.
436             //
437             // If we're in a `match` arm then we could have a case like so:
438             //
439             // Ok(x) | Err(x) if return => { /* ... */ }
440             //
441             // In this case we don't want a drop of `x` scheduled when we
442             // return: it isn't bound by move until right before enter the arm.
443             // To handle this we instead unschedule it's drop after each time
444             // we lower the guard.
445             let target_block = self.cfg.start_new_block();
446             let mut schedule_drops = true;
447             // We keep a stack of all of the bindings and type asciptions
448             // from the parent candidates that we visit, that also need to
449             // be bound for each candidate.
450             traverse_candidate(
451                 candidate,
452                 &mut Vec::new(),
453                 &mut |leaf_candidate, parent_bindings| {
454                     if let Some(arm_scope) = arm_scope {
455                         self.clear_top_scope(arm_scope);
456                     }
457                     let binding_end = self.bind_and_guard_matched_candidate(
458                         leaf_candidate,
459                         parent_bindings,
460                         guard,
461                         &fake_borrow_temps,
462                         scrutinee_span,
463                         arm_span,
464                         match_scope,
465                         schedule_drops,
466                     );
467                     if arm_scope.is_none() {
468                         schedule_drops = false;
469                     }
470                     self.cfg.goto(binding_end, outer_source_info, target_block);
471                 },
472                 |inner_candidate, parent_bindings| {
473                     parent_bindings.push((inner_candidate.bindings, inner_candidate.ascriptions));
474                     inner_candidate.subcandidates.into_iter()
475                 },
476                 |parent_bindings| {
477                     parent_bindings.pop();
478                 },
479             );
480
481             target_block
482         }
483     }
484
485     pub(super) fn expr_into_pattern(
486         &mut self,
487         mut block: BasicBlock,
488         irrefutable_pat: Pat<'tcx>,
489         initializer: &Expr<'tcx>,
490     ) -> BlockAnd<()> {
491         match *irrefutable_pat.kind {
492             // Optimize the case of `let x = ...` to write directly into `x`
493             PatKind::Binding { mode: BindingMode::ByValue, var, subpattern: None, .. } => {
494                 let place =
495                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard, true);
496                 unpack!(block = self.expr_into_dest(place, block, initializer));
497
498                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
499                 let source_info = self.source_info(irrefutable_pat.span);
500                 self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet(None), place);
501
502                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
503                 block.unit()
504             }
505
506             // Optimize the case of `let x: T = ...` to write directly
507             // into `x` and then require that `T == typeof(x)`.
508             //
509             // Weirdly, this is needed to prevent the
510             // `intrinsic-move-val.rs` test case from crashing. That
511             // test works with uninitialized values in a rather
512             // dubious way, so it may be that the test is kind of
513             // broken.
514             PatKind::AscribeUserType {
515                 subpattern:
516                     Pat {
517                         kind:
518                             box PatKind::Binding {
519                                 mode: BindingMode::ByValue,
520                                 var,
521                                 subpattern: None,
522                                 ..
523                             },
524                         ..
525                     },
526                 ascription:
527                     thir::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
528             } => {
529                 let place =
530                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard, true);
531                 unpack!(block = self.expr_into_dest(place, block, initializer));
532
533                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
534                 let pattern_source_info = self.source_info(irrefutable_pat.span);
535                 let cause_let = FakeReadCause::ForLet(None);
536                 self.cfg.push_fake_read(block, pattern_source_info, cause_let, place);
537
538                 let ty_source_info = self.source_info(user_ty_span);
539                 let user_ty = pat_ascription_ty.user_ty(
540                     &mut self.canonical_user_type_annotations,
541                     place.ty(&self.local_decls, self.tcx).ty,
542                     ty_source_info.span,
543                 );
544                 self.cfg.push(
545                     block,
546                     Statement {
547                         source_info: ty_source_info,
548                         kind: StatementKind::AscribeUserType(
549                             Box::new((place, user_ty)),
550                             // We always use invariant as the variance here. This is because the
551                             // variance field from the ascription refers to the variance to use
552                             // when applying the type to the value being matched, but this
553                             // ascription applies rather to the type of the binding. e.g., in this
554                             // example:
555                             //
556                             // ```
557                             // let x: T = <expr>
558                             // ```
559                             //
560                             // We are creating an ascription that defines the type of `x` to be
561                             // exactly `T` (i.e., with invariance). The variance field, in
562                             // contrast, is intended to be used to relate `T` to the type of
563                             // `<expr>`.
564                             ty::Variance::Invariant,
565                         ),
566                     },
567                 );
568
569                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
570                 block.unit()
571             }
572
573             _ => {
574                 let place_builder = unpack!(block = self.as_place_builder(block, initializer));
575                 self.place_into_pattern(block, irrefutable_pat, place_builder, true)
576             }
577         }
578     }
579
580     crate fn place_into_pattern(
581         &mut self,
582         block: BasicBlock,
583         irrefutable_pat: Pat<'tcx>,
584         initializer: PlaceBuilder<'tcx>,
585         set_match_place: bool,
586     ) -> BlockAnd<()> {
587         let mut candidate = Candidate::new(initializer.clone(), &irrefutable_pat, false);
588         let fake_borrow_temps = self.lower_match_tree(
589             block,
590             irrefutable_pat.span,
591             irrefutable_pat.span,
592             false,
593             &mut [&mut candidate],
594         );
595         // For matches and function arguments, the place that is being matched
596         // can be set when creating the variables. But the place for
597         // let PATTERN = ... might not even exist until we do the assignment.
598         // so we set it here instead.
599         if set_match_place {
600             let mut candidate_ref = &candidate;
601             while let Some(next) = {
602                 for binding in &candidate_ref.bindings {
603                     let local = self.var_local_id(binding.var_id, OutsideGuard);
604
605                     let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
606                         VarBindingForm { opt_match_place: Some((ref mut match_place, _)), .. },
607                     )))) = self.local_decls[local].local_info else {
608                         bug!("Let binding to non-user variable.")
609                     };
610                     // `try_upvars_resolved` may fail if it is unable to resolve the given
611                     // `PlaceBuilder` inside a closure. In this case, we don't want to include
612                     // a scrutinee place. `scrutinee_place_builder` will fail for destructured
613                     // assignments. This is because a closure only captures the precise places
614                     // that it will read and as a result a closure may not capture the entire
615                     // tuple/struct and rather have individual places that will be read in the
616                     // final MIR.
617                     // Example:
618                     // ```
619                     // let foo = (0, 1);
620                     // let c = || {
621                     //    let (v1, v2) = foo;
622                     // };
623                     // ```
624                     if let Ok(match_pair_resolved) =
625                         initializer.clone().try_upvars_resolved(self.tcx, self.typeck_results)
626                     {
627                         let place = match_pair_resolved.into_place(self.tcx, self.typeck_results);
628                         *match_place = Some(place);
629                     }
630                 }
631                 // All of the subcandidates should bind the same locals, so we
632                 // only visit the first one.
633                 candidate_ref.subcandidates.get(0)
634             } {
635                 candidate_ref = next;
636             }
637         }
638
639         self.bind_pattern(
640             self.source_info(irrefutable_pat.span),
641             candidate,
642             None,
643             &fake_borrow_temps,
644             irrefutable_pat.span,
645             None,
646             None,
647             None,
648         )
649         .unit()
650     }
651
652     /// Declares the bindings of the given patterns and returns the visibility
653     /// scope for the bindings in these patterns, if such a scope had to be
654     /// created. NOTE: Declaring the bindings should always be done in their
655     /// drop scope.
656     crate fn declare_bindings(
657         &mut self,
658         mut visibility_scope: Option<SourceScope>,
659         scope_span: Span,
660         pattern: &Pat<'tcx>,
661         has_guard: ArmHasGuard,
662         opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
663     ) -> Option<SourceScope> {
664         debug!("declare_bindings: pattern={:?}", pattern);
665         self.visit_primary_bindings(
666             &pattern,
667             UserTypeProjections::none(),
668             &mut |this, mutability, name, mode, var, span, ty, user_ty| {
669                 if visibility_scope.is_none() {
670                     visibility_scope =
671                         Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
672                 }
673                 let source_info = SourceInfo { span, scope: this.source_scope };
674                 let visibility_scope = visibility_scope.unwrap();
675                 this.declare_binding(
676                     source_info,
677                     visibility_scope,
678                     mutability,
679                     name,
680                     mode,
681                     var,
682                     ty,
683                     user_ty,
684                     has_guard,
685                     opt_match_place.map(|(x, y)| (x.cloned(), y)),
686                     pattern.span,
687                 );
688             },
689         );
690         visibility_scope
691     }
692
693     crate fn storage_live_binding(
694         &mut self,
695         block: BasicBlock,
696         var: HirId,
697         span: Span,
698         for_guard: ForGuard,
699         schedule_drop: bool,
700     ) -> Place<'tcx> {
701         let local_id = self.var_local_id(var, for_guard);
702         let source_info = self.source_info(span);
703         self.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(local_id) });
704         let region_scope = self.region_scope_tree.var_scope(var.local_id);
705         if schedule_drop {
706             self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
707         }
708         Place::from(local_id)
709     }
710
711     crate fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
712         let local_id = self.var_local_id(var, for_guard);
713         let region_scope = self.region_scope_tree.var_scope(var.local_id);
714         self.schedule_drop(span, region_scope, local_id, DropKind::Value);
715     }
716
717     /// Visit all of the primary bindings in a patterns, that is, visit the
718     /// leftmost occurrence of each variable bound in a pattern. A variable
719     /// will occur more than once in an or-pattern.
720     pub(super) fn visit_primary_bindings(
721         &mut self,
722         pattern: &Pat<'tcx>,
723         pattern_user_ty: UserTypeProjections,
724         f: &mut impl FnMut(
725             &mut Self,
726             Mutability,
727             Symbol,
728             BindingMode,
729             HirId,
730             Span,
731             Ty<'tcx>,
732             UserTypeProjections,
733         ),
734     ) {
735         debug!(
736             "visit_primary_bindings: pattern={:?} pattern_user_ty={:?}",
737             pattern, pattern_user_ty
738         );
739         match *pattern.kind {
740             PatKind::Binding {
741                 mutability,
742                 name,
743                 mode,
744                 var,
745                 ty,
746                 ref subpattern,
747                 is_primary,
748                 ..
749             } => {
750                 if is_primary {
751                     f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
752                 }
753                 if let Some(subpattern) = subpattern.as_ref() {
754                     self.visit_primary_bindings(subpattern, pattern_user_ty, f);
755                 }
756             }
757
758             PatKind::Array { ref prefix, ref slice, ref suffix }
759             | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
760                 let from = u64::try_from(prefix.len()).unwrap();
761                 let to = u64::try_from(suffix.len()).unwrap();
762                 for subpattern in prefix {
763                     self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
764                 }
765                 for subpattern in slice {
766                     self.visit_primary_bindings(
767                         subpattern,
768                         pattern_user_ty.clone().subslice(from, to),
769                         f,
770                     );
771                 }
772                 for subpattern in suffix {
773                     self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
774                 }
775             }
776
777             PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
778
779             PatKind::Deref { ref subpattern } => {
780                 self.visit_primary_bindings(subpattern, pattern_user_ty.deref(), f);
781             }
782
783             PatKind::AscribeUserType {
784                 ref subpattern,
785                 ascription: thir::Ascription { ref user_ty, user_ty_span, variance: _ },
786             } => {
787                 // This corresponds to something like
788                 //
789                 // ```
790                 // let A::<'a>(_): A<'static> = ...;
791                 // ```
792                 //
793                 // Note that the variance doesn't apply here, as we are tracking the effect
794                 // of `user_ty` on any bindings contained with subpattern.
795                 let annotation = CanonicalUserTypeAnnotation {
796                     span: user_ty_span,
797                     user_ty: user_ty.user_ty,
798                     inferred_ty: subpattern.ty,
799                 };
800                 let projection = UserTypeProjection {
801                     base: self.canonical_user_type_annotations.push(annotation),
802                     projs: Vec::new(),
803                 };
804                 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
805                 self.visit_primary_bindings(subpattern, subpattern_user_ty, f)
806             }
807
808             PatKind::Leaf { ref subpatterns } => {
809                 for subpattern in subpatterns {
810                     let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
811                     debug!("visit_primary_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
812                     self.visit_primary_bindings(&subpattern.pattern, subpattern_user_ty, f);
813                 }
814             }
815
816             PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
817                 for subpattern in subpatterns {
818                     let subpattern_user_ty =
819                         pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field);
820                     self.visit_primary_bindings(&subpattern.pattern, subpattern_user_ty, f);
821                 }
822             }
823             PatKind::Or { ref pats } => {
824                 // In cases where we recover from errors the primary bindings
825                 // may not all be in the leftmost subpattern. For example in
826                 // `let (x | y) = ...`, the primary binding of `y` occurs in
827                 // the right subpattern
828                 for subpattern in pats {
829                     self.visit_primary_bindings(subpattern, pattern_user_ty.clone(), f);
830                 }
831             }
832         }
833     }
834 }
835
836 #[derive(Debug)]
837 struct Candidate<'pat, 'tcx> {
838     /// [`Span`] of the original pattern that gave rise to this candidate.
839     span: Span,
840
841     /// Whether this `Candidate` has a guard.
842     has_guard: bool,
843
844     /// All of these must be satisfied...
845     match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
846
847     /// ...these bindings established...
848     bindings: Vec<Binding<'tcx>>,
849
850     /// ...and these types asserted...
851     ascriptions: Vec<Ascription<'tcx>>,
852
853     /// ...and if this is non-empty, one of these subcandidates also has to match...
854     subcandidates: Vec<Candidate<'pat, 'tcx>>,
855
856     /// ...and the guard must be evaluated; if it's `false` then branch to `otherwise_block`.
857     otherwise_block: Option<BasicBlock>,
858
859     /// The block before the `bindings` have been established.
860     pre_binding_block: Option<BasicBlock>,
861     /// The pre-binding block of the next candidate.
862     next_candidate_pre_binding_block: Option<BasicBlock>,
863 }
864
865 impl<'tcx, 'pat> Candidate<'pat, 'tcx> {
866     fn new(place: PlaceBuilder<'tcx>, pattern: &'pat Pat<'tcx>, has_guard: bool) -> Self {
867         Candidate {
868             span: pattern.span,
869             has_guard,
870             match_pairs: smallvec![MatchPair { place, pattern }],
871             bindings: Vec::new(),
872             ascriptions: Vec::new(),
873             subcandidates: Vec::new(),
874             otherwise_block: None,
875             pre_binding_block: None,
876             next_candidate_pre_binding_block: None,
877         }
878     }
879
880     /// Visit the leaf candidates (those with no subcandidates) contained in
881     /// this candidate.
882     fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
883         traverse_candidate(
884             self,
885             &mut (),
886             &mut move |c, _| visit_leaf(c),
887             move |c, _| c.subcandidates.iter_mut(),
888             |_| {},
889         );
890     }
891 }
892
893 /// A depth-first traversal of the `Candidate` and all of its recursive
894 /// subcandidates.
895 fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>(
896     candidate: C,
897     context: &mut T,
898     visit_leaf: &mut impl FnMut(C, &mut T),
899     get_children: impl Copy + Fn(C, &mut T) -> I,
900     complete_children: impl Copy + Fn(&mut T),
901 ) where
902     C: Borrow<Candidate<'pat, 'tcx>>,
903     I: Iterator<Item = C>,
904 {
905     if candidate.borrow().subcandidates.is_empty() {
906         visit_leaf(candidate, context)
907     } else {
908         for child in get_children(candidate, context) {
909             traverse_candidate(child, context, visit_leaf, get_children, complete_children);
910         }
911         complete_children(context)
912     }
913 }
914
915 #[derive(Clone, Debug)]
916 struct Binding<'tcx> {
917     span: Span,
918     source: Place<'tcx>,
919     var_id: HirId,
920     binding_mode: BindingMode,
921 }
922
923 /// Indicates that the type of `source` must be a subtype of the
924 /// user-given type `user_ty`; this is basically a no-op but can
925 /// influence region inference.
926 #[derive(Clone, Debug)]
927 struct Ascription<'tcx> {
928     span: Span,
929     source: Place<'tcx>,
930     user_ty: PatTyProj<'tcx>,
931     variance: ty::Variance,
932 }
933
934 #[derive(Clone, Debug)]
935 crate struct MatchPair<'pat, 'tcx> {
936     // this place...
937     place: PlaceBuilder<'tcx>,
938
939     // ... must match this pattern.
940     pattern: &'pat Pat<'tcx>,
941 }
942
943 /// See [`Test`] for more.
944 #[derive(Clone, Debug, PartialEq)]
945 enum TestKind<'tcx> {
946     /// Test what enum variant a value is.
947     Switch {
948         /// The enum type being tested.
949         adt_def: &'tcx ty::AdtDef,
950         /// The set of variants that we should create a branch for. We also
951         /// create an additional "otherwise" case.
952         variants: BitSet<VariantIdx>,
953     },
954
955     /// Test what value an integer, `bool`, or `char` has.
956     SwitchInt {
957         /// The type of the value that we're testing.
958         switch_ty: Ty<'tcx>,
959         /// The (ordered) set of values that we test for.
960         ///
961         /// For integers and `char`s we create a branch to each of the values in
962         /// `options`, as well as an "otherwise" branch for all other values, even
963         /// in the (rare) case that `options` is exhaustive.
964         ///
965         /// For `bool` we always generate two edges, one for `true` and one for
966         /// `false`.
967         options: FxIndexMap<ty::Const<'tcx>, u128>,
968     },
969
970     /// Test for equality with value, possibly after an unsizing coercion to
971     /// `ty`,
972     Eq {
973         value: ty::Const<'tcx>,
974         // Integer types are handled by `SwitchInt`, and constants with ADT
975         // types are converted back into patterns, so this can only be `&str`,
976         // `&[T]`, `f32` or `f64`.
977         ty: Ty<'tcx>,
978     },
979
980     /// Test whether the value falls within an inclusive or exclusive range
981     Range(PatRange<'tcx>),
982
983     /// Test that the length of the slice is equal to `len`.
984     Len { len: u64, op: BinOp },
985 }
986
987 /// A test to perform to determine which [`Candidate`] matches a value.
988 ///
989 /// [`Test`] is just the test to perform; it does not include the value
990 /// to be tested.
991 #[derive(Debug)]
992 crate struct Test<'tcx> {
993     span: Span,
994     kind: TestKind<'tcx>,
995 }
996
997 /// `ArmHasGuard` is a wrapper around a boolean flag. It indicates whether
998 /// a match arm has a guard expression attached to it.
999 #[derive(Copy, Clone, Debug)]
1000 crate struct ArmHasGuard(crate bool);
1001
1002 ///////////////////////////////////////////////////////////////////////////
1003 // Main matching algorithm
1004
1005 impl<'a, 'tcx> Builder<'a, 'tcx> {
1006     /// The main match algorithm. It begins with a set of candidates
1007     /// `candidates` and has the job of generating code to determine
1008     /// which of these candidates, if any, is the correct one. The
1009     /// candidates are sorted such that the first item in the list
1010     /// has the highest priority. When a candidate is found to match
1011     /// the value, we will set and generate a branch to the appropriate
1012     /// pre-binding block.
1013     ///
1014     /// If we find that *NONE* of the candidates apply, we branch to the
1015     /// `otherwise_block`, setting it to `Some` if required. In principle, this
1016     /// means that the input list was not exhaustive, though at present we
1017     /// sometimes are not smart enough to recognize all exhaustive inputs.
1018     ///
1019     /// It might be surprising that the input can be non-exhaustive.
1020     /// Indeed, initially, it is not, because all matches are
1021     /// exhaustive in Rust. But during processing we sometimes divide
1022     /// up the list of candidates and recurse with a non-exhaustive
1023     /// list. This is important to keep the size of the generated code
1024     /// under control. See [`Builder::test_candidates`] for more details.
1025     ///
1026     /// If `fake_borrows` is `Some`, then places which need fake borrows
1027     /// will be added to it.
1028     ///
1029     /// For an example of a case where we set `otherwise_block`, even for an
1030     /// exhaustive match, consider:
1031     ///
1032     /// ```
1033     /// match x {
1034     ///     (true, true) => (),
1035     ///     (_, false) => (),
1036     ///     (false, true) => (),
1037     /// }
1038     /// ```
1039     ///
1040     /// For this match, we check if `x.0` matches `true` (for the first
1041     /// arm). If it doesn't match, we check `x.1`. If `x.1` is `true` we check
1042     /// if `x.0` matches `false` (for the third arm). In the (impossible at
1043     /// runtime) case when `x.0` is now `true`, we branch to
1044     /// `otherwise_block`.
1045     fn match_candidates<'pat>(
1046         &mut self,
1047         span: Span,
1048         scrutinee_span: Span,
1049         start_block: BasicBlock,
1050         otherwise_block: &mut Option<BasicBlock>,
1051         candidates: &mut [&mut Candidate<'pat, 'tcx>],
1052         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1053     ) {
1054         debug!(
1055             "matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
1056             span, candidates, start_block, otherwise_block,
1057         );
1058
1059         // Start by simplifying candidates. Once this process is complete, all
1060         // the match pairs which remain require some form of test, whether it
1061         // be a switch or pattern comparison.
1062         let mut split_or_candidate = false;
1063         for candidate in &mut *candidates {
1064             split_or_candidate |= self.simplify_candidate(candidate);
1065         }
1066
1067         ensure_sufficient_stack(|| {
1068             if split_or_candidate {
1069                 // At least one of the candidates has been split into subcandidates.
1070                 // We need to change the candidate list to include those.
1071                 let mut new_candidates = Vec::new();
1072
1073                 for candidate in candidates {
1074                     candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate));
1075                 }
1076                 self.match_simplified_candidates(
1077                     span,
1078                     scrutinee_span,
1079                     start_block,
1080                     otherwise_block,
1081                     &mut *new_candidates,
1082                     fake_borrows,
1083                 );
1084             } else {
1085                 self.match_simplified_candidates(
1086                     span,
1087                     scrutinee_span,
1088                     start_block,
1089                     otherwise_block,
1090                     candidates,
1091                     fake_borrows,
1092                 );
1093             }
1094         });
1095     }
1096
1097     fn match_simplified_candidates(
1098         &mut self,
1099         span: Span,
1100         scrutinee_span: Span,
1101         start_block: BasicBlock,
1102         otherwise_block: &mut Option<BasicBlock>,
1103         candidates: &mut [&mut Candidate<'_, 'tcx>],
1104         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1105     ) {
1106         // The candidates are sorted by priority. Check to see whether the
1107         // higher priority candidates (and hence at the front of the slice)
1108         // have satisfied all their match pairs.
1109         let fully_matched = candidates.iter().take_while(|c| c.match_pairs.is_empty()).count();
1110         debug!("match_candidates: {:?} candidates fully matched", fully_matched);
1111         let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
1112
1113         let block = if !matched_candidates.is_empty() {
1114             let otherwise_block =
1115                 self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
1116
1117             if let Some(last_otherwise_block) = otherwise_block {
1118                 last_otherwise_block
1119             } else {
1120                 // Any remaining candidates are unreachable.
1121                 if unmatched_candidates.is_empty() {
1122                     return;
1123                 }
1124                 self.cfg.start_new_block()
1125             }
1126         } else {
1127             start_block
1128         };
1129
1130         // If there are no candidates that still need testing, we're
1131         // done. Since all matches are exhaustive, execution should
1132         // never reach this point.
1133         if unmatched_candidates.is_empty() {
1134             let source_info = self.source_info(span);
1135             if let Some(otherwise) = *otherwise_block {
1136                 self.cfg.goto(block, source_info, otherwise);
1137             } else {
1138                 *otherwise_block = Some(block);
1139             }
1140             return;
1141         }
1142
1143         // Test for the remaining candidates.
1144         self.test_candidates_with_or(
1145             span,
1146             scrutinee_span,
1147             unmatched_candidates,
1148             block,
1149             otherwise_block,
1150             fake_borrows,
1151         );
1152     }
1153
1154     /// Link up matched candidates.
1155     ///
1156     /// For example, if we have something like this:
1157     ///
1158     /// ```rust
1159     /// ...
1160     /// Some(x) if cond1 => ...
1161     /// Some(x) => ...
1162     /// Some(x) if cond2 => ...
1163     /// ...
1164     /// ```
1165     ///
1166     /// We generate real edges from:
1167     ///
1168     /// * `start_block` to the [pre-binding block] of the first pattern,
1169     /// * the [otherwise block] of the first pattern to the second pattern,
1170     /// * the [otherwise block] of the third pattern to a block with an
1171     ///   [`Unreachable` terminator](TerminatorKind::Unreachable).
1172     ///
1173     /// In addition, we add fake edges from the otherwise blocks to the
1174     /// pre-binding block of the next candidate in the original set of
1175     /// candidates.
1176     ///
1177     /// [pre-binding block]: Candidate::pre_binding_block
1178     /// [otherwise block]: Candidate::otherwise_block
1179     fn select_matched_candidates(
1180         &mut self,
1181         matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
1182         start_block: BasicBlock,
1183         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1184     ) -> Option<BasicBlock> {
1185         debug_assert!(
1186             !matched_candidates.is_empty(),
1187             "select_matched_candidates called with no candidates",
1188         );
1189         debug_assert!(
1190             matched_candidates.iter().all(|c| c.subcandidates.is_empty()),
1191             "subcandidates should be empty in select_matched_candidates",
1192         );
1193
1194         // Insert a borrows of prefixes of places that are bound and are
1195         // behind a dereference projection.
1196         //
1197         // These borrows are taken to avoid situations like the following:
1198         //
1199         // match x[10] {
1200         //     _ if { x = &[0]; false } => (),
1201         //     y => (), // Out of bounds array access!
1202         // }
1203         //
1204         // match *x {
1205         //     // y is bound by reference in the guard and then by copy in the
1206         //     // arm, so y is 2 in the arm!
1207         //     y if { y == 1 && (x = &2) == () } => y,
1208         //     _ => 3,
1209         // }
1210         if let Some(fake_borrows) = fake_borrows {
1211             for Binding { source, .. } in
1212                 matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
1213             {
1214                 if let Some(i) =
1215                     source.projection.iter().rposition(|elem| elem == ProjectionElem::Deref)
1216                 {
1217                     let proj_base = &source.projection[..i];
1218
1219                     fake_borrows.insert(Place {
1220                         local: source.local,
1221                         projection: self.tcx.intern_place_elems(proj_base),
1222                     });
1223                 }
1224             }
1225         }
1226
1227         let fully_matched_with_guard = matched_candidates
1228             .iter()
1229             .position(|c| !c.has_guard)
1230             .unwrap_or(matched_candidates.len() - 1);
1231
1232         let (reachable_candidates, unreachable_candidates) =
1233             matched_candidates.split_at_mut(fully_matched_with_guard + 1);
1234
1235         let mut next_prebinding = start_block;
1236
1237         for candidate in reachable_candidates.iter_mut() {
1238             assert!(candidate.otherwise_block.is_none());
1239             assert!(candidate.pre_binding_block.is_none());
1240             candidate.pre_binding_block = Some(next_prebinding);
1241             if candidate.has_guard {
1242                 // Create the otherwise block for this candidate, which is the
1243                 // pre-binding block for the next candidate.
1244                 next_prebinding = self.cfg.start_new_block();
1245                 candidate.otherwise_block = Some(next_prebinding);
1246             }
1247         }
1248
1249         debug!(
1250             "match_candidates: add pre_binding_blocks for unreachable {:?}",
1251             unreachable_candidates,
1252         );
1253         for candidate in unreachable_candidates {
1254             assert!(candidate.pre_binding_block.is_none());
1255             candidate.pre_binding_block = Some(self.cfg.start_new_block());
1256         }
1257
1258         reachable_candidates.last_mut().unwrap().otherwise_block
1259     }
1260
1261     /// Tests a candidate where there are only or-patterns left to test, or
1262     /// forwards to [Builder::test_candidates].
1263     ///
1264     /// Given a pattern `(P | Q, R | S)` we (in principle) generate a CFG like
1265     /// so:
1266     ///
1267     /// ```text
1268     /// [ start ]
1269     ///      |
1270     /// [ match P, Q ]
1271     ///      |
1272     ///      +----------------------------------------+------------------------------------+
1273     ///      |                                        |                                    |
1274     ///      V                                        V                                    V
1275     /// [ P matches ]                           [ Q matches ]                        [ otherwise ]
1276     ///      |                                        |                                    |
1277     ///      V                                        V                                    |
1278     /// [ match R, S ]                          [ match R, S ]                             |
1279     ///      |                                        |                                    |
1280     ///      +--------------+------------+            +--------------+------------+        |
1281     ///      |              |            |            |              |            |        |
1282     ///      V              V            V            V              V            V        |
1283     /// [ R matches ] [ S matches ] [otherwise ] [ R matches ] [ S matches ] [otherwise ]  |
1284     ///      |              |            |            |              |            |        |
1285     ///      +--------------+------------|------------+--------------+            |        |
1286     ///      |                           |                                        |        |
1287     ///      |                           +----------------------------------------+--------+
1288     ///      |                           |
1289     ///      V                           V
1290     /// [ Success ]                 [ Failure ]
1291     /// ```
1292     ///
1293     /// In practice there are some complications:
1294     ///
1295     /// * If there's a guard, then the otherwise branch of the first match on
1296     ///   `R | S` goes to a test for whether `Q` matches, and the control flow
1297     ///   doesn't merge into a single success block until after the guard is
1298     ///   tested.
1299     /// * If neither `P` or `Q` has any bindings or type ascriptions and there
1300     ///   isn't a match guard, then we create a smaller CFG like:
1301     ///
1302     /// ```text
1303     ///     ...
1304     ///      +---------------+------------+
1305     ///      |               |            |
1306     /// [ P matches ] [ Q matches ] [ otherwise ]
1307     ///      |               |            |
1308     ///      +---------------+            |
1309     ///      |                           ...
1310     /// [ match R, S ]
1311     ///      |
1312     ///     ...
1313     /// ```
1314     fn test_candidates_with_or(
1315         &mut self,
1316         span: Span,
1317         scrutinee_span: Span,
1318         candidates: &mut [&mut Candidate<'_, 'tcx>],
1319         block: BasicBlock,
1320         otherwise_block: &mut Option<BasicBlock>,
1321         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1322     ) {
1323         let (first_candidate, remaining_candidates) = candidates.split_first_mut().unwrap();
1324
1325         // All of the or-patterns have been sorted to the end, so if the first
1326         // pattern is an or-pattern we only have or-patterns.
1327         match *first_candidate.match_pairs[0].pattern.kind {
1328             PatKind::Or { .. } => (),
1329             _ => {
1330                 self.test_candidates(
1331                     span,
1332                     scrutinee_span,
1333                     candidates,
1334                     block,
1335                     otherwise_block,
1336                     fake_borrows,
1337                 );
1338                 return;
1339             }
1340         }
1341
1342         let match_pairs = mem::take(&mut first_candidate.match_pairs);
1343         first_candidate.pre_binding_block = Some(block);
1344
1345         let mut otherwise = None;
1346         for match_pair in match_pairs {
1347             let PatKind::Or { ref pats } = &*match_pair.pattern.kind else {
1348                 bug!("Or-patterns should have been sorted to the end");
1349             };
1350             let or_span = match_pair.pattern.span;
1351             let place = match_pair.place;
1352
1353             first_candidate.visit_leaves(|leaf_candidate| {
1354                 self.test_or_pattern(
1355                     leaf_candidate,
1356                     &mut otherwise,
1357                     pats,
1358                     or_span,
1359                     place.clone(),
1360                     fake_borrows,
1361                 );
1362             });
1363         }
1364
1365         let remainder_start = otherwise.unwrap_or_else(|| self.cfg.start_new_block());
1366
1367         self.match_candidates(
1368             span,
1369             scrutinee_span,
1370             remainder_start,
1371             otherwise_block,
1372             remaining_candidates,
1373             fake_borrows,
1374         )
1375     }
1376
1377     fn test_or_pattern<'pat>(
1378         &mut self,
1379         candidate: &mut Candidate<'pat, 'tcx>,
1380         otherwise: &mut Option<BasicBlock>,
1381         pats: &'pat [Pat<'tcx>],
1382         or_span: Span,
1383         place: PlaceBuilder<'tcx>,
1384         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1385     ) {
1386         debug!("test_or_pattern:\ncandidate={:#?}\npats={:#?}", candidate, pats);
1387         let mut or_candidates: Vec<_> = pats
1388             .iter()
1389             .map(|pat| Candidate::new(place.clone(), pat, candidate.has_guard))
1390             .collect();
1391         let mut or_candidate_refs: Vec<_> = or_candidates.iter_mut().collect();
1392         let otherwise = if candidate.otherwise_block.is_some() {
1393             &mut candidate.otherwise_block
1394         } else {
1395             otherwise
1396         };
1397         self.match_candidates(
1398             or_span,
1399             or_span,
1400             candidate.pre_binding_block.unwrap(),
1401             otherwise,
1402             &mut or_candidate_refs,
1403             fake_borrows,
1404         );
1405         candidate.subcandidates = or_candidates;
1406         self.merge_trivial_subcandidates(candidate, self.source_info(or_span));
1407     }
1408
1409     /// Try to merge all of the subcandidates of the given candidate into one.
1410     /// This avoids exponentially large CFGs in cases like `(1 | 2, 3 | 4, ...)`.
1411     fn merge_trivial_subcandidates(
1412         &mut self,
1413         candidate: &mut Candidate<'_, 'tcx>,
1414         source_info: SourceInfo,
1415     ) {
1416         if candidate.subcandidates.is_empty() || candidate.has_guard {
1417             // FIXME(or_patterns; matthewjasper) Don't give up if we have a guard.
1418             return;
1419         }
1420
1421         let mut can_merge = true;
1422
1423         // Not `Iterator::all` because we don't want to short-circuit.
1424         for subcandidate in &mut candidate.subcandidates {
1425             self.merge_trivial_subcandidates(subcandidate, source_info);
1426
1427             // FIXME(or_patterns; matthewjasper) Try to be more aggressive here.
1428             can_merge &= subcandidate.subcandidates.is_empty()
1429                 && subcandidate.bindings.is_empty()
1430                 && subcandidate.ascriptions.is_empty();
1431         }
1432
1433         if can_merge {
1434             let any_matches = self.cfg.start_new_block();
1435             for subcandidate in mem::take(&mut candidate.subcandidates) {
1436                 let or_block = subcandidate.pre_binding_block.unwrap();
1437                 self.cfg.goto(or_block, source_info, any_matches);
1438             }
1439             candidate.pre_binding_block = Some(any_matches);
1440         }
1441     }
1442
1443     /// This is the most subtle part of the matching algorithm. At
1444     /// this point, the input candidates have been fully simplified,
1445     /// and so we know that all remaining match-pairs require some
1446     /// sort of test. To decide what test to perform, we take the highest
1447     /// priority candidate (the first one in the list, as of January 2021)
1448     /// and extract the first match-pair from the list. From this we decide
1449     /// what kind of test is needed using [`Builder::test`], defined in the
1450     /// [`test` module](mod@test).
1451     ///
1452     /// *Note:* taking the first match pair is somewhat arbitrary, and
1453     /// we might do better here by choosing more carefully what to
1454     /// test.
1455     ///
1456     /// For example, consider the following possible match-pairs:
1457     ///
1458     /// 1. `x @ Some(P)` -- we will do a [`Switch`] to decide what variant `x` has
1459     /// 2. `x @ 22` -- we will do a [`SwitchInt`] to decide what value `x` has
1460     /// 3. `x @ 3..5` -- we will do a [`Range`] test to decide what range `x` falls in
1461     /// 4. etc.
1462     ///
1463     /// [`Switch`]: TestKind::Switch
1464     /// [`SwitchInt`]: TestKind::SwitchInt
1465     /// [`Range`]: TestKind::Range
1466     ///
1467     /// Once we know what sort of test we are going to perform, this
1468     /// test may also help us winnow down our candidates. So we walk over
1469     /// the candidates (from high to low priority) and check. This
1470     /// gives us, for each outcome of the test, a transformed list of
1471     /// candidates. For example, if we are testing `x.0`'s variant,
1472     /// and we have a candidate `(x.0 @ Some(v), x.1 @ 22)`,
1473     /// then we would have a resulting candidate of `((x.0 as Some).0 @ v, x.1 @ 22)`.
1474     /// Note that the first match-pair is now simpler (and, in fact, irrefutable).
1475     ///
1476     /// But there may also be candidates that the test just doesn't
1477     /// apply to. The classical example involves wildcards:
1478     ///
1479     /// ```
1480     /// # let (x, y, z) = (true, true, true);
1481     /// match (x, y, z) {
1482     ///     (true, _, true) => true,    // (0)
1483     ///     (_, true, _) => true,       // (1)
1484     ///     (false, false, _) => false, // (2)
1485     ///     (true, _, false) => false,  // (3)
1486     /// }
1487     /// ```
1488     ///
1489     /// In that case, after we test on `x`, there are 2 overlapping candidate
1490     /// sets:
1491     ///
1492     /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1493     /// - If the outcome is that `x` is false, candidates 1 and 2
1494     ///
1495     /// Here, the traditional "decision tree" method would generate 2
1496     /// separate code-paths for the 2 separate cases.
1497     ///
1498     /// In some cases, this duplication can create an exponential amount of
1499     /// code. This is most easily seen by noticing that this method terminates
1500     /// with precisely the reachable arms being reachable - but that problem
1501     /// is trivially NP-complete:
1502     ///
1503     /// ```rust
1504     ///     match (var0, var1, var2, var3, ...) {
1505     ///         (true, _, _, false, true, ...) => false,
1506     ///         (_, true, true, false, _, ...) => false,
1507     ///         (false, _, false, false, _, ...) => false,
1508     ///         ...
1509     ///         _ => true
1510     ///     }
1511     /// ```
1512     ///
1513     /// Here the last arm is reachable only if there is an assignment to
1514     /// the variables that does not match any of the literals. Therefore,
1515     /// compilation would take an exponential amount of time in some cases.
1516     ///
1517     /// That kind of exponential worst-case might not occur in practice, but
1518     /// our simplistic treatment of constants and guards would make it occur
1519     /// in very common situations - for example [#29740]:
1520     ///
1521     /// ```rust
1522     /// match x {
1523     ///     "foo" if foo_guard => ...,
1524     ///     "bar" if bar_guard => ...,
1525     ///     "baz" if baz_guard => ...,
1526     ///     ...
1527     /// }
1528     /// ```
1529     ///
1530     /// [#29740]: https://github.com/rust-lang/rust/issues/29740
1531     ///
1532     /// Here we first test the match-pair `x @ "foo"`, which is an [`Eq` test].
1533     ///
1534     /// [`Eq` test]: TestKind::Eq
1535     ///
1536     /// It might seem that we would end up with 2 disjoint candidate
1537     /// sets, consisting of the first candidate or the other two, but our
1538     /// algorithm doesn't reason about `"foo"` being distinct from the other
1539     /// constants; it considers the latter arms to potentially match after
1540     /// both outcomes, which obviously leads to an exponential number
1541     /// of tests.
1542     ///
1543     /// To avoid these kinds of problems, our algorithm tries to ensure
1544     /// the amount of generated tests is linear. When we do a k-way test,
1545     /// we return an additional "unmatched" set alongside the obvious `k`
1546     /// sets. When we encounter a candidate that would be present in more
1547     /// than one of the sets, we put it and all candidates below it into the
1548     /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1549     ///
1550     /// After we perform our test, we branch into the appropriate candidate
1551     /// set and recurse with `match_candidates`. These sub-matches are
1552     /// obviously non-exhaustive - as we discarded our otherwise set - so
1553     /// we set their continuation to do `match_candidates` on the
1554     /// "unmatched" set (which is again non-exhaustive).
1555     ///
1556     /// If you apply this to the above test, you basically wind up
1557     /// with an if-else-if chain, testing each candidate in turn,
1558     /// which is precisely what we want.
1559     ///
1560     /// In addition to avoiding exponential-time blowups, this algorithm
1561     /// also has the nice property that each guard and arm is only generated
1562     /// once.
1563     fn test_candidates<'pat, 'b, 'c>(
1564         &mut self,
1565         span: Span,
1566         scrutinee_span: Span,
1567         mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1568         block: BasicBlock,
1569         otherwise_block: &mut Option<BasicBlock>,
1570         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1571     ) {
1572         // extract the match-pair from the highest priority candidate
1573         let match_pair = &candidates.first().unwrap().match_pairs[0];
1574         let mut test = self.test(match_pair);
1575         let match_place = match_pair.place.clone();
1576
1577         // most of the time, the test to perform is simply a function
1578         // of the main candidate; but for a test like SwitchInt, we
1579         // may want to add cases based on the candidates that are
1580         // available
1581         match test.kind {
1582             TestKind::SwitchInt { switch_ty, ref mut options } => {
1583                 for candidate in candidates.iter() {
1584                     if !self.add_cases_to_switch(&match_place, candidate, switch_ty, options) {
1585                         break;
1586                     }
1587                 }
1588             }
1589             TestKind::Switch { adt_def: _, ref mut variants } => {
1590                 for candidate in candidates.iter() {
1591                     if !self.add_variants_to_switch(&match_place, candidate, variants) {
1592                         break;
1593                     }
1594                 }
1595             }
1596             _ => {}
1597         }
1598
1599         // Insert a Shallow borrow of any places that is switched on.
1600         if let Some(fb) = fake_borrows && let Ok(match_place_resolved) =
1601             match_place.clone().try_upvars_resolved(self.tcx, self.typeck_results)
1602         {
1603             let resolved_place = match_place_resolved.into_place(self.tcx, self.typeck_results);
1604             fb.insert(resolved_place);
1605         }
1606
1607         // perform the test, branching to one of N blocks. For each of
1608         // those N possible outcomes, create a (initially empty)
1609         // vector of candidates. Those are the candidates that still
1610         // apply if the test has that particular outcome.
1611         debug!("match_candidates: test={:?} match_pair={:?}", test, match_pair);
1612         let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1613         target_candidates.resize_with(test.targets(), Default::default);
1614
1615         let total_candidate_count = candidates.len();
1616
1617         // Sort the candidates into the appropriate vector in
1618         // `target_candidates`. Note that at some point we may
1619         // encounter a candidate where the test is not relevant; at
1620         // that point, we stop sorting.
1621         while let Some(candidate) = candidates.first_mut() {
1622             let Some(idx) = self.sort_candidate(&match_place.clone(), &test, candidate) else {
1623                 break;
1624             };
1625             let (candidate, rest) = candidates.split_first_mut().unwrap();
1626             target_candidates[idx].push(candidate);
1627             candidates = rest;
1628         }
1629         // at least the first candidate ought to be tested
1630         assert!(total_candidate_count > candidates.len());
1631         debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1632         debug!("untested_candidates: {}", candidates.len());
1633
1634         // HACK(matthewjasper) This is a closure so that we can let the test
1635         // create its blocks before the rest of the match. This currently
1636         // improves the speed of llvm when optimizing long string literal
1637         // matches
1638         let make_target_blocks = move |this: &mut Self| -> Vec<BasicBlock> {
1639             // The block that we should branch to if none of the
1640             // `target_candidates` match. This is either the block where we
1641             // start matching the untested candidates if there are any,
1642             // otherwise it's the `otherwise_block`.
1643             let remainder_start = &mut None;
1644             let remainder_start =
1645                 if candidates.is_empty() { &mut *otherwise_block } else { remainder_start };
1646
1647             // For each outcome of test, process the candidates that still
1648             // apply. Collect a list of blocks where control flow will
1649             // branch if one of the `target_candidate` sets is not
1650             // exhaustive.
1651             let target_blocks: Vec<_> = target_candidates
1652                 .into_iter()
1653                 .map(|mut candidates| {
1654                     if !candidates.is_empty() {
1655                         let candidate_start = this.cfg.start_new_block();
1656                         this.match_candidates(
1657                             span,
1658                             scrutinee_span,
1659                             candidate_start,
1660                             remainder_start,
1661                             &mut *candidates,
1662                             fake_borrows,
1663                         );
1664                         candidate_start
1665                     } else {
1666                         *remainder_start.get_or_insert_with(|| this.cfg.start_new_block())
1667                     }
1668                 })
1669                 .collect();
1670
1671             if !candidates.is_empty() {
1672                 let remainder_start = remainder_start.unwrap_or_else(|| this.cfg.start_new_block());
1673                 this.match_candidates(
1674                     span,
1675                     scrutinee_span,
1676                     remainder_start,
1677                     otherwise_block,
1678                     candidates,
1679                     fake_borrows,
1680                 );
1681             };
1682
1683             target_blocks
1684         };
1685
1686         self.perform_test(span, scrutinee_span, block, match_place, &test, make_target_blocks);
1687     }
1688
1689     /// Determine the fake borrows that are needed from a set of places that
1690     /// have to be stable across match guards.
1691     ///
1692     /// Returns a list of places that need a fake borrow and the temporary
1693     /// that's used to store the fake borrow.
1694     ///
1695     /// Match exhaustiveness checking is not able to handle the case where the
1696     /// place being matched on is mutated in the guards. We add "fake borrows"
1697     /// to the guards that prevent any mutation of the place being matched.
1698     /// There are a some subtleties:
1699     ///
1700     /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
1701     ///    reference, the borrow isn't even tracked. As such we have to add fake
1702     ///    borrows of any prefixes of a place
1703     /// 2. We don't want `match x { _ => (), }` to conflict with mutable
1704     ///    borrows of `x`, so we only add fake borrows for places which are
1705     ///    bound or tested by the match.
1706     /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
1707     ///    so we use a special BorrowKind for them.
1708     /// 4. The fake borrows may be of places in inactive variants, so it would
1709     ///    be UB to generate code for them. They therefore have to be removed
1710     ///    by a MIR pass run after borrow checking.
1711     fn calculate_fake_borrows<'b>(
1712         &mut self,
1713         fake_borrows: &'b FxHashSet<Place<'tcx>>,
1714         temp_span: Span,
1715     ) -> Vec<(Place<'tcx>, Local)> {
1716         let tcx = self.tcx;
1717
1718         debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1719
1720         let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1721
1722         // Insert a Shallow borrow of the prefixes of any fake borrows.
1723         for place in fake_borrows {
1724             let mut cursor = place.projection.as_ref();
1725             while let [proj_base @ .., elem] = cursor {
1726                 cursor = proj_base;
1727
1728                 if let ProjectionElem::Deref = elem {
1729                     // Insert a shallow borrow after a deref. For other
1730                     // projections the borrow of prefix_cursor will
1731                     // conflict with any mutation of base.
1732                     all_fake_borrows.push(PlaceRef { local: place.local, projection: proj_base });
1733                 }
1734             }
1735
1736             all_fake_borrows.push(place.as_ref());
1737         }
1738
1739         // Deduplicate and ensure a deterministic order.
1740         all_fake_borrows.sort();
1741         all_fake_borrows.dedup();
1742
1743         debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1744
1745         all_fake_borrows
1746             .into_iter()
1747             .map(|matched_place_ref| {
1748                 let matched_place = Place {
1749                     local: matched_place_ref.local,
1750                     projection: tcx.intern_place_elems(matched_place_ref.projection),
1751                 };
1752                 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1753                 let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1754                 let fake_borrow_temp =
1755                     self.local_decls.push(LocalDecl::new(fake_borrow_ty, temp_span));
1756
1757                 (matched_place, fake_borrow_temp)
1758             })
1759             .collect()
1760     }
1761 }
1762
1763 ///////////////////////////////////////////////////////////////////////////
1764 // Pat binding - used for `let` and function parameters as well.
1765
1766 impl<'a, 'tcx> Builder<'a, 'tcx> {
1767     crate fn lower_let_expr(
1768         &mut self,
1769         mut block: BasicBlock,
1770         expr: &Expr<'tcx>,
1771         pat: &Pat<'tcx>,
1772         else_target: region::Scope,
1773         span: Span,
1774     ) -> BlockAnd<()> {
1775         let expr_span = expr.span;
1776         let expr_place_builder = unpack!(block = self.lower_scrutinee(block, expr, expr_span));
1777         let wildcard = Pat::wildcard_from_ty(pat.ty);
1778         let mut guard_candidate = Candidate::new(expr_place_builder.clone(), &pat, false);
1779         let mut otherwise_candidate = Candidate::new(expr_place_builder.clone(), &wildcard, false);
1780         let fake_borrow_temps = self.lower_match_tree(
1781             block,
1782             pat.span,
1783             pat.span,
1784             false,
1785             &mut [&mut guard_candidate, &mut otherwise_candidate],
1786         );
1787         let mut opt_expr_place: Option<(Option<&Place<'tcx>>, Span)> = None;
1788         let expr_place: Place<'tcx>;
1789         if let Ok(expr_builder) =
1790             expr_place_builder.try_upvars_resolved(self.tcx, self.typeck_results)
1791         {
1792             expr_place = expr_builder.into_place(self.tcx, self.typeck_results);
1793             opt_expr_place = Some((Some(&expr_place), expr_span));
1794         }
1795         let otherwise_post_guard_block = otherwise_candidate.pre_binding_block.unwrap();
1796         self.break_for_else(otherwise_post_guard_block, else_target, self.source_info(expr_span));
1797
1798         self.declare_bindings(None, pat.span.to(span), pat, ArmHasGuard(false), opt_expr_place);
1799         let post_guard_block = self.bind_pattern(
1800             self.source_info(pat.span),
1801             guard_candidate,
1802             None,
1803             &fake_borrow_temps,
1804             expr.span,
1805             None,
1806             None,
1807             None,
1808         );
1809
1810         post_guard_block.unit()
1811     }
1812
1813     /// Initializes each of the bindings from the candidate by
1814     /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1815     /// any, and then branches to the arm. Returns the block for the case where
1816     /// the guard succeeds.
1817     ///
1818     /// Note: we do not check earlier that if there is a guard,
1819     /// there cannot be move bindings. We avoid a use-after-move by only
1820     /// moving the binding once the guard has evaluated to true (see below).
1821     fn bind_and_guard_matched_candidate<'pat>(
1822         &mut self,
1823         candidate: Candidate<'pat, 'tcx>,
1824         parent_bindings: &[(Vec<Binding<'tcx>>, Vec<Ascription<'tcx>>)],
1825         guard: Option<&Guard<'tcx>>,
1826         fake_borrows: &Vec<(Place<'tcx>, Local)>,
1827         scrutinee_span: Span,
1828         arm_span: Option<Span>,
1829         match_scope: Option<region::Scope>,
1830         schedule_drops: bool,
1831     ) -> BasicBlock {
1832         debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1833
1834         debug_assert!(candidate.match_pairs.is_empty());
1835
1836         let candidate_source_info = self.source_info(candidate.span);
1837
1838         let mut block = candidate.pre_binding_block.unwrap();
1839
1840         if candidate.next_candidate_pre_binding_block.is_some() {
1841             let fresh_block = self.cfg.start_new_block();
1842             self.false_edges(
1843                 block,
1844                 fresh_block,
1845                 candidate.next_candidate_pre_binding_block,
1846                 candidate_source_info,
1847             );
1848             block = fresh_block;
1849         }
1850
1851         self.ascribe_types(
1852             block,
1853             parent_bindings
1854                 .iter()
1855                 .flat_map(|(_, ascriptions)| ascriptions)
1856                 .chain(&candidate.ascriptions),
1857         );
1858
1859         // rust-lang/rust#27282: The `autoref` business deserves some
1860         // explanation here.
1861         //
1862         // The intent of the `autoref` flag is that when it is true,
1863         // then any pattern bindings of type T will map to a `&T`
1864         // within the context of the guard expression, but will
1865         // continue to map to a `T` in the context of the arm body. To
1866         // avoid surfacing this distinction in the user source code
1867         // (which would be a severe change to the language and require
1868         // far more revision to the compiler), when `autoref` is true,
1869         // then any occurrence of the identifier in the guard
1870         // expression will automatically get a deref op applied to it.
1871         //
1872         // So an input like:
1873         //
1874         // ```
1875         // let place = Foo::new();
1876         // match place { foo if inspect(foo)
1877         //     => feed(foo), ...  }
1878         // ```
1879         //
1880         // will be treated as if it were really something like:
1881         //
1882         // ```
1883         // let place = Foo::new();
1884         // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1885         //     => { let tmp2 = place; feed(tmp2) }, ... }
1886         //
1887         // And an input like:
1888         //
1889         // ```
1890         // let place = Foo::new();
1891         // match place { ref mut foo if inspect(foo)
1892         //     => feed(foo), ...  }
1893         // ```
1894         //
1895         // will be treated as if it were really something like:
1896         //
1897         // ```
1898         // let place = Foo::new();
1899         // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1900         //     => { let tmp2 = &mut place; feed(tmp2) }, ... }
1901         // ```
1902         //
1903         // In short, any pattern binding will always look like *some*
1904         // kind of `&T` within the guard at least in terms of how the
1905         // MIR-borrowck views it, and this will ensure that guard
1906         // expressions cannot mutate their the match inputs via such
1907         // bindings. (It also ensures that guard expressions can at
1908         // most *copy* values from such bindings; non-Copy things
1909         // cannot be moved via pattern bindings in guard expressions.)
1910         //
1911         // ----
1912         //
1913         // Implementation notes (under assumption `autoref` is true).
1914         //
1915         // To encode the distinction above, we must inject the
1916         // temporaries `tmp1` and `tmp2`.
1917         //
1918         // There are two cases of interest: binding by-value, and binding by-ref.
1919         //
1920         // 1. Binding by-value: Things are simple.
1921         //
1922         //    * Establishing `tmp1` creates a reference into the
1923         //      matched place. This code is emitted by
1924         //      bind_matched_candidate_for_guard.
1925         //
1926         //    * `tmp2` is only initialized "lazily", after we have
1927         //      checked the guard. Thus, the code that can trigger
1928         //      moves out of the candidate can only fire after the
1929         //      guard evaluated to true. This initialization code is
1930         //      emitted by bind_matched_candidate_for_arm.
1931         //
1932         // 2. Binding by-reference: Things are tricky.
1933         //
1934         //    * Here, the guard expression wants a `&&` or `&&mut`
1935         //      into the original input. This means we need to borrow
1936         //      the reference that we create for the arm.
1937         //    * So we eagerly create the reference for the arm and then take a
1938         //      reference to that.
1939         if let Some(guard) = guard {
1940             let tcx = self.tcx;
1941             let bindings = parent_bindings
1942                 .iter()
1943                 .flat_map(|(bindings, _)| bindings)
1944                 .chain(&candidate.bindings);
1945
1946             self.bind_matched_candidate_for_guard(block, schedule_drops, bindings.clone());
1947             let guard_frame = GuardFrame {
1948                 locals: bindings.map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode)).collect(),
1949             };
1950             debug!("entering guard building context: {:?}", guard_frame);
1951             self.guard_context.push(guard_frame);
1952
1953             let re_erased = tcx.lifetimes.re_erased;
1954             let scrutinee_source_info = self.source_info(scrutinee_span);
1955             for &(place, temp) in fake_borrows {
1956                 let borrow = Rvalue::Ref(re_erased, BorrowKind::Shallow, place);
1957                 self.cfg.push_assign(block, scrutinee_source_info, Place::from(temp), borrow);
1958             }
1959
1960             let arm_span = arm_span.unwrap();
1961             let match_scope = match_scope.unwrap();
1962             let mut guard_span = rustc_span::DUMMY_SP;
1963
1964             let (post_guard_block, otherwise_post_guard_block) =
1965                 self.in_if_then_scope(match_scope, |this| match *guard {
1966                     Guard::If(e) => {
1967                         let e = &this.thir[e];
1968                         guard_span = e.span;
1969                         this.then_else_break(block, e, None, match_scope, arm_span)
1970                     }
1971                     Guard::IfLet(ref pat, scrutinee) => {
1972                         let s = &this.thir[scrutinee];
1973                         guard_span = s.span;
1974                         this.lower_let_expr(block, s, pat, match_scope, arm_span)
1975                     }
1976                 });
1977
1978             let source_info = self.source_info(guard_span);
1979             let guard_end = self.source_info(tcx.sess.source_map().end_point(guard_span));
1980             let guard_frame = self.guard_context.pop().unwrap();
1981             debug!("Exiting guard building context with locals: {:?}", guard_frame);
1982
1983             for &(_, temp) in fake_borrows {
1984                 let cause = FakeReadCause::ForMatchGuard;
1985                 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
1986             }
1987
1988             let otherwise_block = candidate.otherwise_block.unwrap_or_else(|| {
1989                 let unreachable = self.cfg.start_new_block();
1990                 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
1991                 unreachable
1992             });
1993             self.false_edges(
1994                 otherwise_post_guard_block,
1995                 otherwise_block,
1996                 candidate.next_candidate_pre_binding_block,
1997                 source_info,
1998             );
1999
2000             // We want to ensure that the matched candidates are bound
2001             // after we have confirmed this candidate *and* any
2002             // associated guard; Binding them on `block` is too soon,
2003             // because that would be before we've checked the result
2004             // from the guard.
2005             //
2006             // But binding them on the arm is *too late*, because
2007             // then all of the candidates for a single arm would be
2008             // bound in the same place, that would cause a case like:
2009             //
2010             // ```rust
2011             // match (30, 2) {
2012             //     (mut x, 1) | (2, mut x) if { true } => { ... }
2013             //     ...                                 // ^^^^^^^ (this is `arm_block`)
2014             // }
2015             // ```
2016             //
2017             // would yield an `arm_block` something like:
2018             //
2019             // ```
2020             // StorageLive(_4);        // _4 is `x`
2021             // _4 = &mut (_1.0: i32);  // this is handling `(mut x, 1)` case
2022             // _4 = &mut (_1.1: i32);  // this is handling `(2, mut x)` case
2023             // ```
2024             //
2025             // and that is clearly not correct.
2026             let by_value_bindings = parent_bindings
2027                 .iter()
2028                 .flat_map(|(bindings, _)| bindings)
2029                 .chain(&candidate.bindings)
2030                 .filter(|binding| matches!(binding.binding_mode, BindingMode::ByValue));
2031             // Read all of the by reference bindings to ensure that the
2032             // place they refer to can't be modified by the guard.
2033             for binding in by_value_bindings.clone() {
2034                 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
2035                 let cause = FakeReadCause::ForGuardBinding;
2036                 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
2037             }
2038             assert!(schedule_drops, "patterns with guards must schedule drops");
2039             self.bind_matched_candidate_for_arm_body(post_guard_block, true, by_value_bindings);
2040
2041             post_guard_block
2042         } else {
2043             // (Here, it is not too early to bind the matched
2044             // candidate on `block`, because there is no guard result
2045             // that we have to inspect before we bind them.)
2046             self.bind_matched_candidate_for_arm_body(
2047                 block,
2048                 schedule_drops,
2049                 parent_bindings
2050                     .iter()
2051                     .flat_map(|(bindings, _)| bindings)
2052                     .chain(&candidate.bindings),
2053             );
2054             block
2055         }
2056     }
2057
2058     /// Append `AscribeUserType` statements onto the end of `block`
2059     /// for each ascription
2060     fn ascribe_types<'b>(
2061         &mut self,
2062         block: BasicBlock,
2063         ascriptions: impl IntoIterator<Item = &'b Ascription<'tcx>>,
2064     ) where
2065         'tcx: 'b,
2066     {
2067         for ascription in ascriptions {
2068             let source_info = self.source_info(ascription.span);
2069
2070             debug!(
2071                 "adding user ascription at span {:?} of place {:?} and {:?}",
2072                 source_info.span, ascription.source, ascription.user_ty,
2073             );
2074
2075             let user_ty = ascription.user_ty.user_ty(
2076                 &mut self.canonical_user_type_annotations,
2077                 ascription.source.ty(&self.local_decls, self.tcx).ty,
2078                 source_info.span,
2079             );
2080             self.cfg.push(
2081                 block,
2082                 Statement {
2083                     source_info,
2084                     kind: StatementKind::AscribeUserType(
2085                         Box::new((ascription.source, user_ty)),
2086                         ascription.variance,
2087                     ),
2088                 },
2089             );
2090         }
2091     }
2092
2093     fn bind_matched_candidate_for_guard<'b>(
2094         &mut self,
2095         block: BasicBlock,
2096         schedule_drops: bool,
2097         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
2098     ) where
2099         'tcx: 'b,
2100     {
2101         debug!("bind_matched_candidate_for_guard(block={:?})", block);
2102
2103         // Assign each of the bindings. Since we are binding for a
2104         // guard expression, this will never trigger moves out of the
2105         // candidate.
2106         let re_erased = self.tcx.lifetimes.re_erased;
2107         for binding in bindings {
2108             debug!("bind_matched_candidate_for_guard(binding={:?})", binding);
2109             let source_info = self.source_info(binding.span);
2110
2111             // For each pattern ident P of type T, `ref_for_guard` is
2112             // a reference R: &T pointing to the location matched by
2113             // the pattern, and every occurrence of P within a guard
2114             // denotes *R.
2115             let ref_for_guard = self.storage_live_binding(
2116                 block,
2117                 binding.var_id,
2118                 binding.span,
2119                 RefWithinGuard,
2120                 schedule_drops,
2121             );
2122             match binding.binding_mode {
2123                 BindingMode::ByValue => {
2124                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source);
2125                     self.cfg.push_assign(block, source_info, ref_for_guard, rvalue);
2126                 }
2127                 BindingMode::ByRef(borrow_kind) => {
2128                     let value_for_arm = self.storage_live_binding(
2129                         block,
2130                         binding.var_id,
2131                         binding.span,
2132                         OutsideGuard,
2133                         schedule_drops,
2134                     );
2135
2136                     let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source);
2137                     self.cfg.push_assign(block, source_info, value_for_arm, rvalue);
2138                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
2139                     self.cfg.push_assign(block, source_info, ref_for_guard, rvalue);
2140                 }
2141             }
2142         }
2143     }
2144
2145     fn bind_matched_candidate_for_arm_body<'b>(
2146         &mut self,
2147         block: BasicBlock,
2148         schedule_drops: bool,
2149         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
2150     ) where
2151         'tcx: 'b,
2152     {
2153         debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
2154
2155         let re_erased = self.tcx.lifetimes.re_erased;
2156         // Assign each of the bindings. This may trigger moves out of the candidate.
2157         for binding in bindings {
2158             let source_info = self.source_info(binding.span);
2159             let local = self.storage_live_binding(
2160                 block,
2161                 binding.var_id,
2162                 binding.span,
2163                 OutsideGuard,
2164                 schedule_drops,
2165             );
2166             if schedule_drops {
2167                 self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
2168             }
2169             let rvalue = match binding.binding_mode {
2170                 BindingMode::ByValue => Rvalue::Use(self.consume_by_copy_or_move(binding.source)),
2171                 BindingMode::ByRef(borrow_kind) => {
2172                     Rvalue::Ref(re_erased, borrow_kind, binding.source)
2173                 }
2174             };
2175             self.cfg.push_assign(block, source_info, local, rvalue);
2176         }
2177     }
2178
2179     /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
2180     /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
2181     /// first local is a binding for occurrences of `var` in the guard, which
2182     /// will have type `&T`. The second local is a binding for occurrences of
2183     /// `var` in the arm body, which will have type `T`.
2184     fn declare_binding(
2185         &mut self,
2186         source_info: SourceInfo,
2187         visibility_scope: SourceScope,
2188         mutability: Mutability,
2189         name: Symbol,
2190         mode: BindingMode,
2191         var_id: HirId,
2192         var_ty: Ty<'tcx>,
2193         user_ty: UserTypeProjections,
2194         has_guard: ArmHasGuard,
2195         opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
2196         pat_span: Span,
2197     ) {
2198         debug!(
2199             "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
2200              visibility_scope={:?}, source_info={:?})",
2201             var_id, name, mode, var_ty, visibility_scope, source_info
2202         );
2203
2204         let tcx = self.tcx;
2205         let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
2206         let binding_mode = match mode {
2207             BindingMode::ByValue => ty::BindingMode::BindByValue(mutability),
2208             BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability),
2209         };
2210         debug!("declare_binding: user_ty={:?}", user_ty);
2211         let local = LocalDecl::<'tcx> {
2212             mutability,
2213             ty: var_ty,
2214             user_ty: if user_ty.is_empty() { None } else { Some(Box::new(user_ty)) },
2215             source_info,
2216             internal: false,
2217             is_block_tail: None,
2218             local_info: Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
2219                 VarBindingForm {
2220                     binding_mode,
2221                     // hypothetically, `visit_primary_bindings` could try to unzip
2222                     // an outermost hir::Ty as we descend, matching up
2223                     // idents in pat; but complex w/ unclear UI payoff.
2224                     // Instead, just abandon providing diagnostic info.
2225                     opt_ty_info: None,
2226                     opt_match_place,
2227                     pat_span,
2228                 },
2229             ))))),
2230         };
2231         let for_arm_body = self.local_decls.push(local);
2232         self.var_debug_info.push(VarDebugInfo {
2233             name,
2234             source_info: debug_source_info,
2235             value: VarDebugInfoContents::Place(for_arm_body.into()),
2236         });
2237         let locals = if has_guard.0 {
2238             let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
2239                 // This variable isn't mutated but has a name, so has to be
2240                 // immutable to avoid the unused mut lint.
2241                 mutability: Mutability::Not,
2242                 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
2243                 user_ty: None,
2244                 source_info,
2245                 internal: false,
2246                 is_block_tail: None,
2247                 local_info: Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(
2248                     BindingForm::RefForGuard,
2249                 )))),
2250             });
2251             self.var_debug_info.push(VarDebugInfo {
2252                 name,
2253                 source_info: debug_source_info,
2254                 value: VarDebugInfoContents::Place(ref_for_guard.into()),
2255             });
2256             LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
2257         } else {
2258             LocalsForNode::One(for_arm_body)
2259         };
2260         debug!("declare_binding: vars={:?}", locals);
2261         self.var_indices.insert(var_id, locals);
2262     }
2263 }