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