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