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