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