From 4f1c4e29f02ebee5d886844a30e0298fb1ca2a54 Mon Sep 17 00:00:00 2001 From: dianne Date: Wed, 9 Jul 2025 02:36:44 -0700 Subject: [PATCH 1/3] don't schedule unnecessary drops when lowering or-patterns This avoids scheduling drops and immediately unscheduling them. Drops for guard bindings/temporaries are still scheduled and unscheduled as before. --- .../src/builder/matches/mod.rs | 57 ++++++++++--------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 2c29b8628417f..9abb44143df51 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -5,11 +5,11 @@ //! This also includes code for pattern bindings in `let` statements and //! function parameters. -use std::assert_matches::assert_matches; use std::borrow::Borrow; use std::mem; use std::sync::Arc; +use itertools::{Itertools, Position}; use rustc_abi::VariantIdx; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stack::ensure_sufficient_stack; @@ -561,16 +561,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // return: it isn't bound by move until right before enter the arm. // To handle this we instead unschedule it's drop after each time // we lower the guard. + // As a result, we end up with the drop order of the last sub-branch we lower. To use + // the drop order for the first sub-branch, we lower sub-branches in reverse (#142163). + // TODO: I'm saving the breaking change for the next commit. For now, a stopgap: + let sub_branch_to_use_the_drops_from = + if arm_match_scope.is_some() { Position::Last } else { Position::First }; let target_block = self.cfg.start_new_block(); - let mut schedule_drops = ScheduleDrops::Yes; - let arm = arm_match_scope.unzip().0; - // We keep a stack of all of the bindings and type ascriptions - // from the parent candidates that we visit, that also need to - // be bound for each candidate. - for sub_branch in branch.sub_branches { - if let Some(arm) = arm { - self.clear_top_scope(arm.scope); - } + for (pos, sub_branch) in branch.sub_branches.into_iter().with_position() { + debug_assert!(pos != Position::Only); + let schedule_drops = if pos == sub_branch_to_use_the_drops_from { + ScheduleDrops::Yes + } else { + ScheduleDrops::No + }; let binding_end = self.bind_and_guard_matched_candidate( sub_branch, fake_borrow_temps, @@ -579,9 +582,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { schedule_drops, emit_storage_live, ); - if arm.is_none() { - schedule_drops = ScheduleDrops::No; - } self.cfg.goto(binding_end, outer_source_info, target_block); } @@ -2453,11 +2453,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Bindings for guards require some extra handling to automatically // insert implicit references/dereferences. - self.bind_matched_candidate_for_guard( - block, - schedule_drops, - sub_branch.bindings.iter(), - ); + // This always schedules storage drops, so we may need to unschedule them below. + self.bind_matched_candidate_for_guard(block, sub_branch.bindings.iter()); let guard_frame = GuardFrame { locals: sub_branch .bindings @@ -2489,6 +2486,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ) }); + // If this isn't the final sub-branch being lowered, we need to unschedule drops of + // bindings and temporaries created for and by the guard. As a result, the drop order + // for the arm will correspond to the binding order of the final sub-branch lowered. + if matches!(schedule_drops, ScheduleDrops::No) { + self.clear_top_scope(arm.scope); + } + let source_info = self.source_info(guard_span); let guard_end = self.source_info(tcx.sess.source_map().end_point(guard_span)); let guard_frame = self.guard_context.pop().unwrap(); @@ -2538,14 +2542,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let cause = FakeReadCause::ForGuardBinding; self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id)); } - assert_matches!( - schedule_drops, - ScheduleDrops::Yes, - "patterns with guards must schedule drops" - ); + // Only schedule drops for the last sub-branch we lower. self.bind_matched_candidate_for_arm_body( post_guard_block, - ScheduleDrops::Yes, + schedule_drops, by_value_bindings, emit_storage_live, ); @@ -2671,7 +2671,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { fn bind_matched_candidate_for_guard<'b>( &mut self, block: BasicBlock, - schedule_drops: ScheduleDrops, bindings: impl IntoIterator>, ) where 'tcx: 'b, @@ -2690,12 +2689,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // a reference R: &T pointing to the location matched by // the pattern, and every occurrence of P within a guard // denotes *R. + // Drops must be scheduled to emit `StorageDead` on the guard's failure/break branches. let ref_for_guard = self.storage_live_binding( block, binding.var_id, binding.span, RefWithinGuard, - schedule_drops, + ScheduleDrops::Yes, ); match binding.binding_mode.0 { ByRef::No => { @@ -2705,13 +2705,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.cfg.push_assign(block, source_info, ref_for_guard, rvalue); } ByRef::Yes(mutbl) => { - // The arm binding will be by reference, so eagerly create it now. + // The arm binding will be by reference, so eagerly create it now. Drops must + // be scheduled to emit `StorageDead` on the guard's failure/break branches. let value_for_arm = self.storage_live_binding( block, binding.var_id, binding.span, OutsideGuard, - schedule_drops, + ScheduleDrops::Yes, ); let rvalue = From fee2dfd593f47079b2da15c199cb8f47c0fe9684 Mon Sep 17 00:00:00 2001 From: dianne Date: Wed, 9 Jul 2025 02:49:31 -0700 Subject: [PATCH 2/3] base drop order on the first sub-branch --- .../src/builder/matches/mod.rs | 12 ++----- ...fg-initial.after-ElaborateDrops.after.diff | 32 +++++++++---------- tests/ui/drop/or-pattern-drop-order.rs | 8 ++--- .../dropck/eager-by-ref-binding-for-guards.rs | 4 +-- .../eager-by-ref-binding-for-guards.stderr | 16 +++++----- 5 files changed, 33 insertions(+), 39 deletions(-) diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 9abb44143df51..29c5670b0bfcc 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -563,17 +563,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // we lower the guard. // As a result, we end up with the drop order of the last sub-branch we lower. To use // the drop order for the first sub-branch, we lower sub-branches in reverse (#142163). - // TODO: I'm saving the breaking change for the next commit. For now, a stopgap: - let sub_branch_to_use_the_drops_from = - if arm_match_scope.is_some() { Position::Last } else { Position::First }; let target_block = self.cfg.start_new_block(); - for (pos, sub_branch) in branch.sub_branches.into_iter().with_position() { + for (pos, sub_branch) in branch.sub_branches.into_iter().rev().with_position() { debug_assert!(pos != Position::Only); - let schedule_drops = if pos == sub_branch_to_use_the_drops_from { - ScheduleDrops::Yes - } else { - ScheduleDrops::No - }; + let schedule_drops = + if pos == Position::Last { ScheduleDrops::Yes } else { ScheduleDrops::No }; let binding_end = self.bind_and_guard_matched_candidate( sub_branch, fake_borrow_temps, diff --git a/tests/mir-opt/match_arm_scopes.complicated_match.panic-unwind.SimplifyCfg-initial.after-ElaborateDrops.after.diff b/tests/mir-opt/match_arm_scopes.complicated_match.panic-unwind.SimplifyCfg-initial.after-ElaborateDrops.after.diff index b3eb3e1f8b9d2..484bc7dad1289 100644 --- a/tests/mir-opt/match_arm_scopes.complicated_match.panic-unwind.SimplifyCfg-initial.after-ElaborateDrops.after.diff +++ b/tests/mir-opt/match_arm_scopes.complicated_match.panic-unwind.SimplifyCfg-initial.after-ElaborateDrops.after.diff @@ -85,11 +85,11 @@ _8 = &(_2.2: std::string::String); - _3 = &fake shallow (_2.0: bool); - _4 = &fake shallow (_2.1: bool); - StorageLive(_12); - StorageLive(_13); - _13 = copy _1; -- switchInt(move _13) -> [0: bb16, otherwise: bb15]; -+ switchInt(move _13) -> [0: bb13, otherwise: bb12]; + StorageLive(_9); + StorageLive(_10); + _10 = copy _1; +- switchInt(move _10) -> [0: bb12, otherwise: bb11]; ++ switchInt(move _10) -> [0: bb9, otherwise: bb8]; } - bb9: { @@ -100,11 +100,11 @@ _8 = &(_2.2: std::string::String); - _3 = &fake shallow (_2.0: bool); - _4 = &fake shallow (_2.1: bool); - StorageLive(_9); - StorageLive(_10); - _10 = copy _1; -- switchInt(move _10) -> [0: bb12, otherwise: bb11]; -+ switchInt(move _10) -> [0: bb9, otherwise: bb8]; + StorageLive(_12); + StorageLive(_13); + _13 = copy _1; +- switchInt(move _13) -> [0: bb16, otherwise: bb15]; ++ switchInt(move _13) -> [0: bb13, otherwise: bb12]; } - bb10: { @@ -139,7 +139,7 @@ - FakeRead(ForGuardBinding, _6); - FakeRead(ForGuardBinding, _8); StorageLive(_5); - _5 = copy (_2.1: bool); + _5 = copy (_2.0: bool); StorageLive(_7); _7 = move (_2.2: std::string::String); - goto -> bb10; @@ -152,8 +152,8 @@ StorageDead(_9); StorageDead(_8); StorageDead(_6); -- falseEdge -> [real: bb1, imaginary: bb1]; -+ goto -> bb1; +- falseEdge -> [real: bb3, imaginary: bb3]; ++ goto -> bb2; } - bb15: { @@ -181,7 +181,7 @@ - FakeRead(ForGuardBinding, _6); - FakeRead(ForGuardBinding, _8); StorageLive(_5); - _5 = copy (_2.0: bool); + _5 = copy (_2.1: bool); StorageLive(_7); _7 = move (_2.2: std::string::String); - goto -> bb10; @@ -194,8 +194,8 @@ StorageDead(_12); StorageDead(_8); StorageDead(_6); -- falseEdge -> [real: bb3, imaginary: bb3]; -+ goto -> bb2; +- falseEdge -> [real: bb1, imaginary: bb1]; ++ goto -> bb1; } - bb19: { diff --git a/tests/ui/drop/or-pattern-drop-order.rs b/tests/ui/drop/or-pattern-drop-order.rs index fdc28225c3591..a4e4d24995bc8 100644 --- a/tests/ui/drop/or-pattern-drop-order.rs +++ b/tests/ui/drop/or-pattern-drop-order.rs @@ -65,12 +65,12 @@ fn main() { match (LogDrop(o, 3), Ok(LogDrop(o, 1)), LogDrop(o, 2)) { (x, Ok(y) | Err(y), z) => {} } }); assert_drop_order(1..=2, |o| { - // The last or-pattern alternative determines the bindings' drop order: `x`, `y`. - match (true, LogDrop(o, 1), LogDrop(o, 2)) { (true, x, y) | (false, y, x) => {} } + // The first or-pattern alternative determines the bindings' drop order: `y`, `x`. + match (true, LogDrop(o, 2), LogDrop(o, 1)) { (true, x, y) | (false, y, x) => {} } }); assert_drop_order(1..=2, |o| { - // That drop order is used regardless of which or-pattern alternative matches: `x`, `y`. - match (false, LogDrop(o, 2), LogDrop(o, 1)) { (true, x, y) | (false, y, x) => {} } + // That drop order is used regardless of which or-pattern alternative matches: `y`, `x`. + match (false, LogDrop(o, 1), LogDrop(o, 2)) { (true, x, y) | (false, y, x) => {} } }); // Function params are visited one-by-one, and the order of bindings within a param's pattern is diff --git a/tests/ui/dropck/eager-by-ref-binding-for-guards.rs b/tests/ui/dropck/eager-by-ref-binding-for-guards.rs index 3f47583917172..90ff9a747aece 100644 --- a/tests/ui/dropck/eager-by-ref-binding-for-guards.rs +++ b/tests/ui/dropck/eager-by-ref-binding-for-guards.rs @@ -17,15 +17,15 @@ fn main() { (mut long2, ref short2) if true => long2.0 = &short2, _ => unreachable!(), } - // This depends on the binding modes of the final or-pattern alternatives (see #142163): + // This depends on the binding modes of the first or-pattern alternatives: let res: &Result = &Ok(1); match (Struct(&&0), res) { (mut long3, Ok(short3) | &Err(short3)) if true => long3.0 = &short3, - //~^ ERROR `short3` does not live long enough _ => unreachable!(), } match (Struct(&&0), res) { (mut long4, &Err(short4) | Ok(short4)) if true => long4.0 = &short4, + //~^ ERROR `short4` does not live long enough _ => unreachable!(), } } diff --git a/tests/ui/dropck/eager-by-ref-binding-for-guards.stderr b/tests/ui/dropck/eager-by-ref-binding-for-guards.stderr index cb1a04cd4447b..2648ce6f99c34 100644 --- a/tests/ui/dropck/eager-by-ref-binding-for-guards.stderr +++ b/tests/ui/dropck/eager-by-ref-binding-for-guards.stderr @@ -11,15 +11,15 @@ LL | (mut long1, ref short1) => long1.0 = &short1, | = note: values in a scope are dropped in the opposite order they are defined -error[E0597]: `short3` does not live long enough - --> $DIR/eager-by-ref-binding-for-guards.rs:23:69 +error[E0597]: `short4` does not live long enough + --> $DIR/eager-by-ref-binding-for-guards.rs:27:69 | -LL | (mut long3, Ok(short3) | &Err(short3)) if true => long3.0 = &short3, - | ------ ^^^^^^- - | | | | - | | | `short3` dropped here while still borrowed - | | | borrow might be used here, when `long3` is dropped and runs the `Drop` code for type `Struct` - | binding `short3` declared here borrowed value does not live long enough +LL | (mut long4, &Err(short4) | Ok(short4)) if true => long4.0 = &short4, + | ------ ^^^^^^- + | | | | + | | | `short4` dropped here while still borrowed + | | | borrow might be used here, when `long4` is dropped and runs the `Drop` code for type `Struct` + | binding `short4` declared here borrowed value does not live long enough | = note: values in a scope are dropped in the opposite order they are defined From 0cda1104582c662e7db6b88a4e9eafa55e4809d4 Mon Sep 17 00:00:00 2001 From: dianne Date: Thu, 10 Jul 2025 16:38:53 -0700 Subject: [PATCH 3/3] lower bindings in the order they're written --- .../src/builder/matches/match_pair.rs | 20 +++-- .../src/builder/matches/mod.rs | 80 +++++++++++++++++-- .../src/builder/matches/util.rs | 8 +- tests/ui/drop/or-pattern-drop-order.rs | 45 +++++++---- .../bindings-after-at/bind-by-copy-or-pat.rs | 7 +- .../bind-by-copy-or-pat.stderr | 31 ------- 6 files changed, 126 insertions(+), 65 deletions(-) delete mode 100644 tests/ui/pattern/bindings-after-at/bind-by-copy-or-pat.stderr diff --git a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs index 3a7854a5e118d..7a848536d0e33 100644 --- a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -124,9 +124,19 @@ impl<'tcx> MatchPairTree<'tcx> { let test_case = match pattern.kind { PatKind::Missing | PatKind::Wild | PatKind::Error(_) => None, - PatKind::Or { ref pats } => Some(TestCase::Or { - pats: pats.iter().map(|pat| FlatPat::new(place_builder.clone(), pat, cx)).collect(), - }), + PatKind::Or { ref pats } => { + let pats: Box<[FlatPat<'tcx>]> = + pats.iter().map(|pat| FlatPat::new(place_builder.clone(), pat, cx)).collect(); + if !pats[0].extra_data.bindings.is_empty() { + // Hold a place for any bindings established in (possibly-nested) or-patterns. + // By only holding a place when bindings are present, we skip over any + // or-patterns that will be simplified by `merge_trivial_subcandidates`. In + // other words, we can assume this expands into subcandidates. + // FIXME(@dianne): this needs updating/removing if we always merge or-patterns + extra_data.bindings.push(super::SubpatternBindings::FromOrPattern); + } + Some(TestCase::Or { pats }) + } PatKind::Range(ref range) => { if range.is_full_range(cx.tcx) == Some(true) { @@ -194,12 +204,12 @@ impl<'tcx> MatchPairTree<'tcx> { // Then push this binding, after any bindings in the subpattern. if let Some(source) = place { - extra_data.bindings.push(super::Binding { + extra_data.bindings.push(super::SubpatternBindings::One(super::Binding { span: pattern.span, source, var_id: var, binding_mode: mode, - }); + })); } None diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 29c5670b0bfcc..a65b0d99ce37a 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -990,7 +990,7 @@ struct PatternExtraData<'tcx> { span: Span, /// Bindings that must be established. - bindings: Vec>, + bindings: Vec>, /// Types that must be asserted. ascriptions: Vec>, @@ -1005,6 +1005,15 @@ impl<'tcx> PatternExtraData<'tcx> { } } +#[derive(Debug, Clone)] +enum SubpatternBindings<'tcx> { + /// A single binding. + One(Binding<'tcx>), + /// Holds the place for an or-pattern's bindings. This ensures their drops are scheduled in the + /// order the primary bindings appear. See rust-lang/rust#142163 for more information. + FromOrPattern, +} + /// A pattern in a form suitable for lowering the match tree, with all irrefutable /// patterns simplified away. /// @@ -1220,7 +1229,7 @@ fn traverse_candidate<'tcx, C, T, I>( } } -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] struct Binding<'tcx> { span: Span, source: Place<'tcx>, @@ -1446,12 +1455,7 @@ impl<'tcx> MatchTreeSubBranch<'tcx> { span: candidate.extra_data.span, success_block: candidate.pre_binding_block.unwrap(), otherwise_block: candidate.otherwise_block.unwrap(), - bindings: parent_data - .iter() - .flat_map(|d| &d.bindings) - .chain(&candidate.extra_data.bindings) - .cloned() - .collect(), + bindings: sub_branch_bindings(parent_data, &candidate.extra_data.bindings), ascriptions: parent_data .iter() .flat_map(|d| &d.ascriptions) @@ -1484,6 +1488,66 @@ impl<'tcx> MatchTreeBranch<'tcx> { } } +/// Collects the bindings for a [`MatchTreeSubBranch`], preserving the order they appear in the +/// pattern, as though the or-alternatives chosen in this sub-branch were inlined. +fn sub_branch_bindings<'tcx>( + parents: &[PatternExtraData<'tcx>], + leaf_bindings: &[SubpatternBindings<'tcx>], +) -> Vec> { + // In the common case, all bindings will be in leaves. Allocate to fit the leaf's bindings. + let mut bindings = Vec::with_capacity(leaf_bindings.len()); + let remainder = push_sub_branch_bindings(&mut bindings, Some(parents), leaf_bindings); + // Make sure we've included all bindings. We can end up with a non-`None` remainder if there's + // an unsimplifed or-pattern at the end that doesn't contain bindings. + if let Some(remainder) = remainder { + assert!(remainder.iter().all(|parent| parent.bindings.is_empty())); + assert!(leaf_bindings.is_empty()); + } + bindings +} + +/// Helper for [`sub_branch_bindings`]. Returns any bindings yet to be inlined. +fn push_sub_branch_bindings<'c, 'tcx>( + flattened: &mut Vec>, + parents: Option<&'c [PatternExtraData<'tcx>]>, + leaf_bindings: &[SubpatternBindings<'tcx>], +) -> Option<&'c [PatternExtraData<'tcx>]> { + match parents { + None => bug!("can't inline or-pattern bindings: already inlined all bindings"), + Some(mut parents) => { + let (bindings, mut remainder) = loop { + match parents { + // Base case: only the leaf's bindings remain to be inlined. + [] => break (leaf_bindings, None), + // Otherwise, inline the first non-empty descendant. + [parent, remainder @ ..] => { + if parent.bindings.is_empty() { + // Skip over unsimplified or-patterns without bindings. + parents = remainder; + } else { + break (&parent.bindings[..], Some(remainder)); + } + } + } + }; + for subpat_bindings in bindings { + match subpat_bindings { + SubpatternBindings::One(binding) => flattened.push(*binding), + SubpatternBindings::FromOrPattern => { + // Inline bindings from an or-pattern. By construction, this always + // corresponds to a subcandidate and its closest descendants (i.e. those + // from nested or-patterns, but not adjacent or-patterns). To handle + // adjacent or-patterns, e.g. `(x | x, y | y)`, we update the `remainder` to + // point to the first descendant candidate from outside this or-pattern. + remainder = push_sub_branch_bindings(flattened, remainder, leaf_bindings); + } + } + } + remainder + } + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum HasMatchGuard { Yes, diff --git a/compiler/rustc_mir_build/src/builder/matches/util.rs b/compiler/rustc_mir_build/src/builder/matches/util.rs index 589e350a03fc3..2c8ad95b6afdb 100644 --- a/compiler/rustc_mir_build/src/builder/matches/util.rs +++ b/compiler/rustc_mir_build/src/builder/matches/util.rs @@ -138,7 +138,9 @@ impl<'a, 'b, 'tcx> FakeBorrowCollector<'a, 'b, 'tcx> { fn visit_candidate(&mut self, candidate: &Candidate<'tcx>) { for binding in &candidate.extra_data.bindings { - self.visit_binding(binding); + if let super::SubpatternBindings::One(binding) = binding { + self.visit_binding(binding); + } } for match_pair in &candidate.match_pairs { self.visit_match_pair(match_pair); @@ -147,7 +149,9 @@ impl<'a, 'b, 'tcx> FakeBorrowCollector<'a, 'b, 'tcx> { fn visit_flat_pat(&mut self, flat_pat: &FlatPat<'tcx>) { for binding in &flat_pat.extra_data.bindings { - self.visit_binding(binding); + if let super::SubpatternBindings::One(binding) = binding { + self.visit_binding(binding); + } } for match_pair in &flat_pat.match_pairs { self.visit_match_pair(match_pair); diff --git a/tests/ui/drop/or-pattern-drop-order.rs b/tests/ui/drop/or-pattern-drop-order.rs index a4e4d24995bc8..cca81673ac3ac 100644 --- a/tests/ui/drop/or-pattern-drop-order.rs +++ b/tests/ui/drop/or-pattern-drop-order.rs @@ -1,6 +1,7 @@ //@ run-pass //! Test drop order for different ways of declaring pattern bindings involving or-patterns. -//! Currently, it's inconsistent between language constructs (#142163). +//! In particular, are ordered based on the order in which the first occurrence of each binding +//! appears (i.e. the "primary" bindings). Regression test for #142163. use std::cell::RefCell; use std::ops::Drop; @@ -43,11 +44,10 @@ fn main() { y = LogDrop(o, 1); }); - // When bindings are declared with `let pat = expr;`, bindings within or-patterns are seen last, - // thus they're dropped first. + // `let pat = expr;` should have the same drop order. assert_drop_order(1..=3, |o| { - // Drops are right-to-left, treating `y` as rightmost: `y`, `z`, `x`. - let (x, Ok(y) | Err(y), z) = (LogDrop(o, 3), Ok(LogDrop(o, 1)), LogDrop(o, 2)); + // Drops are right-to-left: `z`, `y`, `x`. + let (x, Ok(y) | Err(y), z) = (LogDrop(o, 3), Ok(LogDrop(o, 2)), LogDrop(o, 1)); }); assert_drop_order(1..=2, |o| { // The first or-pattern alternative determines the bindings' drop order: `y`, `x`. @@ -58,11 +58,10 @@ fn main() { let ((true, x, y) | (false, y, x)) = (false, LogDrop(o, 1), LogDrop(o, 2)); }); - // `match` treats or-patterns as last like `let pat = expr;`, but also determines drop order - // using the order of the bindings in the *last* or-pattern alternative. + // `match` should have the same drop order. assert_drop_order(1..=3, |o| { - // Drops are right-to-left, treating `y` as rightmost: `y`, `z`, `x`. - match (LogDrop(o, 3), Ok(LogDrop(o, 1)), LogDrop(o, 2)) { (x, Ok(y) | Err(y), z) => {} } + // Drops are right-to-left: `z`, `y` `x`. + match (LogDrop(o, 3), Ok(LogDrop(o, 2)), LogDrop(o, 1)) { (x, Ok(y) | Err(y), z) => {} } }); assert_drop_order(1..=2, |o| { // The first or-pattern alternative determines the bindings' drop order: `y`, `x`. @@ -74,14 +73,14 @@ fn main() { }); // Function params are visited one-by-one, and the order of bindings within a param's pattern is - // the same as `let pat = expr`; + // the same as `let pat = expr;` assert_drop_order(1..=3, |o| { // Among separate params, the drop order is right-to-left: `z`, `y`, `x`. (|x, (Ok(y) | Err(y)), z| {})(LogDrop(o, 3), Ok(LogDrop(o, 2)), LogDrop(o, 1)); }); assert_drop_order(1..=3, |o| { - // Within a param's pattern, or-patterns are treated as rightmost: `y`, `z`, `x`. - (|(x, Ok(y) | Err(y), z)| {})((LogDrop(o, 3), Ok(LogDrop(o, 1)), LogDrop(o, 2))); + // Within a param's pattern, likewise: `z`, `y`, `x`. + (|(x, Ok(y) | Err(y), z)| {})((LogDrop(o, 3), Ok(LogDrop(o, 2)), LogDrop(o, 1))); }); assert_drop_order(1..=2, |o| { // The first or-pattern alternative determines the bindings' drop order: `y`, `x`. @@ -89,12 +88,11 @@ fn main() { }); // `if let` and `let`-`else` see bindings in the same order as `let pat = expr;`. - // Vars in or-patterns are seen last (dropped first), and the first alternative's order is used. assert_drop_order(1..=3, |o| { - if let (x, Ok(y) | Err(y), z) = (LogDrop(o, 3), Ok(LogDrop(o, 1)), LogDrop(o, 2)) {} + if let (x, Ok(y) | Err(y), z) = (LogDrop(o, 3), Ok(LogDrop(o, 2)), LogDrop(o, 1)) {} }); assert_drop_order(1..=3, |o| { - let (x, Ok(y) | Err(y), z) = (LogDrop(o, 3), Ok(LogDrop(o, 1)), LogDrop(o, 2)) else { + let (x, Ok(y) | Err(y), z) = (LogDrop(o, 3), Ok(LogDrop(o, 2)), LogDrop(o, 1)) else { unreachable!(); }; }); @@ -106,4 +104,21 @@ fn main() { unreachable!(); }; }); + + // Test nested and adjacent or-patterns, including or-patterns without bindings under a guard. + assert_drop_order(1..=6, |o| { + // The `LogDrop`s that aren't moved into bindings are dropped last. + match [ + [LogDrop(o, 6), LogDrop(o, 4)], + [LogDrop(o, 3), LogDrop(o, 2)], + [LogDrop(o, 1), LogDrop(o, 5)], + ] { + [ + [_ | _, w | w] | [w | w, _ | _], + [x | x, y | y] | [y | y, x | x], + [z | z, _ | _] | [_ | _, z | z], + ] if true => {} + _ => unreachable!(), + } + }); } diff --git a/tests/ui/pattern/bindings-after-at/bind-by-copy-or-pat.rs b/tests/ui/pattern/bindings-after-at/bind-by-copy-or-pat.rs index 1555da2fd1fc3..dd23acfa23549 100644 --- a/tests/ui/pattern/bindings-after-at/bind-by-copy-or-pat.rs +++ b/tests/ui/pattern/bindings-after-at/bind-by-copy-or-pat.rs @@ -1,16 +1,15 @@ -//@ known-bug: unknown +//@ run-pass #![allow(unused)] struct A(u32); pub fn main() { - // The or-pattern bindings are lowered after `x`, which triggers the error. + // Bindings are lowered in the order they appear syntactically, so this works. let x @ (A(a) | A(a)) = A(10); - // ERROR: use of moved value assert!(x.0 == 10); assert!(a == 10); - // This works. + // This also works. let (x @ A(a) | x @ A(a)) = A(10); assert!(x.0 == 10); assert!(a == 10); diff --git a/tests/ui/pattern/bindings-after-at/bind-by-copy-or-pat.stderr b/tests/ui/pattern/bindings-after-at/bind-by-copy-or-pat.stderr deleted file mode 100644 index 7980818635836..0000000000000 --- a/tests/ui/pattern/bindings-after-at/bind-by-copy-or-pat.stderr +++ /dev/null @@ -1,31 +0,0 @@ -error[E0382]: use of moved value - --> $DIR/bind-by-copy-or-pat.rs:8:16 - | -LL | let x @ (A(a) | A(a)) = A(10); - | - ^ ----- move occurs because value has type `A`, which does not implement the `Copy` trait - | | | - | | value used here after move - | value moved here - | -help: borrow this binding in the pattern to avoid moving the value - | -LL | let ref x @ (A(a) | A(a)) = A(10); - | +++ - -error[E0382]: use of moved value - --> $DIR/bind-by-copy-or-pat.rs:8:23 - | -LL | let x @ (A(a) | A(a)) = A(10); - | - ^ ----- move occurs because value has type `A`, which does not implement the `Copy` trait - | | | - | | value used here after move - | value moved here - | -help: borrow this binding in the pattern to avoid moving the value - | -LL | let ref x @ (A(a) | A(a)) = A(10); - | +++ - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0382`.