rustc_mir_build/builder/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
8use std::borrow::Borrow;
9use std::mem;
10use std::sync::Arc;
11
12use itertools::{Itertools, Position};
13use rustc_abi::VariantIdx;
14use rustc_data_structures::fx::FxIndexMap;
15use rustc_data_structures::stack::ensure_sufficient_stack;
16use rustc_hir::{BindingMode, ByRef, LetStmt, LocalSource, Node};
17use rustc_middle::bug;
18use rustc_middle::middle::region;
19use rustc_middle::mir::*;
20use rustc_middle::thir::{self, *};
21use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, ValTree, ValTreeKind};
22use rustc_pattern_analysis::constructor::RangeEnd;
23use rustc_pattern_analysis::rustc::{DeconstructedPat, RustcPatCtxt};
24use rustc_span::{BytePos, Pos, Span, Symbol, sym};
25use tracing::{debug, instrument};
26
27use crate::builder::ForGuard::{self, OutsideGuard, RefWithinGuard};
28use crate::builder::expr::as_place::PlaceBuilder;
29use crate::builder::matches::user_ty::ProjectedUserTypesNode;
30use crate::builder::scope::DropKind;
31use crate::builder::{
32    BlockAnd, BlockAndExtension, Builder, GuardFrame, GuardFrameLocal, LocalsForNode,
33};
34
35// helper functions, broken out by category:
36mod match_pair;
37mod test;
38mod user_ty;
39mod util;
40
41/// Arguments to [`Builder::then_else_break_inner`] that are usually forwarded
42/// to recursive invocations.
43#[derive(Clone, Copy)]
44struct ThenElseArgs {
45    /// Used as the temp scope for lowering `expr`. If absent (for match guards),
46    /// `self.local_scope()` is used.
47    temp_scope_override: Option<region::Scope>,
48    variable_source_info: SourceInfo,
49    /// Determines how bindings should be handled when lowering `let` expressions.
50    ///
51    /// Forwarded to [`Builder::lower_let_expr`] when lowering [`ExprKind::Let`].
52    declare_let_bindings: DeclareLetBindings,
53}
54
55/// Should lowering a `let` expression also declare its bindings?
56///
57/// Used by [`Builder::lower_let_expr`] when lowering [`ExprKind::Let`].
58#[derive(Clone, Copy)]
59pub(crate) enum DeclareLetBindings {
60    /// Yes, declare `let` bindings as normal for `if` conditions.
61    Yes,
62    /// No, don't declare `let` bindings, because the caller declares them
63    /// separately due to special requirements.
64    ///
65    /// Used for match guards and let-else.
66    No,
67    /// Let expressions are not permitted in this context, so it is a bug to
68    /// try to lower one (e.g inside lazy-boolean-or or boolean-not).
69    LetNotPermitted,
70}
71
72/// Used by [`Builder::storage_live_binding`] and [`Builder::bind_matched_candidate_for_arm_body`]
73/// to decide whether to schedule drops.
74#[derive(Clone, Copy, Debug)]
75pub(crate) enum ScheduleDrops {
76    /// Yes, the relevant functions should also schedule drops as appropriate.
77    Yes,
78    /// No, don't schedule drops. The caller has taken responsibility for any
79    /// appropriate drops.
80    No,
81}
82
83impl<'a, 'tcx> Builder<'a, 'tcx> {
84    /// Lowers a condition in a way that ensures that variables bound in any let
85    /// expressions are definitely initialized in the if body.
86    ///
87    /// If `declare_let_bindings` is false then variables created in `let`
88    /// expressions will not be declared. This is for if let guards on arms with
89    /// an or pattern, where the guard is lowered multiple times.
90    pub(crate) fn then_else_break(
91        &mut self,
92        block: BasicBlock,
93        expr_id: ExprId,
94        temp_scope_override: Option<region::Scope>,
95        variable_source_info: SourceInfo,
96        declare_let_bindings: DeclareLetBindings,
97    ) -> BlockAnd<()> {
98        self.then_else_break_inner(
99            block,
100            expr_id,
101            ThenElseArgs { temp_scope_override, variable_source_info, declare_let_bindings },
102        )
103    }
104
105    fn then_else_break_inner(
106        &mut self,
107        block: BasicBlock, // Block that the condition and branch will be lowered into
108        expr_id: ExprId,   // Condition expression to lower
109        args: ThenElseArgs,
110    ) -> BlockAnd<()> {
111        let this = self;
112        let expr = &this.thir[expr_id];
113        let expr_span = expr.span;
114
115        match expr.kind {
116            ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
117                let lhs_then_block = this.then_else_break_inner(block, lhs, args).into_block();
118                let rhs_then_block =
119                    this.then_else_break_inner(lhs_then_block, rhs, args).into_block();
120                rhs_then_block.unit()
121            }
122            ExprKind::LogicalOp { op: LogicalOp::Or, lhs, rhs } => {
123                let local_scope = this.local_scope();
124                let (lhs_success_block, failure_block) =
125                    this.in_if_then_scope(local_scope, expr_span, |this| {
126                        this.then_else_break_inner(
127                            block,
128                            lhs,
129                            ThenElseArgs {
130                                declare_let_bindings: DeclareLetBindings::LetNotPermitted,
131                                ..args
132                            },
133                        )
134                    });
135                let rhs_success_block = this
136                    .then_else_break_inner(
137                        failure_block,
138                        rhs,
139                        ThenElseArgs {
140                            declare_let_bindings: DeclareLetBindings::LetNotPermitted,
141                            ..args
142                        },
143                    )
144                    .into_block();
145
146                // Make the LHS and RHS success arms converge to a common block.
147                // (We can't just make LHS goto RHS, because `rhs_success_block`
148                // might contain statements that we don't want on the LHS path.)
149                let success_block = this.cfg.start_new_block();
150                this.cfg.goto(lhs_success_block, args.variable_source_info, success_block);
151                this.cfg.goto(rhs_success_block, args.variable_source_info, success_block);
152                success_block.unit()
153            }
154            ExprKind::Unary { op: UnOp::Not, arg } => {
155                // Improve branch coverage instrumentation by noting conditions
156                // nested within one or more `!` expressions.
157                // (Skipped if branch coverage is not enabled.)
158                if let Some(coverage_info) = this.coverage_info.as_mut() {
159                    coverage_info.visit_unary_not(this.thir, expr_id);
160                }
161
162                let local_scope = this.local_scope();
163                let (success_block, failure_block) =
164                    this.in_if_then_scope(local_scope, expr_span, |this| {
165                        // Help out coverage instrumentation by injecting a dummy statement with
166                        // the original condition's span (including `!`). This fixes #115468.
167                        if this.tcx.sess.instrument_coverage() {
168                            this.cfg.push_coverage_span_marker(block, this.source_info(expr_span));
169                        }
170                        this.then_else_break_inner(
171                            block,
172                            arg,
173                            ThenElseArgs {
174                                declare_let_bindings: DeclareLetBindings::LetNotPermitted,
175                                ..args
176                            },
177                        )
178                    });
179                this.break_for_else(success_block, args.variable_source_info);
180                failure_block.unit()
181            }
182            ExprKind::Scope { region_scope, lint_level, value } => {
183                let region_scope = (region_scope, this.source_info(expr_span));
184                this.in_scope(region_scope, lint_level, |this| {
185                    this.then_else_break_inner(block, value, args)
186                })
187            }
188            ExprKind::Use { source } => this.then_else_break_inner(block, source, args),
189            ExprKind::Let { expr, ref pat } => this.lower_let_expr(
190                block,
191                expr,
192                pat,
193                Some(args.variable_source_info.scope),
194                args.variable_source_info.span,
195                args.declare_let_bindings,
196            ),
197            _ => {
198                let mut block = block;
199                let temp_scope = args.temp_scope_override.unwrap_or_else(|| this.local_scope());
200                let mutability = Mutability::Mut;
201
202                let place = unpack!(
203                    block = this.as_temp(
204                        block,
205                        TempLifetime {
206                            temp_lifetime: Some(temp_scope),
207                            backwards_incompatible: None
208                        },
209                        expr_id,
210                        mutability
211                    )
212                );
213
214                let operand = Operand::Move(Place::from(place));
215
216                let then_block = this.cfg.start_new_block();
217                let else_block = this.cfg.start_new_block();
218                let term = TerminatorKind::if_(operand, then_block, else_block);
219
220                // Record branch coverage info for this condition.
221                // (Does nothing if branch coverage is not enabled.)
222                this.visit_coverage_branch_condition(expr_id, then_block, else_block);
223
224                let source_info = this.source_info(expr_span);
225                this.cfg.terminate(block, source_info, term);
226                this.break_for_else(else_block, source_info);
227
228                then_block.unit()
229            }
230        }
231    }
232
233    /// Generates MIR for a `match` expression.
234    ///
235    /// The MIR that we generate for a match looks like this.
236    ///
237    /// ```text
238    /// [ 0. Pre-match ]
239    ///        |
240    /// [ 1. Evaluate Scrutinee (expression being matched on) ]
241    /// [ (PlaceMention of scrutinee) ]
242    ///        |
243    /// [ 2. Decision tree -- check discriminants ] <--------+
244    ///        |                                             |
245    ///        | (once a specific arm is chosen)             |
246    ///        |                                             |
247    /// [pre_binding_block]                           [otherwise_block]
248    ///        |                                             |
249    /// [ 3. Create "guard bindings" for arm ]               |
250    /// [ (create fake borrows) ]                            |
251    ///        |                                             |
252    /// [ 4. Execute guard code ]                            |
253    /// [ (read fake borrows) ] --(guard is false)-----------+
254    ///        |
255    ///        | (guard results in true)
256    ///        |
257    /// [ 5. Create real bindings and execute arm ]
258    ///        |
259    /// [ Exit match ]
260    /// ```
261    ///
262    /// All of the different arms have been stacked on top of each other to
263    /// simplify the diagram. For an arm with no guard the blocks marked 3 and
264    /// 4 and the fake borrows are omitted.
265    ///
266    /// We generate MIR in the following steps:
267    ///
268    /// 1. Evaluate the scrutinee and add the PlaceMention of it ([Builder::lower_scrutinee]).
269    /// 2. Create the decision tree ([Builder::lower_match_tree]).
270    /// 3. Determine the fake borrows that are needed from the places that were
271    ///    matched against and create the required temporaries for them
272    ///    ([util::collect_fake_borrows]).
273    /// 4. Create everything else: the guards and the arms ([Builder::lower_match_arms]).
274    ///
275    /// ## False edges
276    ///
277    /// We don't want to have the exact structure of the decision tree be visible through borrow
278    /// checking. Specifically we want borrowck to think that:
279    /// - at any point, any or none of the patterns and guards seen so far may have been tested;
280    /// - after the match, any of the patterns may have matched.
281    ///
282    /// For example, all of these would fail to error if borrowck could see the real CFG (examples
283    /// taken from `tests/ui/nll/match-cfg-fake-edges.rs`):
284    /// ```ignore (too many errors, this is already in the test suite)
285    /// let x = String::new();
286    /// let _ = match true {
287    ///     _ => {},
288    ///     _ => drop(x),
289    /// };
290    /// // Borrowck must not know the second arm is never run.
291    /// drop(x); //~ ERROR use of moved value
292    ///
293    /// let x;
294    /// # let y = true;
295    /// match y {
296    ///     _ if { x = 2; true } => {},
297    ///     // Borrowck must not know the guard is always run.
298    ///     _ => drop(x), //~ ERROR used binding `x` is possibly-uninitialized
299    /// };
300    ///
301    /// let x = String::new();
302    /// # let y = true;
303    /// match y {
304    ///     false if { drop(x); true } => {},
305    ///     // Borrowck must not know the guard is not run in the `true` case.
306    ///     true => drop(x), //~ ERROR use of moved value: `x`
307    ///     false => {},
308    /// };
309    ///
310    /// # let mut y = (true, true);
311    /// let r = &mut y.1;
312    /// match y {
313    ///     //~^ ERROR cannot use `y.1` because it was mutably borrowed
314    ///     (false, true) => {}
315    ///     // Borrowck must not know we don't test `y.1` when `y.0` is `true`.
316    ///     (true, _) => drop(r),
317    ///     (false, _) => {}
318    /// };
319    /// ```
320    ///
321    /// We add false edges to act as if we were naively matching each arm in order. What we need is
322    /// a (fake) path from each candidate to the next, specifically from candidate C's pre-binding
323    /// block to next candidate D's pre-binding block. For maximum precision (needed for deref
324    /// patterns), we choose the earliest node on D's success path that doesn't also lead to C (to
325    /// avoid loops).
326    ///
327    /// This turns out to be easy to compute: that block is the `start_block` of the first call to
328    /// `match_candidates` where D is the first candidate in the list.
329    ///
330    /// For example:
331    /// ```rust
332    /// # let (x, y) = (true, true);
333    /// match (x, y) {
334    ///   (true, true) => 1,
335    ///   (false, true) => 2,
336    ///   (true, false) => 3,
337    ///   _ => 4,
338    /// }
339    /// # ;
340    /// ```
341    /// In this example, the pre-binding block of arm 1 has a false edge to the block for result
342    /// `false` of the first test on `x`. The other arms have false edges to the pre-binding blocks
343    /// of the next arm.
344    ///
345    /// On top of this, we also add a false edge from the otherwise_block of each guard to the
346    /// aforementioned start block of the next candidate, to ensure borrock doesn't rely on which
347    /// guards may have run.
348    #[instrument(level = "debug", skip(self, arms))]
349    pub(crate) fn match_expr(
350        &mut self,
351        destination: Place<'tcx>,
352        mut block: BasicBlock,
353        scrutinee_id: ExprId,
354        arms: &[ArmId],
355        span: Span,
356        scrutinee_span: Span,
357    ) -> BlockAnd<()> {
358        let scrutinee_place =
359            unpack!(block = self.lower_scrutinee(block, scrutinee_id, scrutinee_span));
360
361        let match_start_span = span.shrink_to_lo().to(scrutinee_span);
362        let patterns = arms
363            .iter()
364            .map(|&arm| {
365                let arm = &self.thir[arm];
366                let has_match_guard =
367                    if arm.guard.is_some() { HasMatchGuard::Yes } else { HasMatchGuard::No };
368                (&*arm.pattern, has_match_guard)
369            })
370            .collect();
371        let built_tree = self.lower_match_tree(
372            block,
373            scrutinee_span,
374            &scrutinee_place,
375            match_start_span,
376            patterns,
377            false,
378        );
379
380        self.lower_match_arms(
381            destination,
382            scrutinee_place,
383            scrutinee_span,
384            arms,
385            built_tree,
386            self.source_info(span),
387        )
388    }
389
390    /// Evaluate the scrutinee and add the PlaceMention for it.
391    pub(crate) fn lower_scrutinee(
392        &mut self,
393        mut block: BasicBlock,
394        scrutinee_id: ExprId,
395        scrutinee_span: Span,
396    ) -> BlockAnd<PlaceBuilder<'tcx>> {
397        let scrutinee_place_builder = unpack!(block = self.as_place_builder(block, scrutinee_id));
398        if let Some(scrutinee_place) = scrutinee_place_builder.try_to_place(self) {
399            let source_info = self.source_info(scrutinee_span);
400            self.cfg.push_place_mention(block, source_info, scrutinee_place);
401        }
402
403        block.and(scrutinee_place_builder)
404    }
405
406    /// Lower the bindings, guards and arm bodies of a `match` expression.
407    ///
408    /// The decision tree should have already been created
409    /// (by [Builder::lower_match_tree]).
410    ///
411    /// `outer_source_info` is the SourceInfo for the whole match.
412    pub(crate) fn lower_match_arms(
413        &mut self,
414        destination: Place<'tcx>,
415        scrutinee_place_builder: PlaceBuilder<'tcx>,
416        scrutinee_span: Span,
417        arms: &[ArmId],
418        built_match_tree: BuiltMatchTree<'tcx>,
419        outer_source_info: SourceInfo,
420    ) -> BlockAnd<()> {
421        let arm_end_blocks: Vec<BasicBlock> = arms
422            .iter()
423            .map(|&arm| &self.thir[arm])
424            .zip(built_match_tree.branches)
425            .map(|(arm, branch)| {
426                debug!("lowering arm {:?}\ncorresponding branch = {:?}", arm, branch);
427
428                let arm_source_info = self.source_info(arm.span);
429                let arm_scope = (arm.scope, arm_source_info);
430                let match_scope = self.local_scope();
431                let guard_scope = arm
432                    .guard
433                    .map(|_| region::Scope { data: region::ScopeData::MatchGuard, ..arm.scope });
434                self.in_scope(arm_scope, arm.lint_level, |this| {
435                    this.opt_in_scope(guard_scope.map(|scope| (scope, arm_source_info)), |this| {
436                        // `if let` guard temps needing deduplicating will be in the guard scope.
437                        let old_dedup_scope =
438                            mem::replace(&mut this.fixed_temps_scope, guard_scope);
439
440                        // `try_to_place` may fail if it is unable to resolve the given
441                        // `PlaceBuilder` inside a closure. In this case, we don't want to include
442                        // a scrutinee place. `scrutinee_place_builder` will fail to be resolved
443                        // if the only match arm is a wildcard (`_`).
444                        // Example:
445                        // ```
446                        // let foo = (0, 1);
447                        // let c = || {
448                        //    match foo { _ => () };
449                        // };
450                        // ```
451                        let scrutinee_place = scrutinee_place_builder.try_to_place(this);
452                        let opt_scrutinee_place =
453                            scrutinee_place.as_ref().map(|place| (Some(place), scrutinee_span));
454                        let scope = this.declare_bindings(
455                            None,
456                            arm.span,
457                            &arm.pattern,
458                            arm.guard,
459                            opt_scrutinee_place,
460                        );
461
462                        let arm_block = this.bind_pattern(
463                            outer_source_info,
464                            branch,
465                            &built_match_tree.fake_borrow_temps,
466                            scrutinee_span,
467                            Some((arm, match_scope)),
468                        );
469
470                        this.fixed_temps_scope = old_dedup_scope;
471
472                        if let Some(source_scope) = scope {
473                            this.source_scope = source_scope;
474                        }
475
476                        this.expr_into_dest(destination, arm_block, arm.body)
477                    })
478                })
479                .into_block()
480            })
481            .collect();
482
483        // all the arm blocks will rejoin here
484        let end_block = self.cfg.start_new_block();
485
486        let end_brace = self.source_info(
487            outer_source_info.span.with_lo(outer_source_info.span.hi() - BytePos::from_usize(1)),
488        );
489        for arm_block in arm_end_blocks {
490            let block = &self.cfg.basic_blocks[arm_block];
491            let last_location = block.statements.last().map(|s| s.source_info);
492
493            self.cfg.goto(arm_block, last_location.unwrap_or(end_brace), end_block);
494        }
495
496        self.source_scope = outer_source_info.scope;
497
498        end_block.unit()
499    }
500
501    /// For a top-level `match` arm or a `let` binding, binds the variables and
502    /// ascribes types, and also checks the match arm guard (if present).
503    ///
504    /// `arm_scope` should be `Some` if and only if this is called for a
505    /// `match` arm.
506    ///
507    /// In the presence of or-patterns, a match arm might have multiple
508    /// sub-branches representing different ways to match, with each sub-branch
509    /// requiring its own bindings and its own copy of the guard. This method
510    /// handles those sub-branches individually, and then has them jump together
511    /// to a common block.
512    ///
513    /// Returns a single block that the match arm can be lowered into.
514    /// (For `let` bindings, this is the code that can use the bindings.)
515    fn bind_pattern(
516        &mut self,
517        outer_source_info: SourceInfo,
518        branch: MatchTreeBranch<'tcx>,
519        fake_borrow_temps: &[(Place<'tcx>, Local, FakeBorrowKind)],
520        scrutinee_span: Span,
521        arm_match_scope: Option<(&Arm<'tcx>, region::Scope)>,
522    ) -> BasicBlock {
523        if branch.sub_branches.len() == 1 {
524            let [sub_branch] = branch.sub_branches.try_into().unwrap();
525            // Avoid generating another `BasicBlock` when we only have one sub branch.
526            self.bind_and_guard_matched_candidate(
527                sub_branch,
528                fake_borrow_temps,
529                scrutinee_span,
530                arm_match_scope,
531                ScheduleDrops::Yes,
532            )
533        } else {
534            // It's helpful to avoid scheduling drops multiple times to save
535            // drop elaboration from having to clean up the extra drops.
536            //
537            // If we are in a `let` then we only schedule drops for the first
538            // candidate.
539            //
540            // If we're in a `match` arm then we could have a case like so:
541            //
542            // Ok(x) | Err(x) if return => { /* ... */ }
543            //
544            // In this case we don't want a drop of `x` scheduled when we
545            // return: it isn't bound by move until right before enter the arm.
546            // To handle this we instead unschedule it's drop after each time
547            // we lower the guard.
548            // As a result, we end up with the drop order of the last sub-branch we lower. To use
549            // the drop order for the first sub-branch, we lower sub-branches in reverse (#142163).
550            let target_block = self.cfg.start_new_block();
551            for (pos, sub_branch) in branch.sub_branches.into_iter().rev().with_position() {
552                debug_assert!(pos != Position::Only);
553                let schedule_drops =
554                    if pos == Position::Last { ScheduleDrops::Yes } else { ScheduleDrops::No };
555                let binding_end = self.bind_and_guard_matched_candidate(
556                    sub_branch,
557                    fake_borrow_temps,
558                    scrutinee_span,
559                    arm_match_scope,
560                    schedule_drops,
561                );
562                self.cfg.goto(binding_end, outer_source_info, target_block);
563            }
564
565            target_block
566        }
567    }
568
569    pub(super) fn expr_into_pattern(
570        &mut self,
571        mut block: BasicBlock,
572        irrefutable_pat: &Pat<'tcx>,
573        initializer_id: ExprId,
574    ) -> BlockAnd<()> {
575        match irrefutable_pat.kind {
576            // Optimize the case of `let x = ...` to write directly into `x`
577            PatKind::Binding { mode: BindingMode(ByRef::No, _), var, subpattern: None, .. } => {
578                let place = self.storage_live_binding(
579                    block,
580                    var,
581                    irrefutable_pat.span,
582                    OutsideGuard,
583                    ScheduleDrops::Yes,
584                );
585                block = self.expr_into_dest(place, block, initializer_id).into_block();
586
587                // Inject a fake read, see comments on `FakeReadCause::ForLet`.
588                let source_info = self.source_info(irrefutable_pat.span);
589                self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet(None), place);
590
591                self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
592                block.unit()
593            }
594
595            // Optimize the case of `let x: T = ...` to write directly
596            // into `x` and then require that `T == typeof(x)`.
597            PatKind::AscribeUserType {
598                ref subpattern,
599                ascription: thir::Ascription { ref annotation, variance: _ },
600            } if let PatKind::Binding {
601                mode: BindingMode(ByRef::No, _),
602                var,
603                subpattern: None,
604                ..
605            } = subpattern.kind =>
606            {
607                let place = self.storage_live_binding(
608                    block,
609                    var,
610                    irrefutable_pat.span,
611                    OutsideGuard,
612                    ScheduleDrops::Yes,
613                );
614                block = self.expr_into_dest(place, block, initializer_id).into_block();
615
616                // Inject a fake read, see comments on `FakeReadCause::ForLet`.
617                let pattern_source_info = self.source_info(irrefutable_pat.span);
618                let cause_let = FakeReadCause::ForLet(None);
619                self.cfg.push_fake_read(block, pattern_source_info, cause_let, place);
620
621                let ty_source_info = self.source_info(annotation.span);
622
623                let base = self.canonical_user_type_annotations.push(annotation.clone());
624                self.cfg.push(
625                    block,
626                    Statement::new(
627                        ty_source_info,
628                        StatementKind::AscribeUserType(
629                            Box::new((place, UserTypeProjection { base, projs: Vec::new() })),
630                            // We always use invariant as the variance here. This is because the
631                            // variance field from the ascription refers to the variance to use
632                            // when applying the type to the value being matched, but this
633                            // ascription applies rather to the type of the binding. e.g., in this
634                            // example:
635                            //
636                            // ```
637                            // let x: T = <expr>
638                            // ```
639                            //
640                            // We are creating an ascription that defines the type of `x` to be
641                            // exactly `T` (i.e., with invariance). The variance field, in
642                            // contrast, is intended to be used to relate `T` to the type of
643                            // `<expr>`.
644                            ty::Invariant,
645                        ),
646                    ),
647                );
648
649                self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
650                block.unit()
651            }
652
653            _ => {
654                let initializer = &self.thir[initializer_id];
655                let place_builder =
656                    unpack!(block = self.lower_scrutinee(block, initializer_id, initializer.span));
657                self.place_into_pattern(block, irrefutable_pat, place_builder, true)
658            }
659        }
660    }
661
662    pub(crate) fn place_into_pattern(
663        &mut self,
664        block: BasicBlock,
665        irrefutable_pat: &Pat<'tcx>,
666        initializer: PlaceBuilder<'tcx>,
667        set_match_place: bool,
668    ) -> BlockAnd<()> {
669        let built_tree = self.lower_match_tree(
670            block,
671            irrefutable_pat.span,
672            &initializer,
673            irrefutable_pat.span,
674            vec![(irrefutable_pat, HasMatchGuard::No)],
675            false,
676        );
677        let [branch] = built_tree.branches.try_into().unwrap();
678
679        // For matches and function arguments, the place that is being matched
680        // can be set when creating the variables. But the place for
681        // let PATTERN = ... might not even exist until we do the assignment.
682        // so we set it here instead.
683        if set_match_place {
684            // `try_to_place` may fail if it is unable to resolve the given `PlaceBuilder` inside a
685            // closure. In this case, we don't want to include a scrutinee place.
686            // `scrutinee_place_builder` will fail for destructured assignments. This is because a
687            // closure only captures the precise places that it will read and as a result a closure
688            // may not capture the entire tuple/struct and rather have individual places that will
689            // be read in the final MIR.
690            // Example:
691            // ```
692            // let foo = (0, 1);
693            // let c = || {
694            //    let (v1, v2) = foo;
695            // };
696            // ```
697            if let Some(place) = initializer.try_to_place(self) {
698                // Because or-alternatives bind the same variables, we only explore the first one.
699                let first_sub_branch = branch.sub_branches.first().unwrap();
700                for binding in &first_sub_branch.bindings {
701                    let local = self.var_local_id(binding.var_id, OutsideGuard);
702                    if let LocalInfo::User(BindingForm::Var(VarBindingForm {
703                        opt_match_place: Some((ref mut match_place, _)),
704                        ..
705                    })) = **self.local_decls[local].local_info.as_mut().unwrap_crate_local()
706                    {
707                        *match_place = Some(place);
708                    } else {
709                        bug!("Let binding to non-user variable.")
710                    };
711                }
712            }
713        }
714
715        self.bind_pattern(
716            self.source_info(irrefutable_pat.span),
717            branch,
718            &[],
719            irrefutable_pat.span,
720            None,
721        )
722        .unit()
723    }
724
725    /// Declares the bindings of the given patterns and returns the visibility
726    /// scope for the bindings in these patterns, if such a scope had to be
727    /// created. NOTE: Declaring the bindings should always be done in their
728    /// drop scope.
729    #[instrument(skip(self), level = "debug")]
730    pub(crate) fn declare_bindings(
731        &mut self,
732        mut visibility_scope: Option<SourceScope>,
733        scope_span: Span,
734        pattern: &Pat<'tcx>,
735        guard: Option<ExprId>,
736        opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
737    ) -> Option<SourceScope> {
738        self.visit_primary_bindings_special(
739            pattern,
740            &ProjectedUserTypesNode::None,
741            &mut |this, name, mode, var, span, ty, user_tys| {
742                let vis_scope = *visibility_scope
743                    .get_or_insert_with(|| this.new_source_scope(scope_span, LintLevel::Inherited));
744                let source_info = SourceInfo { span, scope: this.source_scope };
745                let user_tys = user_tys.build_user_type_projections();
746
747                this.declare_binding(
748                    source_info,
749                    vis_scope,
750                    name,
751                    mode,
752                    var,
753                    ty,
754                    user_tys,
755                    ArmHasGuard(guard.is_some()),
756                    opt_match_place.map(|(x, y)| (x.cloned(), y)),
757                    pattern.span,
758                );
759            },
760        );
761        if let Some(guard_expr) = guard {
762            self.declare_guard_bindings(guard_expr, scope_span, visibility_scope);
763        }
764        visibility_scope
765    }
766
767    /// Declare bindings in a guard. This has to be done when declaring bindings
768    /// for an arm to ensure that or patterns only have one version of each
769    /// variable.
770    pub(crate) fn declare_guard_bindings(
771        &mut self,
772        guard_expr: ExprId,
773        scope_span: Span,
774        visibility_scope: Option<SourceScope>,
775    ) {
776        match self.thir.exprs[guard_expr].kind {
777            ExprKind::Let { expr: _, pat: ref guard_pat } => {
778                // FIXME: pass a proper `opt_match_place`
779                self.declare_bindings(visibility_scope, scope_span, guard_pat, None, None);
780            }
781            ExprKind::Scope { value, .. } => {
782                self.declare_guard_bindings(value, scope_span, visibility_scope);
783            }
784            ExprKind::Use { source } => {
785                self.declare_guard_bindings(source, scope_span, visibility_scope);
786            }
787            ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
788                self.declare_guard_bindings(lhs, scope_span, visibility_scope);
789                self.declare_guard_bindings(rhs, scope_span, visibility_scope);
790            }
791            _ => {}
792        }
793    }
794
795    /// Emits a [`StatementKind::StorageLive`] for the given var, and also
796    /// schedules a drop if requested (and possible).
797    pub(crate) fn storage_live_binding(
798        &mut self,
799        block: BasicBlock,
800        var: LocalVarId,
801        span: Span,
802        for_guard: ForGuard,
803        schedule_drop: ScheduleDrops,
804    ) -> Place<'tcx> {
805        let local_id = self.var_local_id(var, for_guard);
806        let source_info = self.source_info(span);
807        self.cfg.push(block, Statement::new(source_info, StatementKind::StorageLive(local_id)));
808        // Although there is almost always scope for given variable in corner cases
809        // like #92893 we might get variable with no scope.
810        if let Some(region_scope) = self.region_scope_tree.var_scope(var.0.local_id)
811            && matches!(schedule_drop, ScheduleDrops::Yes)
812        {
813            self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
814        }
815        Place::from(local_id)
816    }
817
818    pub(crate) fn schedule_drop_for_binding(
819        &mut self,
820        var: LocalVarId,
821        span: Span,
822        for_guard: ForGuard,
823    ) {
824        let local_id = self.var_local_id(var, for_guard);
825        if let Some(region_scope) = self.region_scope_tree.var_scope(var.0.local_id) {
826            self.schedule_drop(span, region_scope, local_id, DropKind::Value);
827        }
828    }
829
830    /// Visits all of the "primary" bindings in a pattern, i.e. the leftmost
831    /// occurrence of each variable bound by the pattern.
832    /// See [`PatKind::Binding::is_primary`] for more context.
833    ///
834    /// This variant provides only the limited subset of binding data needed
835    /// by its callers, and should be a "pure" visit without side-effects.
836    pub(super) fn visit_primary_bindings(
837        &mut self,
838        pattern: &Pat<'tcx>,
839        f: &mut impl FnMut(&mut Self, LocalVarId, Span),
840    ) {
841        pattern.walk_always(|pat| {
842            if let PatKind::Binding { var, is_primary: true, .. } = pat.kind {
843                f(self, var, pat.span);
844            }
845        })
846    }
847
848    /// Visits all of the "primary" bindings in a pattern, while preparing
849    /// additional user-type-annotation data needed by `declare_bindings`.
850    ///
851    /// This also has the side-effect of pushing all user type annotations
852    /// onto `canonical_user_type_annotations`, so that they end up in MIR
853    /// even if they aren't associated with any bindings.
854    #[instrument(level = "debug", skip(self, f))]
855    fn visit_primary_bindings_special(
856        &mut self,
857        pattern: &Pat<'tcx>,
858        user_tys: &ProjectedUserTypesNode<'_>,
859        f: &mut impl FnMut(
860            &mut Self,
861            Symbol,
862            BindingMode,
863            LocalVarId,
864            Span,
865            Ty<'tcx>,
866            &ProjectedUserTypesNode<'_>,
867        ),
868    ) {
869        // Avoid having to write the full method name at each recursive call.
870        let visit_subpat = |this: &mut Self, subpat, user_tys: &_, f: &mut _| {
871            this.visit_primary_bindings_special(subpat, user_tys, f)
872        };
873
874        match pattern.kind {
875            PatKind::Binding { name, mode, var, ty, ref subpattern, is_primary, .. } => {
876                if is_primary {
877                    f(self, name, mode, var, pattern.span, ty, user_tys);
878                }
879                if let Some(subpattern) = subpattern.as_ref() {
880                    visit_subpat(self, subpattern, user_tys, f);
881                }
882            }
883
884            PatKind::Array { ref prefix, ref slice, ref suffix }
885            | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
886                let from = u64::try_from(prefix.len()).unwrap();
887                let to = u64::try_from(suffix.len()).unwrap();
888                for subpattern in prefix.iter() {
889                    visit_subpat(self, subpattern, &user_tys.index(), f);
890                }
891                if let Some(subpattern) = slice {
892                    visit_subpat(self, subpattern, &user_tys.subslice(from, to), f);
893                }
894                for subpattern in suffix.iter() {
895                    visit_subpat(self, subpattern, &user_tys.index(), f);
896                }
897            }
898
899            PatKind::Constant { .. }
900            | PatKind::Range { .. }
901            | PatKind::Missing
902            | PatKind::Wild
903            | PatKind::Never
904            | PatKind::Error(_) => {}
905
906            PatKind::Deref { ref subpattern } => {
907                visit_subpat(self, subpattern, &user_tys.deref(), f);
908            }
909
910            PatKind::DerefPattern { ref subpattern, .. } => {
911                visit_subpat(self, subpattern, &ProjectedUserTypesNode::None, f);
912            }
913
914            PatKind::AscribeUserType {
915                ref subpattern,
916                ascription: thir::Ascription { ref annotation, variance: _ },
917            } => {
918                // This corresponds to something like
919                //
920                // ```
921                // let A::<'a>(_): A<'static> = ...;
922                // ```
923                //
924                // Note that the variance doesn't apply here, as we are tracking the effect
925                // of `user_ty` on any bindings contained with subpattern.
926
927                // Caution: Pushing this user type here is load-bearing even for
928                // patterns containing no bindings, to ensure that the type ends
929                // up represented in MIR _somewhere_.
930                let base_user_ty = self.canonical_user_type_annotations.push(annotation.clone());
931                let subpattern_user_tys = user_tys.push_user_type(base_user_ty);
932                visit_subpat(self, subpattern, &subpattern_user_tys, f)
933            }
934
935            PatKind::ExpandedConstant { ref subpattern, .. } => {
936                visit_subpat(self, subpattern, user_tys, f)
937            }
938
939            PatKind::Leaf { ref subpatterns } => {
940                for subpattern in subpatterns {
941                    let subpattern_user_tys = user_tys.leaf(subpattern.field);
942                    debug!("visit_primary_bindings: subpattern_user_tys={subpattern_user_tys:?}");
943                    visit_subpat(self, &subpattern.pattern, &subpattern_user_tys, f);
944                }
945            }
946
947            PatKind::Variant { adt_def, args: _, variant_index, ref subpatterns } => {
948                for subpattern in subpatterns {
949                    let subpattern_user_tys =
950                        user_tys.variant(adt_def, variant_index, subpattern.field);
951                    visit_subpat(self, &subpattern.pattern, &subpattern_user_tys, f);
952                }
953            }
954            PatKind::Or { ref pats } => {
955                // In cases where we recover from errors the primary bindings
956                // may not all be in the leftmost subpattern. For example in
957                // `let (x | y) = ...`, the primary binding of `y` occurs in
958                // the right subpattern
959                for subpattern in pats.iter() {
960                    visit_subpat(self, subpattern, user_tys, f);
961                }
962            }
963        }
964    }
965}
966
967/// Data extracted from a pattern that doesn't affect which branch is taken. Collected during
968/// pattern simplification and not mutated later.
969#[derive(Debug, Clone)]
970struct PatternExtraData<'tcx> {
971    /// [`Span`] of the original pattern.
972    span: Span,
973
974    /// Bindings that must be established.
975    bindings: Vec<SubpatternBindings<'tcx>>,
976
977    /// Types that must be asserted.
978    ascriptions: Vec<Ascription<'tcx>>,
979
980    /// Whether this corresponds to a never pattern.
981    is_never: bool,
982}
983
984impl<'tcx> PatternExtraData<'tcx> {
985    fn is_empty(&self) -> bool {
986        self.bindings.is_empty() && self.ascriptions.is_empty()
987    }
988}
989
990#[derive(Debug, Clone)]
991enum SubpatternBindings<'tcx> {
992    /// A single binding.
993    One(Binding<'tcx>),
994    /// Holds the place for an or-pattern's bindings. This ensures their drops are scheduled in the
995    /// order the primary bindings appear. See rust-lang/rust#142163 for more information.
996    FromOrPattern,
997}
998
999/// A pattern in a form suitable for lowering the match tree, with all irrefutable
1000/// patterns simplified away.
1001///
1002/// Here, "flat" indicates that irrefutable nodes in the pattern tree have been
1003/// recursively replaced with their refutable subpatterns. They are not
1004/// necessarily flat in an absolute sense.
1005///
1006/// Will typically be incorporated into a [`Candidate`].
1007#[derive(Debug, Clone)]
1008struct FlatPat<'tcx> {
1009    /// To match the pattern, all of these must be satisfied...
1010    match_pairs: Vec<MatchPairTree<'tcx>>,
1011
1012    extra_data: PatternExtraData<'tcx>,
1013}
1014
1015impl<'tcx> FlatPat<'tcx> {
1016    /// Creates a `FlatPat` containing a simplified [`MatchPairTree`] list/forest
1017    /// for the given pattern.
1018    fn new(place: PlaceBuilder<'tcx>, pattern: &Pat<'tcx>, cx: &mut Builder<'_, 'tcx>) -> Self {
1019        // Recursively build a tree of match pairs for the given pattern.
1020        let mut match_pairs = vec![];
1021        let mut extra_data = PatternExtraData {
1022            span: pattern.span,
1023            bindings: Vec::new(),
1024            ascriptions: Vec::new(),
1025            is_never: pattern.is_never_pattern(),
1026        };
1027        MatchPairTree::for_pattern(place, pattern, cx, &mut match_pairs, &mut extra_data);
1028
1029        Self { match_pairs, extra_data }
1030    }
1031}
1032
1033/// Candidates are a generalization of (a) top-level match arms, and
1034/// (b) sub-branches of or-patterns, allowing the match-lowering process to handle
1035/// them both in a mostly-uniform way. For example, the list of candidates passed
1036/// to [`Builder::match_candidates`] will often contain a mixture of top-level
1037/// candidates and or-pattern subcandidates.
1038///
1039/// At the start of match lowering, there is one candidate for each match arm.
1040/// During match lowering, arms with or-patterns will be expanded into a tree
1041/// of candidates, where each "leaf" candidate represents one of the ways for
1042/// the arm pattern to successfully match.
1043#[derive(Debug)]
1044struct Candidate<'tcx> {
1045    /// For the candidate to match, all of these must be satisfied...
1046    ///
1047    /// ---
1048    /// Initially contains a list of match pairs created by [`FlatPat`], but is
1049    /// subsequently mutated (in a queue-like way) while lowering the match tree.
1050    /// When this list becomes empty, the candidate is fully matched and becomes
1051    /// a leaf (see [`Builder::select_matched_candidate`]).
1052    ///
1053    /// Key mutations include:
1054    ///
1055    /// - When a match pair is fully satisfied by a test, it is removed from the
1056    ///   list, and its subpairs are added instead (see [`Builder::sort_candidate`]).
1057    /// - During or-pattern expansion, any leading or-pattern is removed, and is
1058    ///   converted into subcandidates (see [`Builder::expand_and_match_or_candidates`]).
1059    /// - After a candidate's subcandidates have been lowered, a copy of any remaining
1060    ///   or-patterns is added to each leaf subcandidate
1061    ///   (see [`Builder::test_remaining_match_pairs_after_or`]).
1062    ///
1063    /// Invariants:
1064    /// - All or-patterns ([`TestCase::Or`]) have been sorted to the end.
1065    match_pairs: Vec<MatchPairTree<'tcx>>,
1066
1067    /// ...and if this is non-empty, one of these subcandidates also has to match...
1068    ///
1069    /// ---
1070    /// Initially a candidate has no subcandidates; they are added (and then immediately
1071    /// lowered) during or-pattern expansion. Their main function is to serve as _output_
1072    /// of match tree lowering, allowing later steps to see the leaf candidates that
1073    /// represent a match of the entire match arm.
1074    ///
1075    /// A candidate no subcandidates is either incomplete (if it has match pairs left),
1076    /// or is a leaf in the match tree. A candidate with one or more subcandidates is
1077    /// an internal node in the match tree.
1078    ///
1079    /// Invariant: at the end of match tree lowering, this must not contain an
1080    /// `is_never` candidate, because that would break binding consistency.
1081    /// - See [`Builder::remove_never_subcandidates`].
1082    subcandidates: Vec<Candidate<'tcx>>,
1083
1084    /// ...and if there is a guard it must be evaluated; if it's `false` then branch to `otherwise_block`.
1085    ///
1086    /// ---
1087    /// For subcandidates, this is copied from the parent candidate, so it indicates
1088    /// whether the enclosing match arm has a guard.
1089    has_guard: bool,
1090
1091    /// Holds extra pattern data that was prepared by [`FlatPat`], including bindings and
1092    /// ascriptions that must be established if this candidate succeeds.
1093    extra_data: PatternExtraData<'tcx>,
1094
1095    /// When setting `self.subcandidates`, we store here the span of the or-pattern they came from.
1096    ///
1097    /// ---
1098    /// Invariant: it is `None` iff `subcandidates.is_empty()`.
1099    /// - FIXME: We sometimes don't unset this when clearing `subcandidates`.
1100    or_span: Option<Span>,
1101
1102    /// The block before the `bindings` have been established.
1103    ///
1104    /// After the match tree has been lowered, [`Builder::lower_match_arms`]
1105    /// will use this as the start point for lowering bindings and guards, and
1106    /// then jump to a shared block containing the arm body.
1107    pre_binding_block: Option<BasicBlock>,
1108
1109    /// The block to branch to if the guard or a nested candidate fails to match.
1110    otherwise_block: Option<BasicBlock>,
1111
1112    /// The earliest block that has only candidates >= this one as descendents. Used for false
1113    /// edges, see the doc for [`Builder::match_expr`].
1114    false_edge_start_block: Option<BasicBlock>,
1115}
1116
1117impl<'tcx> Candidate<'tcx> {
1118    fn new(
1119        place: PlaceBuilder<'tcx>,
1120        pattern: &Pat<'tcx>,
1121        has_guard: HasMatchGuard,
1122        cx: &mut Builder<'_, 'tcx>,
1123    ) -> Self {
1124        // Use `FlatPat` to build simplified match pairs, then immediately
1125        // incorporate them into a new candidate.
1126        Self::from_flat_pat(
1127            FlatPat::new(place, pattern, cx),
1128            matches!(has_guard, HasMatchGuard::Yes),
1129        )
1130    }
1131
1132    /// Incorporates an already-simplified [`FlatPat`] into a new candidate.
1133    fn from_flat_pat(flat_pat: FlatPat<'tcx>, has_guard: bool) -> Self {
1134        let mut this = Candidate {
1135            match_pairs: flat_pat.match_pairs,
1136            extra_data: flat_pat.extra_data,
1137            has_guard,
1138            subcandidates: Vec::new(),
1139            or_span: None,
1140            otherwise_block: None,
1141            pre_binding_block: None,
1142            false_edge_start_block: None,
1143        };
1144        this.sort_match_pairs();
1145        this
1146    }
1147
1148    /// Restores the invariant that or-patterns must be sorted to the end.
1149    fn sort_match_pairs(&mut self) {
1150        self.match_pairs.sort_by_key(|pair| matches!(pair.test_case, TestCase::Or { .. }));
1151    }
1152
1153    /// Returns whether the first match pair of this candidate is an or-pattern.
1154    fn starts_with_or_pattern(&self) -> bool {
1155        matches!(&*self.match_pairs, [MatchPairTree { test_case: TestCase::Or { .. }, .. }, ..])
1156    }
1157
1158    /// Visit the leaf candidates (those with no subcandidates) contained in
1159    /// this candidate.
1160    fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
1161        traverse_candidate(
1162            self,
1163            &mut (),
1164            &mut move |c, _| visit_leaf(c),
1165            move |c, _| c.subcandidates.iter_mut(),
1166            |_| {},
1167        );
1168    }
1169
1170    /// Visit the leaf candidates in reverse order.
1171    fn visit_leaves_rev<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
1172        traverse_candidate(
1173            self,
1174            &mut (),
1175            &mut move |c, _| visit_leaf(c),
1176            move |c, _| c.subcandidates.iter_mut().rev(),
1177            |_| {},
1178        );
1179    }
1180}
1181
1182/// A depth-first traversal of the `Candidate` and all of its recursive
1183/// subcandidates.
1184///
1185/// This signature is very generic, to support traversing candidate trees by
1186/// reference or by value, and to allow a mutable "context" to be shared by the
1187/// traversal callbacks. Most traversals can use the simpler
1188/// [`Candidate::visit_leaves`] wrapper instead.
1189fn traverse_candidate<'tcx, C, T, I>(
1190    candidate: C,
1191    context: &mut T,
1192    // Called when visiting a "leaf" candidate (with no subcandidates).
1193    visit_leaf: &mut impl FnMut(C, &mut T),
1194    // Called when visiting a "node" candidate (with one or more subcandidates).
1195    // Returns an iterator over the candidate's children (by value or reference).
1196    // Can perform setup before visiting the node's children.
1197    get_children: impl Copy + Fn(C, &mut T) -> I,
1198    // Called after visiting a "node" candidate's children.
1199    complete_children: impl Copy + Fn(&mut T),
1200) where
1201    C: Borrow<Candidate<'tcx>>, // Typically `Candidate` or `&mut Candidate`
1202    I: Iterator<Item = C>,
1203{
1204    if candidate.borrow().subcandidates.is_empty() {
1205        visit_leaf(candidate, context)
1206    } else {
1207        for child in get_children(candidate, context) {
1208            traverse_candidate(child, context, visit_leaf, get_children, complete_children);
1209        }
1210        complete_children(context)
1211    }
1212}
1213
1214#[derive(Clone, Copy, Debug)]
1215struct Binding<'tcx> {
1216    span: Span,
1217    source: Place<'tcx>,
1218    var_id: LocalVarId,
1219    binding_mode: BindingMode,
1220}
1221
1222/// Indicates that the type of `source` must be a subtype of the
1223/// user-given type `user_ty`; this is basically a no-op but can
1224/// influence region inference.
1225#[derive(Clone, Debug)]
1226struct Ascription<'tcx> {
1227    source: Place<'tcx>,
1228    annotation: CanonicalUserTypeAnnotation<'tcx>,
1229    variance: ty::Variance,
1230}
1231
1232/// Partial summary of a [`thir::Pat`], indicating what sort of test should be
1233/// performed to match/reject the pattern, and what the desired test outcome is.
1234/// This avoids having to perform a full match on [`thir::PatKind`] in some places,
1235/// and helps [`TestKind::Switch`] and [`TestKind::SwitchInt`] know what target
1236/// values to use.
1237///
1238/// Created by [`MatchPairTree::for_pattern`], and then inspected primarily by:
1239/// - [`Builder::pick_test_for_match_pair`] (to choose a test)
1240/// - [`Builder::sort_candidate`] (to see how the test interacts with a match pair)
1241///
1242/// Note that or-patterns are not tested directly like the other variants.
1243/// Instead they participate in or-pattern expansion, where they are transformed into
1244/// subcandidates. See [`Builder::expand_and_match_or_candidates`].
1245#[derive(Debug, Clone)]
1246enum TestCase<'tcx> {
1247    Variant { adt_def: ty::AdtDef<'tcx>, variant_index: VariantIdx },
1248    Constant { value: ty::Value<'tcx> },
1249    Range(Arc<PatRange<'tcx>>),
1250    Slice { len: usize, variable_length: bool },
1251    Deref { temp: Place<'tcx>, mutability: Mutability },
1252    Never,
1253    Or { pats: Box<[FlatPat<'tcx>]> },
1254}
1255
1256impl<'tcx> TestCase<'tcx> {
1257    fn as_range(&self) -> Option<&PatRange<'tcx>> {
1258        if let Self::Range(v) = self { Some(v.as_ref()) } else { None }
1259    }
1260}
1261
1262/// Node in a tree of "match pairs", where each pair consists of a place to be
1263/// tested, and a test to perform on that place.
1264///
1265/// Each node also has a list of subpairs (possibly empty) that must also match,
1266/// and a reference to the THIR pattern it represents.
1267#[derive(Debug, Clone)]
1268pub(crate) struct MatchPairTree<'tcx> {
1269    /// This place...
1270    ///
1271    /// ---
1272    /// This can be `None` if it referred to a non-captured place in a closure.
1273    ///
1274    /// Invariant: Can only be `None` when `test_case` is `Or`.
1275    /// Therefore this must be `Some(_)` after or-pattern expansion.
1276    place: Option<Place<'tcx>>,
1277
1278    /// ... must pass this test...
1279    test_case: TestCase<'tcx>,
1280
1281    /// ... and these subpairs must match.
1282    ///
1283    /// ---
1284    /// Subpairs typically represent tests that can only be performed after their
1285    /// parent has succeeded. For example, the pattern `Some(3)` might have an
1286    /// outer match pair that tests for the variant `Some`, and then a subpair
1287    /// that tests its field for the value `3`.
1288    subpairs: Vec<Self>,
1289
1290    /// Type field of the pattern this node was created from.
1291    pattern_ty: Ty<'tcx>,
1292    /// Span field of the pattern this node was created from.
1293    pattern_span: Span,
1294}
1295
1296/// See [`Test`] for more.
1297#[derive(Clone, Debug, PartialEq)]
1298enum TestKind<'tcx> {
1299    /// Test what enum variant a value is.
1300    ///
1301    /// The subset of expected variants is not stored here; instead they are
1302    /// extracted from the [`TestCase`]s of the candidates participating in the
1303    /// test.
1304    Switch {
1305        /// The enum type being tested.
1306        adt_def: ty::AdtDef<'tcx>,
1307    },
1308
1309    /// Test what value an integer or `char` has.
1310    ///
1311    /// The test's target values are not stored here; instead they are extracted
1312    /// from the [`TestCase`]s of the candidates participating in the test.
1313    SwitchInt,
1314
1315    /// Test whether a `bool` is `true` or `false`.
1316    If,
1317
1318    /// Test for equality with value, possibly after an unsizing coercion to
1319    /// `cast_ty`,
1320    Eq {
1321        value: ty::Value<'tcx>,
1322        // Integer types are handled by `SwitchInt`, and constants with ADT
1323        // types and `&[T]` types are converted back into patterns, so this can
1324        // only be `&str` or floats.
1325        cast_ty: Ty<'tcx>,
1326    },
1327
1328    /// Test whether the value falls within an inclusive or exclusive range.
1329    Range(Arc<PatRange<'tcx>>),
1330
1331    /// Test that the length of the slice is `== len` or `>= len`.
1332    Len { len: u64, op: BinOp },
1333
1334    /// Call `Deref::deref[_mut]` on the value.
1335    Deref {
1336        /// Temporary to store the result of `deref()`/`deref_mut()`.
1337        temp: Place<'tcx>,
1338        mutability: Mutability,
1339    },
1340
1341    /// Assert unreachability of never patterns.
1342    Never,
1343}
1344
1345/// A test to perform to determine which [`Candidate`] matches a value.
1346///
1347/// [`Test`] is just the test to perform; it does not include the value
1348/// to be tested.
1349#[derive(Debug)]
1350pub(crate) struct Test<'tcx> {
1351    span: Span,
1352    kind: TestKind<'tcx>,
1353}
1354
1355/// The branch to be taken after a test.
1356#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1357enum TestBranch<'tcx> {
1358    /// Success branch, used for tests with two possible outcomes.
1359    Success,
1360    /// Branch corresponding to this constant. Must be a scalar.
1361    Constant(ty::Value<'tcx>),
1362    /// Branch corresponding to this variant.
1363    Variant(VariantIdx),
1364    /// Failure branch for tests with two possible outcomes, and "otherwise" branch for other tests.
1365    Failure,
1366}
1367
1368impl<'tcx> TestBranch<'tcx> {
1369    fn as_constant(&self) -> Option<ty::Value<'tcx>> {
1370        if let Self::Constant(v) = self { Some(*v) } else { None }
1371    }
1372}
1373
1374/// `ArmHasGuard` is a wrapper around a boolean flag. It indicates whether
1375/// a match arm has a guard expression attached to it.
1376#[derive(Copy, Clone, Debug)]
1377pub(crate) struct ArmHasGuard(pub(crate) bool);
1378
1379///////////////////////////////////////////////////////////////////////////
1380// Main matching algorithm
1381
1382/// A sub-branch in the output of match lowering. Match lowering has generated MIR code that will
1383/// branch to `success_block` when the matched value matches the corresponding pattern. If there is
1384/// a guard, its failure must continue to `otherwise_block`, which will resume testing patterns.
1385#[derive(Debug, Clone)]
1386struct MatchTreeSubBranch<'tcx> {
1387    span: Span,
1388    /// The block that is branched to if the corresponding subpattern matches.
1389    success_block: BasicBlock,
1390    /// The block to branch to if this arm had a guard and the guard fails.
1391    otherwise_block: BasicBlock,
1392    /// The bindings to set up in this sub-branch.
1393    bindings: Vec<Binding<'tcx>>,
1394    /// The ascriptions to set up in this sub-branch.
1395    ascriptions: Vec<Ascription<'tcx>>,
1396    /// Whether the sub-branch corresponds to a never pattern.
1397    is_never: bool,
1398}
1399
1400/// A branch in the output of match lowering.
1401#[derive(Debug, Clone)]
1402struct MatchTreeBranch<'tcx> {
1403    sub_branches: Vec<MatchTreeSubBranch<'tcx>>,
1404}
1405
1406/// The result of generating MIR for a pattern-matching expression. Each input branch/arm/pattern
1407/// gives rise to an output `MatchTreeBranch`. If one of the patterns matches, we branch to the
1408/// corresponding `success_block`. If none of the patterns matches, we branch to `otherwise_block`.
1409///
1410/// Each branch is made of one of more sub-branches, corresponding to or-patterns. E.g.
1411/// ```ignore(illustrative)
1412/// match foo {
1413///     (x, false) | (false, x) => {}
1414///     (true, true) => {}
1415/// }
1416/// ```
1417/// Here the first arm gives the first `MatchTreeBranch`, which has two sub-branches, one for each
1418/// alternative of the or-pattern. They are kept separate because each needs to bind `x` to a
1419/// different place.
1420#[derive(Debug, Clone)]
1421pub(crate) struct BuiltMatchTree<'tcx> {
1422    branches: Vec<MatchTreeBranch<'tcx>>,
1423    otherwise_block: BasicBlock,
1424    /// If any of the branches had a guard, we collect here the places and locals to fakely borrow
1425    /// to ensure match guards can't modify the values as we match them. For more details, see
1426    /// [`util::collect_fake_borrows`].
1427    fake_borrow_temps: Vec<(Place<'tcx>, Local, FakeBorrowKind)>,
1428}
1429
1430impl<'tcx> MatchTreeSubBranch<'tcx> {
1431    fn from_sub_candidate(
1432        candidate: Candidate<'tcx>,
1433        parent_data: &Vec<PatternExtraData<'tcx>>,
1434    ) -> Self {
1435        debug_assert!(candidate.match_pairs.is_empty());
1436        MatchTreeSubBranch {
1437            span: candidate.extra_data.span,
1438            success_block: candidate.pre_binding_block.unwrap(),
1439            otherwise_block: candidate.otherwise_block.unwrap(),
1440            bindings: sub_branch_bindings(parent_data, &candidate.extra_data.bindings),
1441            ascriptions: parent_data
1442                .iter()
1443                .flat_map(|d| &d.ascriptions)
1444                .cloned()
1445                .chain(candidate.extra_data.ascriptions)
1446                .collect(),
1447            is_never: candidate.extra_data.is_never,
1448        }
1449    }
1450}
1451
1452impl<'tcx> MatchTreeBranch<'tcx> {
1453    fn from_candidate(candidate: Candidate<'tcx>) -> Self {
1454        let mut sub_branches = Vec::new();
1455        traverse_candidate(
1456            candidate,
1457            &mut Vec::new(),
1458            &mut |candidate: Candidate<'_>, parent_data: &mut Vec<PatternExtraData<'_>>| {
1459                sub_branches.push(MatchTreeSubBranch::from_sub_candidate(candidate, parent_data));
1460            },
1461            |inner_candidate, parent_data| {
1462                parent_data.push(inner_candidate.extra_data);
1463                inner_candidate.subcandidates.into_iter()
1464            },
1465            |parent_data| {
1466                parent_data.pop();
1467            },
1468        );
1469        MatchTreeBranch { sub_branches }
1470    }
1471}
1472
1473/// Collects the bindings for a [`MatchTreeSubBranch`], preserving the order they appear in the
1474/// pattern, as though the or-alternatives chosen in this sub-branch were inlined.
1475fn sub_branch_bindings<'tcx>(
1476    parents: &[PatternExtraData<'tcx>],
1477    leaf_bindings: &[SubpatternBindings<'tcx>],
1478) -> Vec<Binding<'tcx>> {
1479    // In the common case, all bindings will be in leaves. Allocate to fit the leaf's bindings.
1480    let mut all_bindings = Vec::with_capacity(leaf_bindings.len());
1481    let mut remainder = parents
1482        .iter()
1483        .map(|parent| parent.bindings.as_slice())
1484        .chain([leaf_bindings])
1485        // Skip over unsimplified or-patterns without bindings.
1486        .filter(|bindings| !bindings.is_empty());
1487    if let Some(candidate_bindings) = remainder.next() {
1488        push_sub_branch_bindings(&mut all_bindings, candidate_bindings, &mut remainder);
1489    }
1490    // Make sure we've included all bindings. For ill-formed patterns like `(x, _ | y)`, we may not
1491    // have collected all bindings yet, since we only check the first alternative when determining
1492    // whether to inline subcandidates' bindings.
1493    // FIXME(@dianne): prevent ill-formed patterns from getting here
1494    while let Some(candidate_bindings) = remainder.next() {
1495        ty::tls::with(|tcx| {
1496            tcx.dcx().delayed_bug("mismatched or-pattern bindings but no error emitted")
1497        });
1498        // To recover, we collect the rest in an arbitrary order.
1499        push_sub_branch_bindings(&mut all_bindings, candidate_bindings, &mut remainder);
1500    }
1501    all_bindings
1502}
1503
1504/// Helper for [`sub_branch_bindings`]. Collects bindings from `candidate_bindings` into
1505/// `flattened`. Bindings in or-patterns are collected recursively from `remainder`.
1506fn push_sub_branch_bindings<'c, 'tcx: 'c>(
1507    flattened: &mut Vec<Binding<'tcx>>,
1508    candidate_bindings: &'c [SubpatternBindings<'tcx>],
1509    remainder: &mut impl Iterator<Item = &'c [SubpatternBindings<'tcx>]>,
1510) {
1511    for subpat_bindings in candidate_bindings {
1512        match subpat_bindings {
1513            SubpatternBindings::One(binding) => flattened.push(*binding),
1514            SubpatternBindings::FromOrPattern => {
1515                // Inline bindings from an or-pattern. By construction, this always
1516                // corresponds to a subcandidate and its closest descendants (i.e. those
1517                // from nested or-patterns, but not adjacent or-patterns). To handle
1518                // adjacent or-patterns, e.g. `(x | x, y | y)`, we update the `remainder` to
1519                // point to the first descendant candidate from outside this or-pattern.
1520                if let Some(subcandidate_bindings) = remainder.next() {
1521                    push_sub_branch_bindings(flattened, subcandidate_bindings, remainder);
1522                } else {
1523                    // For ill-formed patterns like `x | _`, we may not have any subcandidates left
1524                    // to inline bindings from.
1525                    // FIXME(@dianne): prevent ill-formed patterns from getting here
1526                    ty::tls::with(|tcx| {
1527                        tcx.dcx().delayed_bug("mismatched or-pattern bindings but no error emitted")
1528                    });
1529                };
1530            }
1531        }
1532    }
1533}
1534
1535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1536pub(crate) enum HasMatchGuard {
1537    Yes,
1538    No,
1539}
1540
1541impl<'a, 'tcx> Builder<'a, 'tcx> {
1542    /// The entrypoint of the matching algorithm. Create the decision tree for the match expression,
1543    /// starting from `block`.
1544    ///
1545    /// `patterns` is a list of patterns, one for each arm. The associated boolean indicates whether
1546    /// the arm has a guard.
1547    ///
1548    /// `refutable` indicates whether the candidate list is refutable (for `if let` and `let else`)
1549    /// or not (for `let` and `match`). In the refutable case we return the block to which we branch
1550    /// on failure.
1551    pub(crate) fn lower_match_tree(
1552        &mut self,
1553        block: BasicBlock,
1554        scrutinee_span: Span,
1555        scrutinee_place_builder: &PlaceBuilder<'tcx>,
1556        match_start_span: Span,
1557        patterns: Vec<(&Pat<'tcx>, HasMatchGuard)>,
1558        refutable: bool,
1559    ) -> BuiltMatchTree<'tcx> {
1560        // Assemble the initial list of candidates. These top-level candidates are 1:1 with the
1561        // input patterns, but other parts of match lowering also introduce subcandidates (for
1562        // sub-or-patterns). So inside the algorithm, the candidates list may not correspond to
1563        // match arms directly.
1564        let mut candidates: Vec<Candidate<'_>> = patterns
1565            .into_iter()
1566            .map(|(pat, has_guard)| {
1567                Candidate::new(scrutinee_place_builder.clone(), pat, has_guard, self)
1568            })
1569            .collect();
1570
1571        let fake_borrow_temps = util::collect_fake_borrows(
1572            self,
1573            &candidates,
1574            scrutinee_span,
1575            scrutinee_place_builder.base(),
1576        );
1577
1578        // This will generate code to test scrutinee_place and branch to the appropriate arm block.
1579        // If none of the arms match, we branch to `otherwise_block`. When lowering a `match`
1580        // expression, exhaustiveness checking ensures that this block is unreachable.
1581        let mut candidate_refs = candidates.iter_mut().collect::<Vec<_>>();
1582        let otherwise_block =
1583            self.match_candidates(match_start_span, scrutinee_span, block, &mut candidate_refs);
1584
1585        // Set up false edges so that the borrow-checker cannot make use of the specific CFG we
1586        // generated. We falsely branch from each candidate to the one below it to make it as if we
1587        // were testing match branches one by one in order. In the refutable case we also want a
1588        // false edge to the final failure block.
1589        let mut next_candidate_start_block = if refutable { Some(otherwise_block) } else { None };
1590        for candidate in candidates.iter_mut().rev() {
1591            let has_guard = candidate.has_guard;
1592            candidate.visit_leaves_rev(|leaf_candidate| {
1593                if let Some(next_candidate_start_block) = next_candidate_start_block {
1594                    let source_info = self.source_info(leaf_candidate.extra_data.span);
1595                    // Falsely branch to `next_candidate_start_block` before reaching pre_binding.
1596                    let old_pre_binding = leaf_candidate.pre_binding_block.unwrap();
1597                    let new_pre_binding = self.cfg.start_new_block();
1598                    self.false_edges(
1599                        old_pre_binding,
1600                        new_pre_binding,
1601                        next_candidate_start_block,
1602                        source_info,
1603                    );
1604                    leaf_candidate.pre_binding_block = Some(new_pre_binding);
1605                    if has_guard {
1606                        // Falsely branch to `next_candidate_start_block` also if the guard fails.
1607                        let new_otherwise = self.cfg.start_new_block();
1608                        let old_otherwise = leaf_candidate.otherwise_block.unwrap();
1609                        self.false_edges(
1610                            new_otherwise,
1611                            old_otherwise,
1612                            next_candidate_start_block,
1613                            source_info,
1614                        );
1615                        leaf_candidate.otherwise_block = Some(new_otherwise);
1616                    }
1617                }
1618                assert!(leaf_candidate.false_edge_start_block.is_some());
1619                next_candidate_start_block = leaf_candidate.false_edge_start_block;
1620            });
1621        }
1622
1623        if !refutable {
1624            // Match checking ensures `otherwise_block` is actually unreachable in irrefutable
1625            // cases.
1626            let source_info = self.source_info(scrutinee_span);
1627
1628            // Matching on a scrutinee place of an uninhabited type doesn't generate any memory
1629            // reads by itself, and so if the place is uninitialized we wouldn't know. In order to
1630            // disallow the following:
1631            // ```rust
1632            // let x: !;
1633            // match x {}
1634            // ```
1635            // we add a dummy read on the place.
1636            //
1637            // NOTE: If we require never patterns for empty matches, those will check that the place
1638            // is initialized, and so this read would no longer be needed.
1639            let cause_matched_place = FakeReadCause::ForMatchedPlace(None);
1640
1641            if let Some(scrutinee_place) = scrutinee_place_builder.try_to_place(self) {
1642                self.cfg.push_fake_read(
1643                    otherwise_block,
1644                    source_info,
1645                    cause_matched_place,
1646                    scrutinee_place,
1647                );
1648            }
1649
1650            self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
1651        }
1652
1653        BuiltMatchTree {
1654            branches: candidates.into_iter().map(MatchTreeBranch::from_candidate).collect(),
1655            otherwise_block,
1656            fake_borrow_temps,
1657        }
1658    }
1659
1660    /// The main match algorithm. It begins with a set of candidates `candidates` and has the job of
1661    /// generating code that branches to an appropriate block if the scrutinee matches one of these
1662    /// candidates. The
1663    /// candidates are ordered such that the first item in the list
1664    /// has the highest priority. When a candidate is found to match
1665    /// the value, we will set and generate a branch to the appropriate
1666    /// pre-binding block.
1667    ///
1668    /// If none of the candidates apply, we continue to the returned `otherwise_block`.
1669    ///
1670    /// Note that while `match` expressions in the Rust language are exhaustive,
1671    /// candidate lists passed to this method are often _non-exhaustive_.
1672    /// For example, the match lowering process will frequently divide up the
1673    /// list of candidates, and recursively call this method with a non-exhaustive
1674    /// subset of candidates.
1675    /// See [`Builder::test_candidates`] for more details on this
1676    /// "backtracking automata" approach.
1677    ///
1678    /// For an example of how we use `otherwise_block`, consider:
1679    /// ```
1680    /// # fn foo((x, y): (bool, bool)) -> u32 {
1681    /// match (x, y) {
1682    ///     (true, true) => 1,
1683    ///     (_, false) => 2,
1684    ///     (false, true) => 3,
1685    /// }
1686    /// # }
1687    /// ```
1688    /// For this match, we generate something like:
1689    /// ```
1690    /// # fn foo((x, y): (bool, bool)) -> u32 {
1691    /// if x {
1692    ///     if y {
1693    ///         return 1
1694    ///     } else {
1695    ///         // continue
1696    ///     }
1697    /// } else {
1698    ///     // continue
1699    /// }
1700    /// if y {
1701    ///     if x {
1702    ///         // This is actually unreachable because the `(true, true)` case was handled above,
1703    ///         // but we don't know that from within the lowering algorithm.
1704    ///         // continue
1705    ///     } else {
1706    ///         return 3
1707    ///     }
1708    /// } else {
1709    ///     return 2
1710    /// }
1711    /// // this is the final `otherwise_block`, which is unreachable because the match was exhaustive.
1712    /// unreachable!()
1713    /// # }
1714    /// ```
1715    ///
1716    /// Every `continue` is an instance of branching to some `otherwise_block` somewhere deep within
1717    /// the algorithm. For more details on why we lower like this, see [`Builder::test_candidates`].
1718    ///
1719    /// Note how we test `x` twice. This is the tradeoff of backtracking automata: we prefer smaller
1720    /// code size so we accept non-optimal code paths.
1721    #[instrument(skip(self), level = "debug")]
1722    fn match_candidates(
1723        &mut self,
1724        span: Span,
1725        scrutinee_span: Span,
1726        start_block: BasicBlock,
1727        candidates: &mut [&mut Candidate<'tcx>],
1728    ) -> BasicBlock {
1729        ensure_sufficient_stack(|| {
1730            self.match_candidates_inner(span, scrutinee_span, start_block, candidates)
1731        })
1732    }
1733
1734    /// Construct the decision tree for `candidates`. Don't call this, call `match_candidates`
1735    /// instead to reserve sufficient stack space.
1736    fn match_candidates_inner(
1737        &mut self,
1738        span: Span,
1739        scrutinee_span: Span,
1740        mut start_block: BasicBlock,
1741        candidates: &mut [&mut Candidate<'tcx>],
1742    ) -> BasicBlock {
1743        if let [first, ..] = candidates {
1744            if first.false_edge_start_block.is_none() {
1745                first.false_edge_start_block = Some(start_block);
1746            }
1747        }
1748
1749        // Process a prefix of the candidates.
1750        let rest = match candidates {
1751            [] => {
1752                // If there are no candidates that still need testing, we're done.
1753                return start_block;
1754            }
1755            [first, remaining @ ..] if first.match_pairs.is_empty() => {
1756                // The first candidate has satisfied all its match pairs.
1757                // We record the blocks that will be needed by match arm lowering,
1758                // and then continue with the remaining candidates.
1759                let remainder_start = self.select_matched_candidate(first, start_block);
1760                remainder_start.and(remaining)
1761            }
1762            candidates if candidates.iter().any(|candidate| candidate.starts_with_or_pattern()) => {
1763                // If any candidate starts with an or-pattern, we want to expand or-patterns
1764                // before we do any more tests.
1765                //
1766                // The only candidate we strictly _need_ to expand here is the first one.
1767                // But by expanding other candidates as early as possible, we unlock more
1768                // opportunities to include them in test outcomes, making the match tree
1769                // smaller and simpler.
1770                self.expand_and_match_or_candidates(span, scrutinee_span, start_block, candidates)
1771            }
1772            candidates => {
1773                // The first candidate has some unsatisfied match pairs; we proceed to do more tests.
1774                self.test_candidates(span, scrutinee_span, candidates, start_block)
1775            }
1776        };
1777
1778        // Process any candidates that remain.
1779        let remaining_candidates = unpack!(start_block = rest);
1780        self.match_candidates(span, scrutinee_span, start_block, remaining_candidates)
1781    }
1782
1783    /// Link up matched candidates.
1784    ///
1785    /// For example, if we have something like this:
1786    ///
1787    /// ```ignore (illustrative)
1788    /// ...
1789    /// Some(x) if cond1 => ...
1790    /// Some(x) => ...
1791    /// Some(x) if cond2 => ...
1792    /// ...
1793    /// ```
1794    ///
1795    /// We generate real edges from:
1796    ///
1797    /// * `start_block` to the [pre-binding block] of the first pattern,
1798    /// * the [otherwise block] of the first pattern to the second pattern,
1799    /// * the [otherwise block] of the third pattern to a block with an
1800    ///   [`Unreachable` terminator](TerminatorKind::Unreachable).
1801    ///
1802    /// In addition, we later add fake edges from the otherwise blocks to the
1803    /// pre-binding block of the next candidate in the original set of
1804    /// candidates.
1805    ///
1806    /// [pre-binding block]: Candidate::pre_binding_block
1807    /// [otherwise block]: Candidate::otherwise_block
1808    fn select_matched_candidate(
1809        &mut self,
1810        candidate: &mut Candidate<'tcx>,
1811        start_block: BasicBlock,
1812    ) -> BasicBlock {
1813        assert!(candidate.otherwise_block.is_none());
1814        assert!(candidate.pre_binding_block.is_none());
1815        assert!(candidate.subcandidates.is_empty());
1816
1817        candidate.pre_binding_block = Some(start_block);
1818        let otherwise_block = self.cfg.start_new_block();
1819        // Create the otherwise block for this candidate, which is the
1820        // pre-binding block for the next candidate.
1821        candidate.otherwise_block = Some(otherwise_block);
1822        otherwise_block
1823    }
1824
1825    /// Takes a list of candidates such that some of the candidates' first match pairs are
1826    /// or-patterns. This expands as many or-patterns as possible and processes the resulting
1827    /// candidates. Returns the unprocessed candidates if any.
1828    fn expand_and_match_or_candidates<'b, 'c>(
1829        &mut self,
1830        span: Span,
1831        scrutinee_span: Span,
1832        start_block: BasicBlock,
1833        candidates: &'b mut [&'c mut Candidate<'tcx>],
1834    ) -> BlockAnd<&'b mut [&'c mut Candidate<'tcx>]> {
1835        // We can't expand or-patterns freely. The rule is:
1836        // - If a candidate doesn't start with an or-pattern, we include it in
1837        //   the expansion list as-is (i.e. it "expands" to itself).
1838        // - If a candidate has an or-pattern as its only remaining match pair,
1839        //   we can expand it.
1840        // - If it starts with an or-pattern but also has other match pairs,
1841        //   we can expand it, but we can't process more candidates after it.
1842        //
1843        // If we didn't stop, the `otherwise` cases could get mixed up. E.g. in the
1844        // following, or-pattern simplification (in `merge_trivial_subcandidates`) makes it
1845        // so the `1` and `2` cases branch to a same block (which then tests `false`). If we
1846        // took `(2, _)` in the same set of candidates, when we reach the block that tests
1847        // `false` we don't know whether we came from `1` or `2`, hence we can't know where
1848        // to branch on failure.
1849        //
1850        // ```ignore(illustrative)
1851        // match (1, true) {
1852        //     (1 | 2, false) => {},
1853        //     (2, _) => {},
1854        //     _ => {}
1855        // }
1856        // ```
1857        //
1858        // We therefore split the `candidates` slice in two, expand or-patterns in the first part,
1859        // and process the rest separately.
1860        let expand_until = candidates
1861            .iter()
1862            .position(|candidate| {
1863                // If a candidate starts with an or-pattern and has more match pairs,
1864                // we can expand it, but we must stop expanding _after_ it.
1865                candidate.match_pairs.len() > 1 && candidate.starts_with_or_pattern()
1866            })
1867            .map(|pos| pos + 1) // Stop _after_ the found candidate
1868            .unwrap_or(candidates.len()); // Otherwise, include all candidates
1869        let (candidates_to_expand, remaining_candidates) = candidates.split_at_mut(expand_until);
1870
1871        // Expand one level of or-patterns for each candidate in `candidates_to_expand`.
1872        // We take care to preserve the relative ordering of candidates, so that
1873        // or-patterns are expanded in their parent's relative position.
1874        let mut expanded_candidates = Vec::new();
1875        for candidate in candidates_to_expand.iter_mut() {
1876            if candidate.starts_with_or_pattern() {
1877                let or_match_pair = candidate.match_pairs.remove(0);
1878                // Expand the or-pattern into subcandidates.
1879                self.create_or_subcandidates(candidate, or_match_pair);
1880                // Collect the newly created subcandidates.
1881                for subcandidate in candidate.subcandidates.iter_mut() {
1882                    expanded_candidates.push(subcandidate);
1883                }
1884                // Note that the subcandidates have been added to `expanded_candidates`,
1885                // but `candidate` itself has not. If the last candidate has more match pairs,
1886                // they are handled separately by `test_remaining_match_pairs_after_or`.
1887            } else {
1888                // A candidate that doesn't start with an or-pattern has nothing to
1889                // expand, so it is included in the post-expansion list as-is.
1890                expanded_candidates.push(candidate);
1891            }
1892        }
1893
1894        // Recursively lower the part of the match tree represented by the
1895        // expanded candidates. This is where subcandidates actually get lowered!
1896        let remainder_start = self.match_candidates(
1897            span,
1898            scrutinee_span,
1899            start_block,
1900            expanded_candidates.as_mut_slice(),
1901        );
1902
1903        // Postprocess subcandidates, and process any leftover match pairs.
1904        // (Only the last candidate can possibly have more match pairs.)
1905        debug_assert!({
1906            let mut all_except_last = candidates_to_expand.iter().rev().skip(1);
1907            all_except_last.all(|candidate| candidate.match_pairs.is_empty())
1908        });
1909        for candidate in candidates_to_expand.iter_mut() {
1910            if !candidate.subcandidates.is_empty() {
1911                self.merge_trivial_subcandidates(candidate);
1912                self.remove_never_subcandidates(candidate);
1913            }
1914        }
1915        // It's important to perform the above simplifications _before_ dealing
1916        // with remaining match pairs, to avoid exponential blowup if possible
1917        // (for trivial or-patterns), and avoid useless work (for never patterns).
1918        if let Some(last_candidate) = candidates_to_expand.last_mut() {
1919            self.test_remaining_match_pairs_after_or(span, scrutinee_span, last_candidate);
1920        }
1921
1922        remainder_start.and(remaining_candidates)
1923    }
1924
1925    /// Given a match-pair that corresponds to an or-pattern, expand each subpattern into a new
1926    /// subcandidate. Any candidate that has been expanded this way should also be postprocessed
1927    /// at the end of [`Self::expand_and_match_or_candidates`].
1928    fn create_or_subcandidates(
1929        &mut self,
1930        candidate: &mut Candidate<'tcx>,
1931        match_pair: MatchPairTree<'tcx>,
1932    ) {
1933        let TestCase::Or { pats } = match_pair.test_case else { bug!() };
1934        debug!("expanding or-pattern: candidate={:#?}\npats={:#?}", candidate, pats);
1935        candidate.or_span = Some(match_pair.pattern_span);
1936        candidate.subcandidates = pats
1937            .into_iter()
1938            .map(|flat_pat| Candidate::from_flat_pat(flat_pat, candidate.has_guard))
1939            .collect();
1940        candidate.subcandidates[0].false_edge_start_block = candidate.false_edge_start_block;
1941    }
1942
1943    /// Try to merge all of the subcandidates of the given candidate into one. This avoids
1944    /// exponentially large CFGs in cases like `(1 | 2, 3 | 4, ...)`. The candidate should have been
1945    /// expanded with `create_or_subcandidates`.
1946    ///
1947    /// Given a pattern `(P | Q, R | S)` we (in principle) generate a CFG like
1948    /// so:
1949    ///
1950    /// ```text
1951    /// [ start ]
1952    ///      |
1953    /// [ match P, Q ]
1954    ///      |
1955    ///      +----------------------------------------+------------------------------------+
1956    ///      |                                        |                                    |
1957    ///      V                                        V                                    V
1958    /// [ P matches ]                           [ Q matches ]                        [ otherwise ]
1959    ///      |                                        |                                    |
1960    ///      V                                        V                                    |
1961    /// [ match R, S ]                          [ match R, S ]                             |
1962    ///      |                                        |                                    |
1963    ///      +--------------+------------+            +--------------+------------+        |
1964    ///      |              |            |            |              |            |        |
1965    ///      V              V            V            V              V            V        |
1966    /// [ R matches ] [ S matches ] [otherwise ] [ R matches ] [ S matches ] [otherwise ]  |
1967    ///      |              |            |            |              |            |        |
1968    ///      +--------------+------------|------------+--------------+            |        |
1969    ///      |                           |                                        |        |
1970    ///      |                           +----------------------------------------+--------+
1971    ///      |                           |
1972    ///      V                           V
1973    /// [ Success ]                 [ Failure ]
1974    /// ```
1975    ///
1976    /// In practice there are some complications:
1977    ///
1978    /// * If there's a guard, then the otherwise branch of the first match on
1979    ///   `R | S` goes to a test for whether `Q` matches, and the control flow
1980    ///   doesn't merge into a single success block until after the guard is
1981    ///   tested.
1982    /// * If neither `P` or `Q` has any bindings or type ascriptions and there
1983    ///   isn't a match guard, then we create a smaller CFG like:
1984    ///
1985    /// ```text
1986    ///     ...
1987    ///      +---------------+------------+
1988    ///      |               |            |
1989    /// [ P matches ] [ Q matches ] [ otherwise ]
1990    ///      |               |            |
1991    ///      +---------------+            |
1992    ///      |                           ...
1993    /// [ match R, S ]
1994    ///      |
1995    ///     ...
1996    /// ```
1997    ///
1998    /// Note that this takes place _after_ the subcandidates have participated
1999    /// in match tree lowering.
2000    fn merge_trivial_subcandidates(&mut self, candidate: &mut Candidate<'tcx>) {
2001        assert!(!candidate.subcandidates.is_empty());
2002        if candidate.has_guard {
2003            // FIXME(or_patterns; matthewjasper) Don't give up if we have a guard.
2004            return;
2005        }
2006
2007        // FIXME(or_patterns; matthewjasper) Try to be more aggressive here.
2008        let can_merge = candidate.subcandidates.iter().all(|subcandidate| {
2009            subcandidate.subcandidates.is_empty() && subcandidate.extra_data.is_empty()
2010        });
2011        if !can_merge {
2012            return;
2013        }
2014
2015        let mut last_otherwise = None;
2016        let shared_pre_binding_block = self.cfg.start_new_block();
2017        // This candidate is about to become a leaf, so unset `or_span`.
2018        let or_span = candidate.or_span.take().unwrap();
2019        let source_info = self.source_info(or_span);
2020
2021        if candidate.false_edge_start_block.is_none() {
2022            candidate.false_edge_start_block = candidate.subcandidates[0].false_edge_start_block;
2023        }
2024
2025        // Remove the (known-trivial) subcandidates from the candidate tree,
2026        // so that they aren't visible after match tree lowering, and wire them
2027        // all to join up at a single shared pre-binding block.
2028        // (Note that the subcandidates have already had their part of the match
2029        // tree lowered by this point, which is why we can add a goto to them.)
2030        for subcandidate in mem::take(&mut candidate.subcandidates) {
2031            let subcandidate_block = subcandidate.pre_binding_block.unwrap();
2032            self.cfg.goto(subcandidate_block, source_info, shared_pre_binding_block);
2033            last_otherwise = subcandidate.otherwise_block;
2034        }
2035        candidate.pre_binding_block = Some(shared_pre_binding_block);
2036        assert!(last_otherwise.is_some());
2037        candidate.otherwise_block = last_otherwise;
2038    }
2039
2040    /// Never subcandidates may have a set of bindings inconsistent with their siblings,
2041    /// which would break later code. So we filter them out. Note that we can't filter out
2042    /// top-level candidates this way.
2043    fn remove_never_subcandidates(&mut self, candidate: &mut Candidate<'tcx>) {
2044        if candidate.subcandidates.is_empty() {
2045            return;
2046        }
2047
2048        let false_edge_start_block = candidate.subcandidates[0].false_edge_start_block;
2049        candidate.subcandidates.retain_mut(|candidate| {
2050            if candidate.extra_data.is_never {
2051                candidate.visit_leaves(|subcandidate| {
2052                    let block = subcandidate.pre_binding_block.unwrap();
2053                    // That block is already unreachable but needs a terminator to make the MIR well-formed.
2054                    let source_info = self.source_info(subcandidate.extra_data.span);
2055                    self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
2056                });
2057                false
2058            } else {
2059                true
2060            }
2061        });
2062        if candidate.subcandidates.is_empty() {
2063            // If `candidate` has become a leaf candidate, ensure it has a `pre_binding_block` and `otherwise_block`.
2064            let next_block = self.cfg.start_new_block();
2065            candidate.pre_binding_block = Some(next_block);
2066            candidate.otherwise_block = Some(next_block);
2067            // In addition, if `candidate` doesn't have `false_edge_start_block`, it should be assigned here.
2068            if candidate.false_edge_start_block.is_none() {
2069                candidate.false_edge_start_block = false_edge_start_block;
2070            }
2071        }
2072    }
2073
2074    /// If more match pairs remain, test them after each subcandidate.
2075    /// We could have added them to the or-candidates during or-pattern expansion, but that
2076    /// would make it impossible to detect simplifiable or-patterns. That would guarantee
2077    /// exponentially large CFGs for cases like `(1 | 2, 3 | 4, ...)`.
2078    fn test_remaining_match_pairs_after_or(
2079        &mut self,
2080        span: Span,
2081        scrutinee_span: Span,
2082        candidate: &mut Candidate<'tcx>,
2083    ) {
2084        if candidate.match_pairs.is_empty() {
2085            return;
2086        }
2087
2088        let or_span = candidate.or_span.unwrap_or(candidate.extra_data.span);
2089        let source_info = self.source_info(or_span);
2090        let mut last_otherwise = None;
2091        candidate.visit_leaves(|leaf_candidate| {
2092            last_otherwise = leaf_candidate.otherwise_block;
2093        });
2094
2095        let remaining_match_pairs = mem::take(&mut candidate.match_pairs);
2096        // We're testing match pairs that remained after an `Or`, so the remaining
2097        // pairs should all be `Or` too, due to the sorting invariant.
2098        debug_assert!(
2099            remaining_match_pairs
2100                .iter()
2101                .all(|match_pair| matches!(match_pair.test_case, TestCase::Or { .. }))
2102        );
2103
2104        // Visit each leaf candidate within this subtree, add a copy of the remaining
2105        // match pairs to it, and then recursively lower the rest of the match tree
2106        // from that point.
2107        candidate.visit_leaves(|leaf_candidate| {
2108            // At this point the leaf's own match pairs have all been lowered
2109            // and removed, so `extend` and assignment are equivalent,
2110            // but extending can also recycle any existing vector capacity.
2111            assert!(leaf_candidate.match_pairs.is_empty());
2112            leaf_candidate.match_pairs.extend(remaining_match_pairs.iter().cloned());
2113
2114            let or_start = leaf_candidate.pre_binding_block.unwrap();
2115            let otherwise =
2116                self.match_candidates(span, scrutinee_span, or_start, &mut [leaf_candidate]);
2117            // In a case like `(P | Q, R | S)`, if `P` succeeds and `R | S` fails, we know `(Q,
2118            // R | S)` will fail too. If there is no guard, we skip testing of `Q` by branching
2119            // directly to `last_otherwise`. If there is a guard,
2120            // `leaf_candidate.otherwise_block` can be reached by guard failure as well, so we
2121            // can't skip `Q`.
2122            let or_otherwise = if leaf_candidate.has_guard {
2123                leaf_candidate.otherwise_block.unwrap()
2124            } else {
2125                last_otherwise.unwrap()
2126            };
2127            self.cfg.goto(otherwise, source_info, or_otherwise);
2128        });
2129    }
2130
2131    /// Pick a test to run. Which test doesn't matter as long as it is guaranteed to fully match at
2132    /// least one match pair. We currently simply pick the test corresponding to the first match
2133    /// pair of the first candidate in the list.
2134    ///
2135    /// *Note:* taking the first match pair is somewhat arbitrary, and we might do better here by
2136    /// choosing more carefully what to test.
2137    ///
2138    /// For example, consider the following possible match-pairs:
2139    ///
2140    /// 1. `x @ Some(P)` -- we will do a [`Switch`] to decide what variant `x` has
2141    /// 2. `x @ 22` -- we will do a [`SwitchInt`] to decide what value `x` has
2142    /// 3. `x @ 3..5` -- we will do a [`Range`] test to decide what range `x` falls in
2143    /// 4. etc.
2144    ///
2145    /// [`Switch`]: TestKind::Switch
2146    /// [`SwitchInt`]: TestKind::SwitchInt
2147    /// [`Range`]: TestKind::Range
2148    fn pick_test(&mut self, candidates: &[&mut Candidate<'tcx>]) -> (Place<'tcx>, Test<'tcx>) {
2149        // Extract the match-pair from the highest priority candidate
2150        let match_pair = &candidates[0].match_pairs[0];
2151        let test = self.pick_test_for_match_pair(match_pair);
2152        // Unwrap is ok after simplification.
2153        let match_place = match_pair.place.unwrap();
2154        debug!(?test, ?match_pair);
2155
2156        (match_place, test)
2157    }
2158
2159    /// Given a test, we partition the input candidates into several buckets.
2160    /// If a candidate matches in exactly one of the branches of `test`
2161    /// (and no other branches), we put it into the corresponding bucket.
2162    /// If it could match in more than one of the branches of `test`, the test
2163    /// doesn't usefully apply to it, and we stop partitioning candidates.
2164    ///
2165    /// Importantly, we also **mutate** the branched candidates to remove match pairs
2166    /// that are entailed by the outcome of the test, and add any sub-pairs of the
2167    /// removed pairs.
2168    ///
2169    /// This returns a pair of
2170    /// - the candidates that weren't sorted;
2171    /// - for each possible outcome of the test, the candidates that match in that outcome.
2172    ///
2173    /// For example:
2174    /// ```
2175    /// # let (x, y, z) = (true, true, true);
2176    /// match (x, y, z) {
2177    ///     (true , _    , true ) => true,  // (0)
2178    ///     (false, false, _    ) => false, // (1)
2179    ///     (_    , true , _    ) => true,  // (2)
2180    ///     (true , _    , false) => false, // (3)
2181    /// }
2182    /// # ;
2183    /// ```
2184    ///
2185    /// Assume we are testing on `x`. Conceptually, there are 2 overlapping candidate sets:
2186    /// - If the outcome is that `x` is true, candidates {0, 2, 3} are possible
2187    /// - If the outcome is that `x` is false, candidates {1, 2} are possible
2188    ///
2189    /// Following our algorithm:
2190    /// - Candidate 0 is sorted into outcome `x == true`
2191    /// - Candidate 1 is sorted into outcome `x == false`
2192    /// - Candidate 2 remains unsorted, because testing `x` has no effect on it
2193    /// - Candidate 3 remains unsorted, because a previous candidate (2) was unsorted
2194    ///   - This helps preserve the illusion that candidates are tested "in order"
2195    ///
2196    /// The sorted candidates are mutated to remove entailed match pairs:
2197    /// - candidate 0 becomes `[z @ true]` since we know that `x` was `true`;
2198    /// - candidate 1 becomes `[y @ false]` since we know that `x` was `false`.
2199    fn sort_candidates<'b, 'c>(
2200        &mut self,
2201        match_place: Place<'tcx>,
2202        test: &Test<'tcx>,
2203        mut candidates: &'b mut [&'c mut Candidate<'tcx>],
2204    ) -> (
2205        &'b mut [&'c mut Candidate<'tcx>],
2206        FxIndexMap<TestBranch<'tcx>, Vec<&'b mut Candidate<'tcx>>>,
2207    ) {
2208        // For each of the possible outcomes, collect vector of candidates that apply if the test
2209        // has that particular outcome.
2210        let mut target_candidates: FxIndexMap<_, Vec<&mut Candidate<'_>>> = Default::default();
2211
2212        let total_candidate_count = candidates.len();
2213
2214        // Sort the candidates into the appropriate vector in `target_candidates`. Note that at some
2215        // point we may encounter a candidate where the test is not relevant; at that point, we stop
2216        // sorting.
2217        while let Some(candidate) = candidates.first_mut() {
2218            let Some(branch) =
2219                self.sort_candidate(match_place, test, candidate, &target_candidates)
2220            else {
2221                break;
2222            };
2223            let (candidate, rest) = candidates.split_first_mut().unwrap();
2224            target_candidates.entry(branch).or_insert_with(Vec::new).push(candidate);
2225            candidates = rest;
2226        }
2227
2228        // At least the first candidate ought to be tested
2229        assert!(
2230            total_candidate_count > candidates.len(),
2231            "{total_candidate_count}, {candidates:#?}"
2232        );
2233        debug!("tested_candidates: {}", total_candidate_count - candidates.len());
2234        debug!("untested_candidates: {}", candidates.len());
2235
2236        (candidates, target_candidates)
2237    }
2238
2239    /// This is the most subtle part of the match lowering algorithm. At this point, there are
2240    /// no fully-satisfied candidates, and no or-patterns to expand, so we actually need to
2241    /// perform some sort of test to make progress.
2242    ///
2243    /// Once we pick what sort of test we are going to perform, this test will help us winnow down
2244    /// our candidates. So we walk over the candidates (from high to low priority) and check. We
2245    /// compute, for each outcome of the test, a list of (modified) candidates. If a candidate
2246    /// matches in exactly one branch of our test, we add it to the corresponding outcome. We also
2247    /// **mutate its list of match pairs** if appropriate, to reflect the fact that we know which
2248    /// outcome occurred.
2249    ///
2250    /// For example, if we are testing `x.0`'s variant, and we have a candidate `(x.0 @ Some(v), x.1
2251    /// @ 22)`, then we would have a resulting candidate of `((x.0 as Some).0 @ v, x.1 @ 22)` in the
2252    /// branch corresponding to `Some`. To ensure we make progress, we always pick a test that
2253    /// results in simplifying the first candidate.
2254    ///
2255    /// But there may also be candidates that the test doesn't
2256    /// apply to. The classical example is wildcards:
2257    ///
2258    /// ```
2259    /// # let (x, y, z) = (true, true, true);
2260    /// match (x, y, z) {
2261    ///     (true , _    , true ) => true,  // (0)
2262    ///     (false, false, _    ) => false, // (1)
2263    ///     (_    , true , _    ) => true,  // (2)
2264    ///     (true , _    , false) => false, // (3)
2265    /// }
2266    /// # ;
2267    /// ```
2268    ///
2269    /// Here, the traditional "decision tree" method would generate 2 separate code-paths for the 2
2270    /// possible values of `x`. This would however duplicate some candidates, which would need to be
2271    /// lowered several times.
2272    ///
2273    /// In some cases, this duplication can create an exponential amount of
2274    /// code. This is most easily seen by noticing that this method terminates
2275    /// with precisely the reachable arms being reachable - but that problem
2276    /// is trivially NP-complete:
2277    ///
2278    /// ```ignore (illustrative)
2279    /// match (var0, var1, var2, var3, ...) {
2280    ///     (true , _   , _    , false, true, ...) => false,
2281    ///     (_    , true, true , false, _   , ...) => false,
2282    ///     (false, _   , false, false, _   , ...) => false,
2283    ///     ...
2284    ///     _ => true
2285    /// }
2286    /// ```
2287    ///
2288    /// Here the last arm is reachable only if there is an assignment to
2289    /// the variables that does not match any of the literals. Therefore,
2290    /// compilation would take an exponential amount of time in some cases.
2291    ///
2292    /// In rustc, we opt instead for the "backtracking automaton" approach. This guarantees we never
2293    /// duplicate a candidate (except in the presence of or-patterns). In fact this guarantee is
2294    /// ensured by the fact that we carry around `&mut Candidate`s which can't be duplicated.
2295    ///
2296    /// To make this work, whenever we decide to perform a test, if we encounter a candidate that
2297    /// could match in more than one branch of the test, we stop. We generate code for the test and
2298    /// for the candidates in its branches; the remaining candidates will be tested if the
2299    /// candidates in the branches fail to match.
2300    ///
2301    /// For example, if we test on `x` in the following:
2302    /// ```
2303    /// # fn foo((x, y, z): (bool, bool, bool)) -> u32 {
2304    /// match (x, y, z) {
2305    ///     (true , _    , true ) => 0,
2306    ///     (false, false, _    ) => 1,
2307    ///     (_    , true , _    ) => 2,
2308    ///     (true , _    , false) => 3,
2309    /// }
2310    /// # }
2311    /// ```
2312    /// this function generates code that looks more of less like:
2313    /// ```
2314    /// # fn foo((x, y, z): (bool, bool, bool)) -> u32 {
2315    /// if x {
2316    ///     match (y, z) {
2317    ///         (_, true) => return 0,
2318    ///         _ => {} // continue matching
2319    ///     }
2320    /// } else {
2321    ///     match (y, z) {
2322    ///         (false, _) => return 1,
2323    ///         _ => {} // continue matching
2324    ///     }
2325    /// }
2326    /// // the block here is `remainder_start`
2327    /// match (x, y, z) {
2328    ///     (_    , true , _    ) => 2,
2329    ///     (true , _    , false) => 3,
2330    ///     _ => unreachable!(),
2331    /// }
2332    /// # }
2333    /// ```
2334    ///
2335    /// We return the unprocessed candidates.
2336    fn test_candidates<'b, 'c>(
2337        &mut self,
2338        span: Span,
2339        scrutinee_span: Span,
2340        candidates: &'b mut [&'c mut Candidate<'tcx>],
2341        start_block: BasicBlock,
2342    ) -> BlockAnd<&'b mut [&'c mut Candidate<'tcx>]> {
2343        // Choose a match pair from the first candidate, and use it to determine a
2344        // test to perform that will confirm or refute that match pair.
2345        let (match_place, test) = self.pick_test(candidates);
2346
2347        // For each of the N possible test outcomes, build the vector of candidates that applies if
2348        // the test has that particular outcome. This also mutates the candidates to remove match
2349        // pairs that are fully satisfied by the relevant outcome.
2350        let (remaining_candidates, target_candidates) =
2351            self.sort_candidates(match_place, &test, candidates);
2352
2353        // The block that we should branch to if none of the `target_candidates` match.
2354        let remainder_start = self.cfg.start_new_block();
2355
2356        // For each outcome of the test, recursively lower the rest of the match tree
2357        // from that point. (Note that we haven't lowered the actual test yet!)
2358        let target_blocks: FxIndexMap<_, _> = target_candidates
2359            .into_iter()
2360            .map(|(branch, mut candidates)| {
2361                let branch_start = self.cfg.start_new_block();
2362                // Recursively lower the rest of the match tree after the relevant outcome.
2363                let branch_otherwise =
2364                    self.match_candidates(span, scrutinee_span, branch_start, &mut *candidates);
2365
2366                // Link up the `otherwise` block of the subtree to `remainder_start`.
2367                let source_info = self.source_info(span);
2368                self.cfg.goto(branch_otherwise, source_info, remainder_start);
2369                (branch, branch_start)
2370            })
2371            .collect();
2372
2373        // Perform the chosen test, branching to one of the N subtrees prepared above
2374        // (or to `remainder_start` if no outcome was satisfied).
2375        self.perform_test(
2376            span,
2377            scrutinee_span,
2378            start_block,
2379            remainder_start,
2380            match_place,
2381            &test,
2382            target_blocks,
2383        );
2384
2385        remainder_start.and(remaining_candidates)
2386    }
2387}
2388
2389///////////////////////////////////////////////////////////////////////////
2390// Pat binding - used for `let` and function parameters as well.
2391
2392impl<'a, 'tcx> Builder<'a, 'tcx> {
2393    /// Lowers a `let` expression that appears in a suitable context
2394    /// (e.g. an `if` condition or match guard).
2395    ///
2396    /// Also used for lowering let-else statements, since they have similar
2397    /// needs despite not actually using `let` expressions.
2398    ///
2399    /// Use [`DeclareLetBindings`] to control whether the `let` bindings are
2400    /// declared or not.
2401    pub(crate) fn lower_let_expr(
2402        &mut self,
2403        mut block: BasicBlock,
2404        expr_id: ExprId,
2405        pat: &Pat<'tcx>,
2406        source_scope: Option<SourceScope>,
2407        scope_span: Span,
2408        declare_let_bindings: DeclareLetBindings,
2409    ) -> BlockAnd<()> {
2410        let expr_span = self.thir[expr_id].span;
2411        let scrutinee = unpack!(block = self.lower_scrutinee(block, expr_id, expr_span));
2412        let built_tree = self.lower_match_tree(
2413            block,
2414            expr_span,
2415            &scrutinee,
2416            pat.span,
2417            vec![(pat, HasMatchGuard::No)],
2418            true,
2419        );
2420        let [branch] = built_tree.branches.try_into().unwrap();
2421
2422        self.break_for_else(built_tree.otherwise_block, self.source_info(expr_span));
2423
2424        match declare_let_bindings {
2425            DeclareLetBindings::Yes => {
2426                let expr_place = scrutinee.try_to_place(self);
2427                let opt_expr_place = expr_place.as_ref().map(|place| (Some(place), expr_span));
2428                self.declare_bindings(
2429                    source_scope,
2430                    pat.span.to(scope_span),
2431                    pat,
2432                    None,
2433                    opt_expr_place,
2434                );
2435            }
2436            DeclareLetBindings::No => {} // Caller is responsible for bindings.
2437            DeclareLetBindings::LetNotPermitted => {
2438                self.tcx.dcx().span_bug(expr_span, "let expression not expected in this context")
2439            }
2440        }
2441
2442        let success = self.bind_pattern(self.source_info(pat.span), branch, &[], expr_span, None);
2443
2444        // If branch coverage is enabled, record this branch.
2445        self.visit_coverage_conditional_let(pat, success, built_tree.otherwise_block);
2446
2447        success.unit()
2448    }
2449
2450    /// Initializes each of the bindings from the candidate by
2451    /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
2452    /// any, and then branches to the arm. Returns the block for the case where
2453    /// the guard succeeds.
2454    ///
2455    /// Note: we do not check earlier that if there is a guard,
2456    /// there cannot be move bindings. We avoid a use-after-move by only
2457    /// moving the binding once the guard has evaluated to true (see below).
2458    fn bind_and_guard_matched_candidate(
2459        &mut self,
2460        sub_branch: MatchTreeSubBranch<'tcx>,
2461        fake_borrows: &[(Place<'tcx>, Local, FakeBorrowKind)],
2462        scrutinee_span: Span,
2463        arm_match_scope: Option<(&Arm<'tcx>, region::Scope)>,
2464        schedule_drops: ScheduleDrops,
2465    ) -> BasicBlock {
2466        debug!("bind_and_guard_matched_candidate(subbranch={:?})", sub_branch);
2467
2468        let block = sub_branch.success_block;
2469
2470        if sub_branch.is_never {
2471            // This arm has a dummy body, we don't need to generate code for it. `block` is already
2472            // unreachable (except via false edge).
2473            let source_info = self.source_info(sub_branch.span);
2474            self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
2475            return self.cfg.start_new_block();
2476        }
2477
2478        self.ascribe_types(block, sub_branch.ascriptions);
2479
2480        // Lower an instance of the arm guard (if present) for this candidate,
2481        // and then perform bindings for the arm body.
2482        if let Some((arm, match_scope)) = arm_match_scope
2483            && let Some(guard) = arm.guard
2484        {
2485            let tcx = self.tcx;
2486
2487            // Bindings for guards require some extra handling to automatically
2488            // insert implicit references/dereferences.
2489            // This always schedules storage drops, so we may need to unschedule them below.
2490            self.bind_matched_candidate_for_guard(block, sub_branch.bindings.iter());
2491            let guard_frame = GuardFrame {
2492                locals: sub_branch
2493                    .bindings
2494                    .iter()
2495                    .map(|b| GuardFrameLocal::new(b.var_id))
2496                    .collect(),
2497            };
2498            debug!("entering guard building context: {:?}", guard_frame);
2499            self.guard_context.push(guard_frame);
2500
2501            let re_erased = tcx.lifetimes.re_erased;
2502            let scrutinee_source_info = self.source_info(scrutinee_span);
2503            for &(place, temp, kind) in fake_borrows {
2504                let borrow = Rvalue::Ref(re_erased, BorrowKind::Fake(kind), place);
2505                self.cfg.push_assign(block, scrutinee_source_info, Place::from(temp), borrow);
2506            }
2507
2508            let mut guard_span = rustc_span::DUMMY_SP;
2509
2510            let (post_guard_block, otherwise_post_guard_block) =
2511                self.in_if_then_scope(match_scope, guard_span, |this| {
2512                    guard_span = this.thir[guard].span;
2513                    this.then_else_break(
2514                        block,
2515                        guard,
2516                        None, // Use `self.local_scope()` as the temp scope
2517                        this.source_info(arm.span),
2518                        DeclareLetBindings::No, // For guards, `let` bindings are declared separately
2519                    )
2520                });
2521
2522            // If this isn't the final sub-branch being lowered, we need to unschedule drops of
2523            // bindings and temporaries created for and by the guard. As a result, the drop order
2524            // for the arm will correspond to the binding order of the final sub-branch lowered.
2525            if matches!(schedule_drops, ScheduleDrops::No) {
2526                self.clear_match_arm_and_guard_scopes(arm.scope);
2527            }
2528
2529            let source_info = self.source_info(guard_span);
2530            let guard_end = self.source_info(tcx.sess.source_map().end_point(guard_span));
2531            let guard_frame = self.guard_context.pop().unwrap();
2532            debug!("Exiting guard building context with locals: {:?}", guard_frame);
2533
2534            for &(_, temp, _) in fake_borrows {
2535                let cause = FakeReadCause::ForMatchGuard;
2536                self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
2537            }
2538
2539            self.cfg.goto(otherwise_post_guard_block, source_info, sub_branch.otherwise_block);
2540
2541            // We want to ensure that the matched candidates are bound
2542            // after we have confirmed this candidate *and* any
2543            // associated guard; Binding them on `block` is too soon,
2544            // because that would be before we've checked the result
2545            // from the guard.
2546            //
2547            // But binding them on the arm is *too late*, because
2548            // then all of the candidates for a single arm would be
2549            // bound in the same place, that would cause a case like:
2550            //
2551            // ```rust
2552            // match (30, 2) {
2553            //     (mut x, 1) | (2, mut x) if { true } => { ... }
2554            //     ...                                 // ^^^^^^^ (this is `arm_block`)
2555            // }
2556            // ```
2557            //
2558            // would yield an `arm_block` something like:
2559            //
2560            // ```
2561            // StorageLive(_4);        // _4 is `x`
2562            // _4 = &mut (_1.0: i32);  // this is handling `(mut x, 1)` case
2563            // _4 = &mut (_1.1: i32);  // this is handling `(2, mut x)` case
2564            // ```
2565            //
2566            // and that is clearly not correct.
2567            let by_value_bindings = sub_branch
2568                .bindings
2569                .iter()
2570                .filter(|binding| matches!(binding.binding_mode.0, ByRef::No));
2571            // Read all of the by reference bindings to ensure that the
2572            // place they refer to can't be modified by the guard.
2573            for binding in by_value_bindings.clone() {
2574                let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
2575                let cause = FakeReadCause::ForGuardBinding;
2576                self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
2577            }
2578            // Only schedule drops for the last sub-branch we lower.
2579            self.bind_matched_candidate_for_arm_body(
2580                post_guard_block,
2581                schedule_drops,
2582                by_value_bindings,
2583            );
2584
2585            post_guard_block
2586        } else {
2587            // (Here, it is not too early to bind the matched
2588            // candidate on `block`, because there is no guard result
2589            // that we have to inspect before we bind them.)
2590            self.bind_matched_candidate_for_arm_body(
2591                block,
2592                schedule_drops,
2593                sub_branch.bindings.iter(),
2594            );
2595            block
2596        }
2597    }
2598
2599    /// Append `AscribeUserType` statements onto the end of `block`
2600    /// for each ascription
2601    fn ascribe_types(
2602        &mut self,
2603        block: BasicBlock,
2604        ascriptions: impl IntoIterator<Item = Ascription<'tcx>>,
2605    ) {
2606        for ascription in ascriptions {
2607            let source_info = self.source_info(ascription.annotation.span);
2608
2609            let base = self.canonical_user_type_annotations.push(ascription.annotation);
2610            self.cfg.push(
2611                block,
2612                Statement::new(
2613                    source_info,
2614                    StatementKind::AscribeUserType(
2615                        Box::new((
2616                            ascription.source,
2617                            UserTypeProjection { base, projs: Vec::new() },
2618                        )),
2619                        ascription.variance,
2620                    ),
2621                ),
2622            );
2623        }
2624    }
2625
2626    /// Binding for guards is a bit different from binding for the arm body,
2627    /// because an extra layer of implicit reference/dereference is added.
2628    ///
2629    /// The idea is that any pattern bindings of type T will map to a `&T` within
2630    /// the context of the guard expression, but will continue to map to a `T`
2631    /// in the context of the arm body. To avoid surfacing this distinction in
2632    /// the user source code (which would be a severe change to the language and
2633    /// require far more revision to the compiler), any occurrence of the
2634    /// identifier in the guard expression will automatically get a deref op
2635    /// applied to it. (See the caller of [`Self::is_bound_var_in_guard`].)
2636    ///
2637    /// So an input like:
2638    ///
2639    /// ```ignore (illustrative)
2640    /// let place = Foo::new();
2641    /// match place { foo if inspect(foo)
2642    ///     => feed(foo), ... }
2643    /// ```
2644    ///
2645    /// will be treated as if it were really something like:
2646    ///
2647    /// ```ignore (illustrative)
2648    /// let place = Foo::new();
2649    /// match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
2650    ///     => { let tmp2 = place; feed(tmp2) }, ... }
2651    /// ```
2652    ///
2653    /// And an input like:
2654    ///
2655    /// ```ignore (illustrative)
2656    /// let place = Foo::new();
2657    /// match place { ref mut foo if inspect(foo)
2658    ///     => feed(foo), ... }
2659    /// ```
2660    ///
2661    /// will be treated as if it were really something like:
2662    ///
2663    /// ```ignore (illustrative)
2664    /// let place = Foo::new();
2665    /// match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
2666    ///     => { let tmp2 = &mut place; feed(tmp2) }, ... }
2667    /// ```
2668    /// ---
2669    ///
2670    /// ## Implementation notes
2671    ///
2672    /// To encode the distinction above, we must inject the
2673    /// temporaries `tmp1` and `tmp2`.
2674    ///
2675    /// There are two cases of interest: binding by-value, and binding by-ref.
2676    ///
2677    /// 1. Binding by-value: Things are simple.
2678    ///
2679    ///    * Establishing `tmp1` creates a reference into the
2680    ///      matched place. This code is emitted by
2681    ///      [`Self::bind_matched_candidate_for_guard`].
2682    ///
2683    ///    * `tmp2` is only initialized "lazily", after we have
2684    ///      checked the guard. Thus, the code that can trigger
2685    ///      moves out of the candidate can only fire after the
2686    ///      guard evaluated to true. This initialization code is
2687    ///      emitted by [`Self::bind_matched_candidate_for_arm_body`].
2688    ///
2689    /// 2. Binding by-reference: Things are tricky.
2690    ///
2691    ///    * Here, the guard expression wants a `&&` or `&&mut`
2692    ///      into the original input. This means we need to borrow
2693    ///      the reference that we create for the arm.
2694    ///    * So we eagerly create the reference for the arm and then take a
2695    ///      reference to that.
2696    ///
2697    /// ---
2698    ///
2699    /// See these PRs for some historical context:
2700    /// - <https://github.com/rust-lang/rust/pull/49870> (introduction of autoref)
2701    /// - <https://github.com/rust-lang/rust/pull/59114> (always use autoref)
2702    fn bind_matched_candidate_for_guard<'b>(
2703        &mut self,
2704        block: BasicBlock,
2705        bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
2706    ) where
2707        'tcx: 'b,
2708    {
2709        debug!("bind_matched_candidate_for_guard(block={:?})", block);
2710
2711        // Assign each of the bindings. Since we are binding for a
2712        // guard expression, this will never trigger moves out of the
2713        // candidate.
2714        let re_erased = self.tcx.lifetimes.re_erased;
2715        for binding in bindings {
2716            debug!("bind_matched_candidate_for_guard(binding={:?})", binding);
2717            let source_info = self.source_info(binding.span);
2718
2719            // For each pattern ident P of type T, `ref_for_guard` is
2720            // a reference R: &T pointing to the location matched by
2721            // the pattern, and every occurrence of P within a guard
2722            // denotes *R.
2723            // Drops must be scheduled to emit `StorageDead` on the guard's failure/break branches.
2724            let ref_for_guard = self.storage_live_binding(
2725                block,
2726                binding.var_id,
2727                binding.span,
2728                RefWithinGuard,
2729                ScheduleDrops::Yes,
2730            );
2731            match binding.binding_mode.0 {
2732                ByRef::No => {
2733                    // The arm binding will be by value, so for the guard binding
2734                    // just take a shared reference to the matched place.
2735                    let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source);
2736                    self.cfg.push_assign(block, source_info, ref_for_guard, rvalue);
2737                }
2738                ByRef::Yes(mutbl) => {
2739                    // The arm binding will be by reference, so eagerly create it now. Drops must
2740                    // be scheduled to emit `StorageDead` on the guard's failure/break branches.
2741                    let value_for_arm = self.storage_live_binding(
2742                        block,
2743                        binding.var_id,
2744                        binding.span,
2745                        OutsideGuard,
2746                        ScheduleDrops::Yes,
2747                    );
2748
2749                    let rvalue =
2750                        Rvalue::Ref(re_erased, util::ref_pat_borrow_kind(mutbl), binding.source);
2751                    self.cfg.push_assign(block, source_info, value_for_arm, rvalue);
2752                    // For the guard binding, take a shared reference to that reference.
2753                    let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
2754                    self.cfg.push_assign(block, source_info, ref_for_guard, rvalue);
2755                }
2756            }
2757        }
2758    }
2759
2760    fn bind_matched_candidate_for_arm_body<'b>(
2761        &mut self,
2762        block: BasicBlock,
2763        schedule_drops: ScheduleDrops,
2764        bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
2765    ) where
2766        'tcx: 'b,
2767    {
2768        debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
2769
2770        let re_erased = self.tcx.lifetimes.re_erased;
2771        // Assign each of the bindings. This may trigger moves out of the candidate.
2772        for binding in bindings {
2773            let source_info = self.source_info(binding.span);
2774            let local = self.storage_live_binding(
2775                block,
2776                binding.var_id,
2777                binding.span,
2778                OutsideGuard,
2779                schedule_drops,
2780            );
2781            if matches!(schedule_drops, ScheduleDrops::Yes) {
2782                self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
2783            }
2784            let rvalue = match binding.binding_mode.0 {
2785                ByRef::No => Rvalue::Use(self.consume_by_copy_or_move(binding.source)),
2786                ByRef::Yes(mutbl) => {
2787                    Rvalue::Ref(re_erased, util::ref_pat_borrow_kind(mutbl), binding.source)
2788                }
2789            };
2790            self.cfg.push_assign(block, source_info, local, rvalue);
2791        }
2792    }
2793
2794    /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
2795    /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
2796    /// first local is a binding for occurrences of `var` in the guard, which
2797    /// will have type `&T`. The second local is a binding for occurrences of
2798    /// `var` in the arm body, which will have type `T`.
2799    #[instrument(skip(self), level = "debug")]
2800    fn declare_binding(
2801        &mut self,
2802        source_info: SourceInfo,
2803        visibility_scope: SourceScope,
2804        name: Symbol,
2805        mode: BindingMode,
2806        var_id: LocalVarId,
2807        var_ty: Ty<'tcx>,
2808        user_ty: Option<Box<UserTypeProjections>>,
2809        has_guard: ArmHasGuard,
2810        opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
2811        pat_span: Span,
2812    ) {
2813        let tcx = self.tcx;
2814        let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
2815        let local = LocalDecl {
2816            mutability: mode.1,
2817            ty: var_ty,
2818            user_ty,
2819            source_info,
2820            local_info: ClearCrossCrate::Set(Box::new(LocalInfo::User(BindingForm::Var(
2821                VarBindingForm {
2822                    binding_mode: mode,
2823                    // hypothetically, `visit_primary_bindings` could try to unzip
2824                    // an outermost hir::Ty as we descend, matching up
2825                    // idents in pat; but complex w/ unclear UI payoff.
2826                    // Instead, just abandon providing diagnostic info.
2827                    opt_ty_info: None,
2828                    opt_match_place,
2829                    pat_span,
2830                },
2831            )))),
2832        };
2833        let for_arm_body = self.local_decls.push(local);
2834        if self.should_emit_debug_info_for_binding(name, var_id) {
2835            self.var_debug_info.push(VarDebugInfo {
2836                name,
2837                source_info: debug_source_info,
2838                value: VarDebugInfoContents::Place(for_arm_body.into()),
2839                composite: None,
2840                argument_index: None,
2841            });
2842        }
2843        let locals = if has_guard.0 {
2844            let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
2845                // This variable isn't mutated but has a name, so has to be
2846                // immutable to avoid the unused mut lint.
2847                mutability: Mutability::Not,
2848                ty: Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, var_ty),
2849                user_ty: None,
2850                source_info,
2851                local_info: ClearCrossCrate::Set(Box::new(LocalInfo::User(
2852                    BindingForm::RefForGuard,
2853                ))),
2854            });
2855            if self.should_emit_debug_info_for_binding(name, var_id) {
2856                self.var_debug_info.push(VarDebugInfo {
2857                    name,
2858                    source_info: debug_source_info,
2859                    value: VarDebugInfoContents::Place(ref_for_guard.into()),
2860                    composite: None,
2861                    argument_index: None,
2862                });
2863            }
2864            LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
2865        } else {
2866            LocalsForNode::One(for_arm_body)
2867        };
2868        debug!(?locals);
2869        self.var_indices.insert(var_id, locals);
2870    }
2871
2872    /// Some bindings are introduced when producing HIR from the AST and don't
2873    /// actually exist in the source. Skip producing debug info for those when
2874    /// we can recognize them.
2875    fn should_emit_debug_info_for_binding(&self, name: Symbol, var_id: LocalVarId) -> bool {
2876        // For now we only recognize the output of desugaring assigns.
2877        if name != sym::lhs {
2878            return true;
2879        }
2880
2881        let tcx = self.tcx;
2882        for (_, node) in tcx.hir_parent_iter(var_id.0) {
2883            // FIXME(khuey) at what point is it safe to bail on the iterator?
2884            // Can we stop at the first non-Pat node?
2885            if matches!(node, Node::LetStmt(&LetStmt { source: LocalSource::AssignDesugar(_), .. }))
2886            {
2887                return false;
2888            }
2889        }
2890
2891        true
2892    }
2893
2894    /// Attempt to statically pick the `BasicBlock` that a value would resolve to at runtime.
2895    pub(crate) fn static_pattern_match(
2896        &self,
2897        cx: &RustcPatCtxt<'_, 'tcx>,
2898        valtree: ValTree<'tcx>,
2899        arms: &[ArmId],
2900        built_match_tree: &BuiltMatchTree<'tcx>,
2901    ) -> Option<BasicBlock> {
2902        let it = arms.iter().zip(built_match_tree.branches.iter());
2903        for (&arm_id, branch) in it {
2904            let pat = cx.lower_pat(&*self.thir.arms[arm_id].pattern);
2905
2906            // Peel off or-patterns if they exist.
2907            if let rustc_pattern_analysis::rustc::Constructor::Or = pat.ctor() {
2908                for pat in pat.iter_fields() {
2909                    // For top-level or-patterns (the only ones we accept right now), when the
2910                    // bindings are the same (e.g. there are none), the sub_branch is stored just
2911                    // once.
2912                    let sub_branch = branch
2913                        .sub_branches
2914                        .get(pat.idx)
2915                        .or_else(|| branch.sub_branches.last())
2916                        .unwrap();
2917
2918                    match self.static_pattern_match_inner(valtree, &pat.pat) {
2919                        true => return Some(sub_branch.success_block),
2920                        false => continue,
2921                    }
2922                }
2923            } else if self.static_pattern_match_inner(valtree, &pat) {
2924                return Some(branch.sub_branches[0].success_block);
2925            }
2926        }
2927
2928        None
2929    }
2930
2931    /// Helper for [`Self::static_pattern_match`], checking whether the value represented by the
2932    /// `ValTree` matches the given pattern. This function does not recurse, meaning that it does
2933    /// not handle or-patterns, or patterns for types with fields.
2934    fn static_pattern_match_inner(
2935        &self,
2936        valtree: ty::ValTree<'tcx>,
2937        pat: &DeconstructedPat<'_, 'tcx>,
2938    ) -> bool {
2939        use rustc_pattern_analysis::constructor::{IntRange, MaybeInfiniteInt};
2940        use rustc_pattern_analysis::rustc::Constructor;
2941
2942        match pat.ctor() {
2943            Constructor::Variant(variant_index) => {
2944                let ValTreeKind::Branch(box [actual_variant_idx]) = *valtree else {
2945                    bug!("malformed valtree for an enum")
2946                };
2947
2948                let ValTreeKind::Leaf(actual_variant_idx) = ***actual_variant_idx else {
2949                    bug!("malformed valtree for an enum")
2950                };
2951
2952                *variant_index == VariantIdx::from_u32(actual_variant_idx.to_u32())
2953            }
2954            Constructor::IntRange(int_range) => {
2955                let size = pat.ty().primitive_size(self.tcx);
2956                let actual_int = valtree.unwrap_leaf().to_bits(size);
2957                let actual_int = if pat.ty().is_signed() {
2958                    MaybeInfiniteInt::new_finite_int(actual_int, size.bits())
2959                } else {
2960                    MaybeInfiniteInt::new_finite_uint(actual_int)
2961                };
2962                IntRange::from_singleton(actual_int).is_subrange(int_range)
2963            }
2964            Constructor::Bool(pattern_value) => match valtree.unwrap_leaf().try_to_bool() {
2965                Ok(actual_value) => *pattern_value == actual_value,
2966                Err(()) => bug!("bool value with invalid bits"),
2967            },
2968            Constructor::F16Range(l, h, end) => {
2969                let actual = valtree.unwrap_leaf().to_f16();
2970                match end {
2971                    RangeEnd::Included => (*l..=*h).contains(&actual),
2972                    RangeEnd::Excluded => (*l..*h).contains(&actual),
2973                }
2974            }
2975            Constructor::F32Range(l, h, end) => {
2976                let actual = valtree.unwrap_leaf().to_f32();
2977                match end {
2978                    RangeEnd::Included => (*l..=*h).contains(&actual),
2979                    RangeEnd::Excluded => (*l..*h).contains(&actual),
2980                }
2981            }
2982            Constructor::F64Range(l, h, end) => {
2983                let actual = valtree.unwrap_leaf().to_f64();
2984                match end {
2985                    RangeEnd::Included => (*l..=*h).contains(&actual),
2986                    RangeEnd::Excluded => (*l..*h).contains(&actual),
2987                }
2988            }
2989            Constructor::F128Range(l, h, end) => {
2990                let actual = valtree.unwrap_leaf().to_f128();
2991                match end {
2992                    RangeEnd::Included => (*l..=*h).contains(&actual),
2993                    RangeEnd::Excluded => (*l..*h).contains(&actual),
2994                }
2995            }
2996            Constructor::Wildcard => true,
2997
2998            // Opaque patterns must not be matched on structurally.
2999            Constructor::Opaque(_) => false,
3000
3001            // These we may eventually support:
3002            Constructor::Struct
3003            | Constructor::Ref
3004            | Constructor::DerefPattern(_)
3005            | Constructor::Slice(_)
3006            | Constructor::UnionField
3007            | Constructor::Or
3008            | Constructor::Str(_) => bug!("unsupported pattern constructor {:?}", pat.ctor()),
3009
3010            // These should never occur here:
3011            Constructor::Never
3012            | Constructor::NonExhaustive
3013            | Constructor::Hidden
3014            | Constructor::Missing
3015            | Constructor::PrivateUninhabited => {
3016                bug!("unsupported pattern constructor {:?}", pat.ctor())
3017            }
3018        }
3019    }
3020}