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::borrow::Borrow;
9use std::mem;
10use std::sync::Arc;
1112use itertools::{Itertools, Position};
13use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
14use rustc_data_structures::debug_assert_matches;
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 { pin: Pinnedness::Pinned, ref subpattern } =>
{
visit_subpat(self, subpattern,
&user_tys.leaf(FieldIdx::ZERO).deref(), f);
}
PatKind::Deref { pin: Pinnedness::Not, 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:927",
"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(927u32),
::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 { pin: Pinnedness::Pinned, ref subpattern } => {
913// Project into the `Pin(_)` struct, then deref the inner `&` or `&mut`.
914visit_subpat(self, subpattern, &user_tys.leaf(FieldIdx::ZERO).deref(), f);
915 }
916 PatKind::Deref { pin: Pinnedness::Not, ref subpattern } => {
917 visit_subpat(self, subpattern, &user_tys.deref(), f);
918 }
919920 PatKind::DerefPattern { ref subpattern, .. } => {
921 visit_subpat(self, subpattern, &ProjectedUserTypesNode::None, f);
922 }
923924 PatKind::Leaf { ref subpatterns } => {
925for subpattern in subpatterns {
926let subpattern_user_tys = user_tys.leaf(subpattern.field);
927debug!("visit_primary_bindings: subpattern_user_tys={subpattern_user_tys:?}");
928 visit_subpat(self, &subpattern.pattern, &subpattern_user_tys, f);
929 }
930 }
931932 PatKind::Variant { adt_def, args: _, variant_index, ref subpatterns } => {
933for subpattern in subpatterns {
934let subpattern_user_tys =
935 user_tys.variant(adt_def, variant_index, subpattern.field);
936 visit_subpat(self, &subpattern.pattern, &subpattern_user_tys, f);
937 }
938 }
939 PatKind::Or { ref pats } => {
940// In cases where we recover from errors the primary bindings
941 // may not all be in the leftmost subpattern. For example in
942 // `let (x | y) = ...`, the primary binding of `y` occurs in
943 // the right subpattern
944for subpattern in pats.iter() {
945 visit_subpat(self, subpattern, user_tys, f);
946 }
947 }
948 }
949 }
950}
951952/// Data extracted from a pattern that doesn't affect which branch is taken. Collected during
953/// pattern simplification and not mutated later.
954#[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)]
955struct PatternExtraData<'tcx> {
956/// [`Span`] of the original pattern.
957span: Span,
958959/// Bindings that must be established.
960bindings: Vec<SubpatternBindings<'tcx>>,
961962/// Types that must be asserted.
963ascriptions: Vec<Ascription<'tcx>>,
964965/// Whether this corresponds to a never pattern.
966is_never: bool,
967}
968969impl<'tcx> PatternExtraData<'tcx> {
970fn is_empty(&self) -> bool {
971self.bindings.is_empty() && self.ascriptions.is_empty()
972 }
973}
974975#[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)]
976enum SubpatternBindings<'tcx> {
977/// A single binding.
978One(Binding<'tcx>),
979/// Holds the place for an or-pattern's bindings. This ensures their drops are scheduled in the
980 /// order the primary bindings appear. See rust-lang/rust#142163 for more information.
981FromOrPattern,
982}
983984/// A pattern in a form suitable for lowering the match tree, with all irrefutable
985/// patterns simplified away.
986///
987/// Here, "flat" indicates that irrefutable nodes in the pattern tree have been
988/// recursively replaced with their refutable subpatterns. They are not
989/// necessarily flat in an absolute sense.
990///
991/// Will typically be incorporated into a [`Candidate`].
992#[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)]
993struct FlatPat<'tcx> {
994/// To match the pattern, all of these must be satisfied...
995match_pairs: Vec<MatchPairTree<'tcx>>,
996997 extra_data: PatternExtraData<'tcx>,
998}
9991000impl<'tcx> FlatPat<'tcx> {
1001/// Creates a `FlatPat` containing a simplified [`MatchPairTree`] list/forest
1002 /// for the given pattern.
1003fn new(place: PlaceBuilder<'tcx>, pattern: &Pat<'tcx>, cx: &mut Builder<'_, 'tcx>) -> Self {
1004// Recursively build a tree of match pairs for the given pattern.
1005let mut match_pairs = ::alloc::vec::Vec::new()vec![];
1006let mut extra_data = PatternExtraData {
1007 span: pattern.span,
1008 bindings: Vec::new(),
1009 ascriptions: Vec::new(),
1010 is_never: pattern.is_never_pattern(),
1011 };
1012MatchPairTree::for_pattern(place, pattern, cx, &mut match_pairs, &mut extra_data);
10131014Self { match_pairs, extra_data }
1015 }
1016}
10171018/// Candidates are a generalization of (a) top-level match arms, and
1019/// (b) sub-branches of or-patterns, allowing the match-lowering process to handle
1020/// them both in a mostly-uniform way. For example, the list of candidates passed
1021/// to [`Builder::match_candidates`] will often contain a mixture of top-level
1022/// candidates and or-pattern subcandidates.
1023///
1024/// At the start of match lowering, there is one candidate for each match arm.
1025/// During match lowering, arms with or-patterns will be expanded into a tree
1026/// of candidates, where each "leaf" candidate represents one of the ways for
1027/// the arm pattern to successfully match.
1028#[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)]
1029struct Candidate<'tcx> {
1030/// For the candidate to match, all of these must be satisfied...
1031 ///
1032 /// ---
1033 /// Initially contains a list of match pairs created by [`FlatPat`], but is
1034 /// subsequently mutated (in a queue-like way) while lowering the match tree.
1035 /// When this list becomes empty, the candidate is fully matched and becomes
1036 /// a leaf (see [`Builder::select_matched_candidate`]).
1037 ///
1038 /// Key mutations include:
1039 ///
1040 /// - When a match pair is fully satisfied by a test, it is removed from the
1041 /// list, and its subpairs are added instead (see [`Builder::choose_bucket_for_candidate`]).
1042 /// - During or-pattern expansion, any leading or-pattern is removed, and is
1043 /// converted into subcandidates (see [`Builder::expand_and_match_or_candidates`]).
1044 /// - After a candidate's subcandidates have been lowered, a copy of any remaining
1045 /// or-patterns is added to each leaf subcandidate
1046 /// (see [`Builder::test_remaining_match_pairs_after_or`]).
1047 ///
1048 /// Invariants:
1049 /// - All or-patterns ([`TestableCase::Or`]) have been sorted to the end.
1050match_pairs: Vec<MatchPairTree<'tcx>>,
10511052/// ...and if this is non-empty, one of these subcandidates also has to match...
1053 ///
1054 /// ---
1055 /// Initially a candidate has no subcandidates; they are added (and then immediately
1056 /// lowered) during or-pattern expansion. Their main function is to serve as _output_
1057 /// of match tree lowering, allowing later steps to see the leaf candidates that
1058 /// represent a match of the entire match arm.
1059 ///
1060 /// A candidate no subcandidates is either incomplete (if it has match pairs left),
1061 /// or is a leaf in the match tree. A candidate with one or more subcandidates is
1062 /// an internal node in the match tree.
1063 ///
1064 /// Invariant: at the end of match tree lowering, this must not contain an
1065 /// `is_never` candidate, because that would break binding consistency.
1066 /// - See [`Builder::remove_never_subcandidates`].
1067subcandidates: Vec<Candidate<'tcx>>,
10681069/// ...and if there is a guard it must be evaluated; if it's `false` then branch to `otherwise_block`.
1070 ///
1071 /// ---
1072 /// For subcandidates, this is copied from the parent candidate, so it indicates
1073 /// whether the enclosing match arm has a guard.
1074has_guard: bool,
10751076/// Holds extra pattern data that was prepared by [`FlatPat`], including bindings and
1077 /// ascriptions that must be established if this candidate succeeds.
1078extra_data: PatternExtraData<'tcx>,
10791080/// When setting `self.subcandidates`, we store here the span of the or-pattern they came from.
1081 ///
1082 /// ---
1083 /// Invariant: it is `None` iff `subcandidates.is_empty()`.
1084 /// - FIXME: We sometimes don't unset this when clearing `subcandidates`.
1085or_span: Option<Span>,
10861087/// The block before the `bindings` have been established.
1088 ///
1089 /// After the match tree has been lowered, [`Builder::lower_match_arms`]
1090 /// will use this as the start point for lowering bindings and guards, and
1091 /// then jump to a shared block containing the arm body.
1092pre_binding_block: Option<BasicBlock>,
10931094/// The block to branch to if the guard or a nested candidate fails to match.
1095otherwise_block: Option<BasicBlock>,
10961097/// The earliest block that has only candidates >= this one as descendents. Used for false
1098 /// edges, see the doc for [`Builder::match_expr`].
1099false_edge_start_block: Option<BasicBlock>,
1100}
11011102impl<'tcx> Candidate<'tcx> {
1103fn new(
1104 place: PlaceBuilder<'tcx>,
1105 pattern: &Pat<'tcx>,
1106 has_guard: HasMatchGuard,
1107 cx: &mut Builder<'_, 'tcx>,
1108 ) -> Self {
1109// Use `FlatPat` to build simplified match pairs, then immediately
1110 // incorporate them into a new candidate.
1111Self::from_flat_pat(
1112FlatPat::new(place, pattern, cx),
1113#[allow(non_exhaustive_omitted_patterns)] match has_guard {
HasMatchGuard::Yes => true,
_ => false,
}matches!(has_guard, HasMatchGuard::Yes),
1114 )
1115 }
11161117/// Incorporates an already-simplified [`FlatPat`] into a new candidate.
1118fn from_flat_pat(flat_pat: FlatPat<'tcx>, has_guard: bool) -> Self {
1119let mut this = Candidate {
1120 match_pairs: flat_pat.match_pairs,
1121 extra_data: flat_pat.extra_data,
1122has_guard,
1123 subcandidates: Vec::new(),
1124 or_span: None,
1125 otherwise_block: None,
1126 pre_binding_block: None,
1127 false_edge_start_block: None,
1128 };
1129this.sort_match_pairs();
1130this1131 }
11321133/// Restores the invariant that or-patterns must be sorted to the end.
1134fn sort_match_pairs(&mut self) {
1135self.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 { .. }));
1136 }
11371138/// Returns whether the first match pair of this candidate is an or-pattern.
1139fn starts_with_or_pattern(&self) -> bool {
1140#[allow(non_exhaustive_omitted_patterns)] match &*self.match_pairs {
[MatchPairTree { testable_case: TestableCase::Or { .. }, .. }, ..] =>
true,
_ => false,
}matches!(
1141&*self.match_pairs,
1142 [MatchPairTree { testable_case: TestableCase::Or { .. }, .. }, ..]
1143 )1144 }
11451146/// Visit the leaf candidates (those with no subcandidates) contained in
1147 /// this candidate.
1148fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
1149traverse_candidate(
1150self,
1151&mut (),
1152&mut move |c, _| visit_leaf(c),
1153move |c, _| c.subcandidates.iter_mut(),
1154 |_| {},
1155 );
1156 }
11571158/// Visit the leaf candidates in reverse order.
1159fn visit_leaves_rev<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
1160traverse_candidate(
1161self,
1162&mut (),
1163&mut move |c, _| visit_leaf(c),
1164move |c, _| c.subcandidates.iter_mut().rev(),
1165 |_| {},
1166 );
1167 }
1168}
11691170/// A depth-first traversal of the `Candidate` and all of its recursive
1171/// subcandidates.
1172///
1173/// This signature is very generic, to support traversing candidate trees by
1174/// reference or by value, and to allow a mutable "context" to be shared by the
1175/// traversal callbacks. Most traversals can use the simpler
1176/// [`Candidate::visit_leaves`] wrapper instead.
1177fn traverse_candidate<'tcx, C, T, I>(
1178 candidate: C,
1179 context: &mut T,
1180// Called when visiting a "leaf" candidate (with no subcandidates).
1181visit_leaf: &mut impl FnMut(C, &mut T),
1182// Called when visiting a "node" candidate (with one or more subcandidates).
1183 // Returns an iterator over the candidate's children (by value or reference).
1184 // Can perform setup before visiting the node's children.
1185get_children: impl Copy + Fn(C, &mut T) -> I,
1186// Called after visiting a "node" candidate's children.
1187complete_children: impl Copy + Fn(&mut T),
1188) where
1189C: Borrow<Candidate<'tcx>>, // Typically `Candidate` or `&mut Candidate`
1190I: Iterator<Item = C>,
1191{
1192if candidate.borrow().subcandidates.is_empty() {
1193visit_leaf(candidate, context)
1194 } else {
1195for child in get_children(candidate, context) {
1196 traverse_candidate(child, context, visit_leaf, get_children, complete_children);
1197 }
1198complete_children(context)
1199 }
1200}
12011202#[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)]
1203struct Binding<'tcx> {
1204 span: Span,
1205 source: Place<'tcx>,
1206 var_id: LocalVarId,
1207 binding_mode: BindingMode,
1208 is_shorthand: bool,
1209}
12101211/// Indicates that the type of `source` must be a subtype of the
1212/// user-given type `user_ty`; this is basically a no-op but can
1213/// influence region inference.
1214#[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)]
1215struct Ascription<'tcx> {
1216 source: Place<'tcx>,
1217 annotation: CanonicalUserTypeAnnotation<'tcx>,
1218 variance: ty::Variance,
1219}
12201221/// Partial summary of a [`thir::Pat`], indicating what sort of test should be
1222/// performed to match/reject the pattern, and what the desired test outcome is.
1223/// This avoids having to perform a full match on [`thir::PatKind`] in some places,
1224/// and helps [`TestKind::Switch`] and [`TestKind::SwitchInt`] know what target
1225/// values to use.
1226///
1227/// Created by [`MatchPairTree::for_pattern`], and then inspected primarily by:
1228/// - [`Builder::pick_test_for_match_pair`] (to choose a test)
1229/// - [`Builder::choose_bucket_for_candidate`] (to see how the test interacts with a match pair)
1230///
1231/// Note that or-patterns are not tested directly like the other variants.
1232/// Instead they participate in or-pattern expansion, where they are transformed into
1233/// subcandidates. See [`Builder::expand_and_match_or_candidates`].
1234#[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)]
1235enum TestableCase<'tcx> {
1236 Variant { adt_def: ty::AdtDef<'tcx>, variant_index: VariantIdx },
1237 Constant { value: ty::Value<'tcx>, kind: PatConstKind },
1238 Range(Arc<PatRange<'tcx>>),
1239 Slice { len: u64, op: SliceLenOp },
1240 Deref { temp: Place<'tcx>, mutability: Mutability },
1241 Never,
1242 Or { pats: Box<[FlatPat<'tcx>]> },
1243}
12441245impl<'tcx> TestableCase<'tcx> {
1246fn as_range(&self) -> Option<&PatRange<'tcx>> {
1247if let Self::Range(v) = self { Some(v.as_ref()) } else { None }
1248 }
1249}
12501251/// Sub-classification of [`TestableCase::Constant`], which helps to avoid
1252/// some redundant ad-hoc checks when preparing and lowering tests.
1253#[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)]
1254enum PatConstKind {
1255/// The primitive `bool` type, which is like an integer but simpler,
1256 /// having only two values.
1257Bool,
1258/// Primitive unsigned/signed integer types, plus `char`.
1259 /// These types interact nicely with `SwitchInt`.
1260IntOrChar,
1261/// Floating-point primitives, e.g. `f32`, `f64`.
1262 /// These types don't support `SwitchInt` and require an equality test,
1263 /// but can also interact with range pattern tests.
1264Float,
1265/// Constant string values, tested via string equality.
1266String,
1267/// Any other constant-pattern is usually tested via some kind of equality
1268 /// check. Types that might be encountered here include:
1269 /// - raw pointers derived from integer values
1270 /// - pattern types, e.g. `pattern_type!(u32 is 1..)`
1271Other,
1272}
12731274/// Node in a tree of "match pairs", where each pair consists of a place to be
1275/// tested, and a test to perform on that place.
1276///
1277/// Each node also has a list of subpairs (possibly empty) that must also match,
1278/// and a reference to the THIR pattern it represents.
1279#[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)]
1280pub(crate) struct MatchPairTree<'tcx> {
1281/// This place...
1282 ///
1283 /// ---
1284 /// This can be `None` if it referred to a non-captured place in a closure.
1285 ///
1286 /// Invariant: Can only be `None` when `testable_case` is `Or`.
1287 /// Therefore this must be `Some(_)` after or-pattern expansion.
1288place: Option<Place<'tcx>>,
12891290/// ... must pass this test...
1291testable_case: TestableCase<'tcx>,
12921293/// ... and these subpairs must match.
1294 ///
1295 /// ---
1296 /// Subpairs typically represent tests that can only be performed after their
1297 /// parent has succeeded. For example, the pattern `Some(3)` might have an
1298 /// outer match pair that tests for the variant `Some`, and then a subpair
1299 /// that tests its field for the value `3`.
1300subpairs: Vec<Self>,
13011302/// Type field of the pattern this node was created from.
1303pattern_ty: Ty<'tcx>,
1304/// Span field of the pattern this node was created from.
1305pattern_span: Span,
1306}
13071308/// A runtime test to perform to determine which candidates match a scrutinee place.
1309///
1310/// The kind of test to perform is indicated by [`TestKind`].
1311#[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)]
1312pub(crate) struct Test<'tcx> {
1313 span: Span,
1314 kind: TestKind<'tcx>,
1315}
13161317/// The kind of runtime test to perform to determine which candidates match a
1318/// scrutinee place. This is the main component of [`Test`].
1319///
1320/// Some of these variants don't contain the constant value(s) being tested
1321/// against, because those values are stored in the corresponding bucketed
1322/// candidates instead.
1323#[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)]
1324enum TestKind<'tcx> {
1325/// Test what enum variant a value is.
1326 ///
1327 /// The subset of expected variants is not stored here; instead they are
1328 /// extracted from the [`TestableCase`]s of the candidates participating in the
1329 /// test.
1330Switch {
1331/// The enum type being tested.
1332adt_def: ty::AdtDef<'tcx>,
1333 },
13341335/// Test what value an integer or `char` has.
1336 ///
1337 /// The test's target values are not stored here; instead they are extracted
1338 /// from the [`TestableCase`]s of the candidates participating in the test.
1339SwitchInt,
13401341/// Test whether a `bool` is `true` or `false`.
1342If,
13431344/// Tests the place against a string constant using string equality.
1345StringEq {
1346/// Constant string value to test against.
1347 /// Note that this value has type `str` (not `&str`).
1348value: ty::Value<'tcx>,
1349 },
13501351/// Tests the place against a constant using scalar equality.
1352ScalarEq { value: ty::Value<'tcx> },
13531354/// Test whether the value falls within an inclusive or exclusive range.
1355Range(Arc<PatRange<'tcx>>),
13561357/// Test that the length of the slice is `== len` or `>= len`.
1358SliceLen { len: u64, op: SliceLenOp },
13591360/// Call `Deref::deref[_mut]` on the value.
1361Deref {
1362/// Temporary to store the result of `deref()`/`deref_mut()`.
1363temp: Place<'tcx>,
1364 mutability: Mutability,
1365 },
13661367/// Assert unreachability of never patterns.
1368Never,
1369}
13701371/// Indicates the kind of slice-length constraint imposed by a slice pattern,
1372/// or its corresponding test.
1373#[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)]
1374enum SliceLenOp {
1375/// The slice pattern can only match a slice with exactly `len` elements.
1376Equal,
1377/// The slice pattern can match a slice with `len` or more elements
1378 /// (i.e. it contains a `..` subpattern in the middle).
1379GreaterOrEqual,
1380}
13811382/// The branch to be taken after a test.
1383#[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)]
1384enum TestBranch<'tcx> {
1385/// Success branch, used for tests with two possible outcomes.
1386Success,
1387/// Branch corresponding to this constant. Must be a scalar.
1388Constant(ty::Value<'tcx>),
1389/// Branch corresponding to this variant.
1390Variant(VariantIdx),
1391/// Failure branch for tests with two possible outcomes, and "otherwise" branch for other tests.
1392Failure,
1393}
13941395impl<'tcx> TestBranch<'tcx> {
1396fn as_constant(&self) -> Option<ty::Value<'tcx>> {
1397if let Self::Constant(v) = self { Some(*v) } else { None }
1398 }
1399}
14001401/// `ArmHasGuard` is a wrapper around a boolean flag. It indicates whether
1402/// a match arm has a guard expression attached to it.
1403#[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)]
1404pub(crate) struct ArmHasGuard(pub(crate) bool);
14051406///////////////////////////////////////////////////////////////////////////
1407// Main matching algorithm
14081409/// A sub-branch in the output of match lowering. Match lowering has generated MIR code that will
1410/// branch to `success_block` when the matched value matches the corresponding pattern. If there is
1411/// a guard, its failure must continue to `otherwise_block`, which will resume testing patterns.
1412#[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)]
1413struct MatchTreeSubBranch<'tcx> {
1414 span: Span,
1415/// The block that is branched to if the corresponding subpattern matches.
1416success_block: BasicBlock,
1417/// The block to branch to if this arm had a guard and the guard fails.
1418otherwise_block: BasicBlock,
1419/// The bindings to set up in this sub-branch.
1420bindings: Vec<Binding<'tcx>>,
1421/// The ascriptions to set up in this sub-branch.
1422ascriptions: Vec<Ascription<'tcx>>,
1423/// Whether the sub-branch corresponds to a never pattern.
1424is_never: bool,
1425}
14261427/// A branch in the output of match lowering.
1428#[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)]
1429struct MatchTreeBranch<'tcx> {
1430 sub_branches: Vec<MatchTreeSubBranch<'tcx>>,
1431}
14321433/// The result of generating MIR for a pattern-matching expression. Each input branch/arm/pattern
1434/// gives rise to an output `MatchTreeBranch`. If one of the patterns matches, we branch to the
1435/// corresponding `success_block`. If none of the patterns matches, we branch to `otherwise_block`.
1436///
1437/// Each branch is made of one of more sub-branches, corresponding to or-patterns. E.g.
1438/// ```ignore(illustrative)
1439/// match foo {
1440/// (x, false) | (false, x) => {}
1441/// (true, true) => {}
1442/// }
1443/// ```
1444/// Here the first arm gives the first `MatchTreeBranch`, which has two sub-branches, one for each
1445/// alternative of the or-pattern. They are kept separate because each needs to bind `x` to a
1446/// different place.
1447#[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)]
1448pub(crate) struct BuiltMatchTree<'tcx> {
1449 branches: Vec<MatchTreeBranch<'tcx>>,
1450 otherwise_block: BasicBlock,
1451/// If any of the branches had a guard, we collect here the places and locals to fakely borrow
1452 /// to ensure match guards can't modify the values as we match them. For more details, see
1453 /// [`util::collect_fake_borrows`].
1454fake_borrow_temps: Vec<(Place<'tcx>, Local, FakeBorrowKind)>,
1455}
14561457impl<'tcx> MatchTreeSubBranch<'tcx> {
1458fn from_sub_candidate(
1459 candidate: Candidate<'tcx>,
1460 parent_data: &Vec<PatternExtraData<'tcx>>,
1461 ) -> Self {
1462if true {
if !candidate.match_pairs.is_empty() {
::core::panicking::panic("assertion failed: candidate.match_pairs.is_empty()")
};
};debug_assert!(candidate.match_pairs.is_empty());
1463MatchTreeSubBranch {
1464 span: candidate.extra_data.span,
1465 success_block: candidate.pre_binding_block.unwrap(),
1466 otherwise_block: candidate.otherwise_block.unwrap(),
1467 bindings: sub_branch_bindings(parent_data, &candidate.extra_data.bindings),
1468 ascriptions: parent_data1469 .iter()
1470 .flat_map(|d| &d.ascriptions)
1471 .cloned()
1472 .chain(candidate.extra_data.ascriptions)
1473 .collect(),
1474 is_never: candidate.extra_data.is_never,
1475 }
1476 }
1477}
14781479impl<'tcx> MatchTreeBranch<'tcx> {
1480fn from_candidate(candidate: Candidate<'tcx>) -> Self {
1481let mut sub_branches = Vec::new();
1482traverse_candidate(
1483candidate,
1484&mut Vec::new(),
1485&mut |candidate: Candidate<'_>, parent_data: &mut Vec<PatternExtraData<'_>>| {
1486sub_branches.push(MatchTreeSubBranch::from_sub_candidate(candidate, parent_data));
1487 },
1488 |inner_candidate, parent_data| {
1489parent_data.push(inner_candidate.extra_data);
1490inner_candidate.subcandidates.into_iter()
1491 },
1492 |parent_data| {
1493parent_data.pop();
1494 },
1495 );
1496MatchTreeBranch { sub_branches }
1497 }
1498}
14991500/// Collects the bindings for a [`MatchTreeSubBranch`], preserving the order they appear in the
1501/// pattern, as though the or-alternatives chosen in this sub-branch were inlined.
1502fn sub_branch_bindings<'tcx>(
1503 parents: &[PatternExtraData<'tcx>],
1504 leaf_bindings: &[SubpatternBindings<'tcx>],
1505) -> Vec<Binding<'tcx>> {
1506// In the common case, all bindings will be in leaves. Allocate to fit the leaf's bindings.
1507let mut all_bindings = Vec::with_capacity(leaf_bindings.len());
1508let mut remainder = parents1509 .iter()
1510 .map(|parent| parent.bindings.as_slice())
1511 .chain([leaf_bindings])
1512// Skip over unsimplified or-patterns without bindings.
1513.filter(|bindings| !bindings.is_empty());
1514if let Some(candidate_bindings) = remainder.next() {
1515push_sub_branch_bindings(&mut all_bindings, candidate_bindings, &mut remainder);
1516 }
1517// Make sure we've included all bindings. For ill-formed patterns like `(x, _ | y)`, we may not
1518 // have collected all bindings yet, since we only check the first alternative when determining
1519 // whether to inline subcandidates' bindings.
1520 // FIXME(@dianne): prevent ill-formed patterns from getting here
1521while let Some(candidate_bindings) = remainder.next() {
1522 ty::tls::with(|tcx| {
1523 tcx.dcx().delayed_bug("mismatched or-pattern bindings but no error emitted")
1524 });
1525// To recover, we collect the rest in an arbitrary order.
1526push_sub_branch_bindings(&mut all_bindings, candidate_bindings, &mut remainder);
1527 }
1528all_bindings1529}
15301531/// Helper for [`sub_branch_bindings`]. Collects bindings from `candidate_bindings` into
1532/// `flattened`. Bindings in or-patterns are collected recursively from `remainder`.
1533fn push_sub_branch_bindings<'c, 'tcx: 'c>(
1534 flattened: &mut Vec<Binding<'tcx>>,
1535 candidate_bindings: &'c [SubpatternBindings<'tcx>],
1536 remainder: &mut impl Iterator<Item = &'c [SubpatternBindings<'tcx>]>,
1537) {
1538for subpat_bindings in candidate_bindings {
1539match subpat_bindings {
1540 SubpatternBindings::One(binding) => flattened.push(*binding),
1541 SubpatternBindings::FromOrPattern => {
1542// Inline bindings from an or-pattern. By construction, this always
1543 // corresponds to a subcandidate and its closest descendants (i.e. those
1544 // from nested or-patterns, but not adjacent or-patterns). To handle
1545 // adjacent or-patterns, e.g. `(x | x, y | y)`, we update the `remainder` to
1546 // point to the first descendant candidate from outside this or-pattern.
1547if let Some(subcandidate_bindings) = remainder.next() {
1548 push_sub_branch_bindings(flattened, subcandidate_bindings, remainder);
1549 } else {
1550// For ill-formed patterns like `x | _`, we may not have any subcandidates left
1551 // to inline bindings from.
1552 // FIXME(@dianne): prevent ill-formed patterns from getting here
1553ty::tls::with(|tcx| {
1554 tcx.dcx().delayed_bug("mismatched or-pattern bindings but no error emitted")
1555 });
1556 };
1557 }
1558 }
1559 }
1560}
15611562#[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)]
1563pub(crate) enum HasMatchGuard {
1564 Yes,
1565 No,
1566}
15671568impl<'a, 'tcx> Builder<'a, 'tcx> {
1569/// The entrypoint of the matching algorithm. Create the decision tree for the match expression,
1570 /// starting from `block`.
1571 ///
1572 /// `patterns` is a list of patterns, one for each arm. The associated boolean indicates whether
1573 /// the arm has a guard.
1574 ///
1575 /// `refutable` indicates whether the candidate list is refutable (for `if let` and `let else`)
1576 /// or not (for `let` and `match`). In the refutable case we return the block to which we branch
1577 /// on failure.
1578pub(crate) fn lower_match_tree(
1579&mut self,
1580 block: BasicBlock,
1581 scrutinee_span: Span,
1582 scrutinee_place_builder: &PlaceBuilder<'tcx>,
1583 match_start_span: Span,
1584 patterns: Vec<(&Pat<'tcx>, HasMatchGuard)>,
1585 refutable: bool,
1586 ) -> BuiltMatchTree<'tcx> {
1587// Assemble the initial list of candidates. These top-level candidates are 1:1 with the
1588 // input patterns, but other parts of match lowering also introduce subcandidates (for
1589 // sub-or-patterns). So inside the algorithm, the candidates list may not correspond to
1590 // match arms directly.
1591let mut candidates: Vec<Candidate<'_>> = patterns1592 .into_iter()
1593 .map(|(pat, has_guard)| {
1594Candidate::new(scrutinee_place_builder.clone(), pat, has_guard, self)
1595 })
1596 .collect();
15971598let fake_borrow_temps = util::collect_fake_borrows(
1599self,
1600&candidates,
1601scrutinee_span,
1602scrutinee_place_builder.base(),
1603 );
16041605// This will generate code to test scrutinee_place and branch to the appropriate arm block.
1606 // If none of the arms match, we branch to `otherwise_block`. When lowering a `match`
1607 // expression, exhaustiveness checking ensures that this block is unreachable.
1608let mut candidate_refs = candidates.iter_mut().collect::<Vec<_>>();
1609let otherwise_block =
1610self.match_candidates(match_start_span, scrutinee_span, block, &mut candidate_refs);
16111612// Set up false edges so that the borrow-checker cannot make use of the specific CFG we
1613 // generated. We falsely branch from each candidate to the one below it to make it as if we
1614 // were testing match branches one by one in order. In the refutable case we also want a
1615 // false edge to the final failure block.
1616let mut next_candidate_start_block = if refutable { Some(otherwise_block) } else { None };
1617for candidate in candidates.iter_mut().rev() {
1618let has_guard = candidate.has_guard;
1619 candidate.visit_leaves_rev(|leaf_candidate| {
1620if let Some(next_candidate_start_block) = next_candidate_start_block {
1621let source_info = self.source_info(leaf_candidate.extra_data.span);
1622// Falsely branch to `next_candidate_start_block` before reaching pre_binding.
1623let old_pre_binding = leaf_candidate.pre_binding_block.unwrap();
1624let new_pre_binding = self.cfg.start_new_block();
1625self.false_edges(
1626 old_pre_binding,
1627 new_pre_binding,
1628 next_candidate_start_block,
1629 source_info,
1630 );
1631 leaf_candidate.pre_binding_block = Some(new_pre_binding);
1632if has_guard {
1633// Falsely branch to `next_candidate_start_block` also if the guard fails.
1634let new_otherwise = self.cfg.start_new_block();
1635let old_otherwise = leaf_candidate.otherwise_block.unwrap();
1636self.false_edges(
1637 new_otherwise,
1638 old_otherwise,
1639 next_candidate_start_block,
1640 source_info,
1641 );
1642 leaf_candidate.otherwise_block = Some(new_otherwise);
1643 }
1644 }
1645if !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());
1646 next_candidate_start_block = leaf_candidate.false_edge_start_block;
1647 });
1648 }
16491650if !refutable {
1651// Match checking ensures `otherwise_block` is actually unreachable in irrefutable
1652 // cases.
1653let source_info = self.source_info(scrutinee_span);
16541655// Matching on a scrutinee place of an uninhabited type doesn't generate any memory
1656 // reads by itself, and so if the place is uninitialized we wouldn't know. In order to
1657 // disallow the following:
1658 // ```rust
1659 // let x: !;
1660 // match x {}
1661 // ```
1662 // we add a dummy read on the place.
1663 //
1664 // NOTE: If we require never patterns for empty matches, those will check that the place
1665 // is initialized, and so this read would no longer be needed.
1666let cause_matched_place = FakeReadCause::ForMatchedPlace(None);
16671668if let Some(scrutinee_place) = scrutinee_place_builder.try_to_place(self) {
1669self.cfg.push_fake_read(
1670otherwise_block,
1671source_info,
1672cause_matched_place,
1673scrutinee_place,
1674 );
1675 }
16761677self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
1678 }
16791680BuiltMatchTree {
1681 branches: candidates.into_iter().map(MatchTreeBranch::from_candidate).collect(),
1682otherwise_block,
1683fake_borrow_temps,
1684 }
1685 }
16861687/// The main match algorithm. It begins with a set of candidates `candidates` and has the job of
1688 /// generating code that branches to an appropriate block if the scrutinee matches one of these
1689 /// candidates. The
1690 /// candidates are ordered such that the first item in the list
1691 /// has the highest priority. When a candidate is found to match
1692 /// the value, we will set and generate a branch to the appropriate
1693 /// pre-binding block.
1694 ///
1695 /// If none of the candidates apply, we continue to the returned `otherwise_block`.
1696 ///
1697 /// Note that while `match` expressions in the Rust language are exhaustive,
1698 /// candidate lists passed to this method are often _non-exhaustive_.
1699 /// For example, the match lowering process will frequently divide up the
1700 /// list of candidates, and recursively call this method with a non-exhaustive
1701 /// subset of candidates.
1702 /// See [`Builder::test_candidates`] for more details on this
1703 /// "backtracking automata" approach.
1704 ///
1705 /// For an example of how we use `otherwise_block`, consider:
1706 /// ```
1707 /// # fn foo((x, y): (bool, bool)) -> u32 {
1708 /// match (x, y) {
1709 /// (true, true) => 1,
1710 /// (_, false) => 2,
1711 /// (false, true) => 3,
1712 /// }
1713 /// # }
1714 /// ```
1715 /// For this match, we generate something like:
1716 /// ```
1717 /// # fn foo((x, y): (bool, bool)) -> u32 {
1718 /// if x {
1719 /// if y {
1720 /// return 1
1721 /// } else {
1722 /// // continue
1723 /// }
1724 /// } else {
1725 /// // continue
1726 /// }
1727 /// if y {
1728 /// if x {
1729 /// // This is actually unreachable because the `(true, true)` case was handled above,
1730 /// // but we don't know that from within the lowering algorithm.
1731 /// // continue
1732 /// } else {
1733 /// return 3
1734 /// }
1735 /// } else {
1736 /// return 2
1737 /// }
1738 /// // this is the final `otherwise_block`, which is unreachable because the match was exhaustive.
1739 /// unreachable!()
1740 /// # }
1741 /// ```
1742 ///
1743 /// Every `continue` is an instance of branching to some `otherwise_block` somewhere deep within
1744 /// the algorithm. For more details on why we lower like this, see [`Builder::test_candidates`].
1745 ///
1746 /// Note how we test `x` twice. This is the tradeoff of backtracking automata: we prefer smaller
1747 /// code size so we accept non-optimal code paths.
1748#[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(1748u32),
::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")]1749fn match_candidates(
1750&mut self,
1751 span: Span,
1752 scrutinee_span: Span,
1753 start_block: BasicBlock,
1754 candidates: &mut [&mut Candidate<'tcx>],
1755 ) -> BasicBlock {
1756 ensure_sufficient_stack(|| {
1757self.match_candidates_inner(span, scrutinee_span, start_block, candidates)
1758 })
1759 }
17601761/// Construct the decision tree for `candidates`. Don't call this, call `match_candidates`
1762 /// instead to reserve sufficient stack space.
1763fn match_candidates_inner(
1764&mut self,
1765 span: Span,
1766 scrutinee_span: Span,
1767mut start_block: BasicBlock,
1768 candidates: &mut [&mut Candidate<'tcx>],
1769 ) -> BasicBlock {
1770if let [first, ..] = candidates {
1771if first.false_edge_start_block.is_none() {
1772first.false_edge_start_block = Some(start_block);
1773 }
1774 }
17751776// Process a prefix of the candidates.
1777let rest = match candidates {
1778 [] => {
1779// If there are no candidates that still need testing, we're done.
1780return start_block;
1781 }
1782 [first, remaining @ ..] if first.match_pairs.is_empty() => {
1783// The first candidate has satisfied all its match pairs.
1784 // We record the blocks that will be needed by match arm lowering,
1785 // and then continue with the remaining candidates.
1786let remainder_start = self.select_matched_candidate(first, start_block);
1787remainder_start.and(remaining)
1788 }
1789 candidates if candidates.iter().any(|candidate| candidate.starts_with_or_pattern()) => {
1790// If any candidate starts with an or-pattern, we want to expand or-patterns
1791 // before we do any more tests.
1792 //
1793 // The only candidate we strictly _need_ to expand here is the first one.
1794 // But by expanding other candidates as early as possible, we unlock more
1795 // opportunities to include them in test outcomes, making the match tree
1796 // smaller and simpler.
1797self.expand_and_match_or_candidates(span, scrutinee_span, start_block, candidates)
1798 }
1799 candidates => {
1800// The first candidate has some unsatisfied match pairs; we proceed to do more tests.
1801self.test_candidates(span, scrutinee_span, candidates, start_block)
1802 }
1803 };
18041805// Process any candidates that remain.
1806let remaining_candidates = { let BlockAnd(b, v) = rest; start_block = b; v }unpack!(start_block = rest);
1807self.match_candidates(span, scrutinee_span, start_block, remaining_candidates)
1808 }
18091810/// Link up matched candidates.
1811 ///
1812 /// For example, if we have something like this:
1813 ///
1814 /// ```ignore (illustrative)
1815 /// ...
1816 /// Some(x) if cond1 => ...
1817 /// Some(x) => ...
1818 /// Some(x) if cond2 => ...
1819 /// ...
1820 /// ```
1821 ///
1822 /// We generate real edges from:
1823 ///
1824 /// * `start_block` to the [pre-binding block] of the first pattern,
1825 /// * the [otherwise block] of the first pattern to the second pattern,
1826 /// * the [otherwise block] of the third pattern to a block with an
1827 /// [`Unreachable` terminator](TerminatorKind::Unreachable).
1828 ///
1829 /// In addition, we later add fake edges from the otherwise blocks to the
1830 /// pre-binding block of the next candidate in the original set of
1831 /// candidates.
1832 ///
1833 /// [pre-binding block]: Candidate::pre_binding_block
1834 /// [otherwise block]: Candidate::otherwise_block
1835fn select_matched_candidate(
1836&mut self,
1837 candidate: &mut Candidate<'tcx>,
1838 start_block: BasicBlock,
1839 ) -> BasicBlock {
1840if !candidate.otherwise_block.is_none() {
::core::panicking::panic("assertion failed: candidate.otherwise_block.is_none()")
};assert!(candidate.otherwise_block.is_none());
1841if !candidate.pre_binding_block.is_none() {
::core::panicking::panic("assertion failed: candidate.pre_binding_block.is_none()")
};assert!(candidate.pre_binding_block.is_none());
1842if !candidate.subcandidates.is_empty() {
::core::panicking::panic("assertion failed: candidate.subcandidates.is_empty()")
};assert!(candidate.subcandidates.is_empty());
18431844candidate.pre_binding_block = Some(start_block);
1845let otherwise_block = self.cfg.start_new_block();
1846// Create the otherwise block for this candidate, which is the
1847 // pre-binding block for the next candidate.
1848candidate.otherwise_block = Some(otherwise_block);
1849otherwise_block1850 }
18511852/// Takes a list of candidates such that some of the candidates' first match pairs are
1853 /// or-patterns. This expands as many or-patterns as possible and processes the resulting
1854 /// candidates. Returns the unprocessed candidates if any.
1855fn expand_and_match_or_candidates<'b, 'c>(
1856&mut self,
1857 span: Span,
1858 scrutinee_span: Span,
1859 start_block: BasicBlock,
1860 candidates: &'b mut [&'c mut Candidate<'tcx>],
1861 ) -> BlockAnd<&'b mut [&'c mut Candidate<'tcx>]> {
1862// We can't expand or-patterns freely. The rule is:
1863 // - If a candidate doesn't start with an or-pattern, we include it in
1864 // the expansion list as-is (i.e. it "expands" to itself).
1865 // - If a candidate has an or-pattern as its only remaining match pair,
1866 // we can expand it.
1867 // - If it starts with an or-pattern but also has other match pairs,
1868 // we can expand it, but we can't process more candidates after it.
1869 //
1870 // If we didn't stop, the `otherwise` cases could get mixed up. E.g. in the
1871 // following, or-pattern simplification (in `merge_trivial_subcandidates`) makes it
1872 // so the `1` and `2` cases branch to a same block (which then tests `false`). If we
1873 // took `(2, _)` in the same set of candidates, when we reach the block that tests
1874 // `false` we don't know whether we came from `1` or `2`, hence we can't know where
1875 // to branch on failure.
1876 //
1877 // ```ignore(illustrative)
1878 // match (1, true) {
1879 // (1 | 2, false) => {},
1880 // (2, _) => {},
1881 // _ => {}
1882 // }
1883 // ```
1884 //
1885 // We therefore split the `candidates` slice in two, expand or-patterns in the first part,
1886 // and process the rest separately.
1887let expand_until = candidates1888 .iter()
1889 .position(|candidate| {
1890// If a candidate starts with an or-pattern and has more match pairs,
1891 // we can expand it, but we must stop expanding _after_ it.
1892candidate.match_pairs.len() > 1 && candidate.starts_with_or_pattern()
1893 })
1894 .map(|pos| pos + 1) // Stop _after_ the found candidate
1895.unwrap_or(candidates.len()); // Otherwise, include all candidates
1896let (candidates_to_expand, remaining_candidates) = candidates.split_at_mut(expand_until);
18971898// Expand one level of or-patterns for each candidate in `candidates_to_expand`.
1899 // We take care to preserve the relative ordering of candidates, so that
1900 // or-patterns are expanded in their parent's relative position.
1901let mut expanded_candidates = Vec::new();
1902for candidate in candidates_to_expand.iter_mut() {
1903if candidate.starts_with_or_pattern() {
1904let or_match_pair = candidate.match_pairs.remove(0);
1905// Expand the or-pattern into subcandidates.
1906self.create_or_subcandidates(candidate, or_match_pair);
1907// Collect the newly created subcandidates.
1908for subcandidate in candidate.subcandidates.iter_mut() {
1909 expanded_candidates.push(subcandidate);
1910 }
1911// Note that the subcandidates have been added to `expanded_candidates`,
1912 // but `candidate` itself has not. If the last candidate has more match pairs,
1913 // they are handled separately by `test_remaining_match_pairs_after_or`.
1914} else {
1915// A candidate that doesn't start with an or-pattern has nothing to
1916 // expand, so it is included in the post-expansion list as-is.
1917expanded_candidates.push(candidate);
1918 }
1919 }
19201921// Recursively lower the part of the match tree represented by the
1922 // expanded candidates. This is where subcandidates actually get lowered!
1923let remainder_start = self.match_candidates(
1924span,
1925scrutinee_span,
1926start_block,
1927expanded_candidates.as_mut_slice(),
1928 );
19291930// Postprocess subcandidates, and process any leftover match pairs.
1931 // (Only the last candidate can possibly have more match pairs.)
1932if 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!({
1933let mut all_except_last = candidates_to_expand.iter().rev().skip(1);
1934 all_except_last.all(|candidate| candidate.match_pairs.is_empty())
1935 });
1936for candidate in candidates_to_expand.iter_mut() {
1937if !candidate.subcandidates.is_empty() {
1938self.merge_trivial_subcandidates(candidate);
1939self.remove_never_subcandidates(candidate);
1940 }
1941 }
1942// It's important to perform the above simplifications _before_ dealing
1943 // with remaining match pairs, to avoid exponential blowup if possible
1944 // (for trivial or-patterns), and avoid useless work (for never patterns).
1945if let Some(last_candidate) = candidates_to_expand.last_mut() {
1946self.test_remaining_match_pairs_after_or(span, scrutinee_span, last_candidate);
1947 }
19481949remainder_start.and(remaining_candidates)
1950 }
19511952/// Given a match-pair that corresponds to an or-pattern, expand each subpattern into a new
1953 /// subcandidate. Any candidate that has been expanded this way should also be postprocessed
1954 /// at the end of [`Self::expand_and_match_or_candidates`].
1955fn create_or_subcandidates(
1956&mut self,
1957 candidate: &mut Candidate<'tcx>,
1958 match_pair: MatchPairTree<'tcx>,
1959 ) {
1960let TestableCase::Or { pats } = match_pair.testable_case else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1961{
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:1961",
"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(1961u32),
::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);
1962candidate.or_span = Some(match_pair.pattern_span);
1963candidate.subcandidates = pats1964 .into_iter()
1965 .map(|flat_pat| Candidate::from_flat_pat(flat_pat, candidate.has_guard))
1966 .collect();
1967candidate.subcandidates[0].false_edge_start_block = candidate.false_edge_start_block;
1968 }
19691970/// Try to merge all of the subcandidates of the given candidate into one. This avoids
1971 /// exponentially large CFGs in cases like `(1 | 2, 3 | 4, ...)`. The candidate should have been
1972 /// expanded with `create_or_subcandidates`.
1973 ///
1974 /// Given a pattern `(P | Q, R | S)` we (in principle) generate a CFG like
1975 /// so:
1976 ///
1977 /// ```text
1978 /// [ start ]
1979 /// |
1980 /// [ match P, Q ]
1981 /// |
1982 /// +----------------------------------------+------------------------------------+
1983 /// | | |
1984 /// V V V
1985 /// [ P matches ] [ Q matches ] [ otherwise ]
1986 /// | | |
1987 /// V V |
1988 /// [ match R, S ] [ match R, S ] |
1989 /// | | |
1990 /// +--------------+------------+ +--------------+------------+ |
1991 /// | | | | | | |
1992 /// V V V V V V |
1993 /// [ R matches ] [ S matches ] [otherwise ] [ R matches ] [ S matches ] [otherwise ] |
1994 /// | | | | | | |
1995 /// +--------------+------------|------------+--------------+ | |
1996 /// | | | |
1997 /// | +----------------------------------------+--------+
1998 /// | |
1999 /// V V
2000 /// [ Success ] [ Failure ]
2001 /// ```
2002 ///
2003 /// In practice there are some complications:
2004 ///
2005 /// * If there's a guard, then the otherwise branch of the first match on
2006 /// `R | S` goes to a test for whether `Q` matches, and the control flow
2007 /// doesn't merge into a single success block until after the guard is
2008 /// tested.
2009 /// * If neither `P` or `Q` has any bindings or type ascriptions and there
2010 /// isn't a match guard, then we create a smaller CFG like:
2011 ///
2012 /// ```text
2013 /// ...
2014 /// +---------------+------------+
2015 /// | | |
2016 /// [ P matches ] [ Q matches ] [ otherwise ]
2017 /// | | |
2018 /// +---------------+ |
2019 /// | ...
2020 /// [ match R, S ]
2021 /// |
2022 /// ...
2023 /// ```
2024 ///
2025 /// Note that this takes place _after_ the subcandidates have participated
2026 /// in match tree lowering.
2027fn merge_trivial_subcandidates(&mut self, candidate: &mut Candidate<'tcx>) {
2028if !!candidate.subcandidates.is_empty() {
::core::panicking::panic("assertion failed: !candidate.subcandidates.is_empty()")
};assert!(!candidate.subcandidates.is_empty());
2029if candidate.has_guard {
2030// FIXME(or_patterns; matthewjasper) Don't give up if we have a guard.
2031return;
2032 }
20332034// FIXME(or_patterns; matthewjasper) Try to be more aggressive here.
2035let can_merge = candidate.subcandidates.iter().all(|subcandidate| {
2036subcandidate.subcandidates.is_empty() && subcandidate.extra_data.is_empty()
2037 });
2038if !can_merge {
2039return;
2040 }
20412042let mut last_otherwise = None;
2043let shared_pre_binding_block = self.cfg.start_new_block();
2044// This candidate is about to become a leaf, so unset `or_span`.
2045let or_span = candidate.or_span.take().unwrap();
2046let source_info = self.source_info(or_span);
20472048if candidate.false_edge_start_block.is_none() {
2049candidate.false_edge_start_block = candidate.subcandidates[0].false_edge_start_block;
2050 }
20512052// Remove the (known-trivial) subcandidates from the candidate tree,
2053 // so that they aren't visible after match tree lowering, and wire them
2054 // all to join up at a single shared pre-binding block.
2055 // (Note that the subcandidates have already had their part of the match
2056 // tree lowered by this point, which is why we can add a goto to them.)
2057for subcandidate in mem::take(&mut candidate.subcandidates) {
2058let subcandidate_block = subcandidate.pre_binding_block.unwrap();
2059self.cfg.goto(subcandidate_block, source_info, shared_pre_binding_block);
2060 last_otherwise = subcandidate.otherwise_block;
2061 }
2062candidate.pre_binding_block = Some(shared_pre_binding_block);
2063if !last_otherwise.is_some() {
::core::panicking::panic("assertion failed: last_otherwise.is_some()")
};assert!(last_otherwise.is_some());
2064candidate.otherwise_block = last_otherwise;
2065 }
20662067/// Never subcandidates may have a set of bindings inconsistent with their siblings,
2068 /// which would break later code. So we filter them out. Note that we can't filter out
2069 /// top-level candidates this way.
2070fn remove_never_subcandidates(&mut self, candidate: &mut Candidate<'tcx>) {
2071if candidate.subcandidates.is_empty() {
2072return;
2073 }
20742075let false_edge_start_block = candidate.subcandidates[0].false_edge_start_block;
2076candidate.subcandidates.retain_mut(|candidate| {
2077if candidate.extra_data.is_never {
2078candidate.visit_leaves(|subcandidate| {
2079let block = subcandidate.pre_binding_block.unwrap();
2080// That block is already unreachable but needs a terminator to make the MIR well-formed.
2081let source_info = self.source_info(subcandidate.extra_data.span);
2082self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
2083 });
2084false
2085} else {
2086true
2087}
2088 });
2089if candidate.subcandidates.is_empty() {
2090// If `candidate` has become a leaf candidate, ensure it has a `pre_binding_block` and `otherwise_block`.
2091let next_block = self.cfg.start_new_block();
2092candidate.pre_binding_block = Some(next_block);
2093candidate.otherwise_block = Some(next_block);
2094// In addition, if `candidate` doesn't have `false_edge_start_block`, it should be assigned here.
2095if candidate.false_edge_start_block.is_none() {
2096candidate.false_edge_start_block = false_edge_start_block;
2097 }
2098 }
2099 }
21002101/// If more match pairs remain, test them after each subcandidate.
2102 /// We could have added them to the or-candidates during or-pattern expansion, but that
2103 /// would make it impossible to detect simplifiable or-patterns. That would guarantee
2104 /// exponentially large CFGs for cases like `(1 | 2, 3 | 4, ...)`.
2105fn test_remaining_match_pairs_after_or(
2106&mut self,
2107 span: Span,
2108 scrutinee_span: Span,
2109 candidate: &mut Candidate<'tcx>,
2110 ) {
2111if candidate.match_pairs.is_empty() {
2112return;
2113 }
21142115let or_span = candidate.or_span.unwrap_or(candidate.extra_data.span);
2116let source_info = self.source_info(or_span);
2117let mut last_otherwise = None;
2118candidate.visit_leaves(|leaf_candidate| {
2119last_otherwise = leaf_candidate.otherwise_block;
2120 });
21212122let remaining_match_pairs = mem::take(&mut candidate.match_pairs);
2123// We're testing match pairs that remained after an `Or`, so the remaining
2124 // pairs should all be `Or` too, due to the sorting invariant.
2125if 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!(
2126 remaining_match_pairs
2127 .iter()
2128 .all(|match_pair| matches!(match_pair.testable_case, TestableCase::Or { .. }))
2129 );
21302131// Visit each leaf candidate within this subtree, add a copy of the remaining
2132 // match pairs to it, and then recursively lower the rest of the match tree
2133 // from that point.
2134candidate.visit_leaves(|leaf_candidate| {
2135// At this point the leaf's own match pairs have all been lowered
2136 // and removed, so `extend` and assignment are equivalent,
2137 // but extending can also recycle any existing vector capacity.
2138if !leaf_candidate.match_pairs.is_empty() {
::core::panicking::panic("assertion failed: leaf_candidate.match_pairs.is_empty()")
};assert!(leaf_candidate.match_pairs.is_empty());
2139leaf_candidate.match_pairs.extend(remaining_match_pairs.iter().cloned());
21402141let or_start = leaf_candidate.pre_binding_block.unwrap();
2142let otherwise =
2143self.match_candidates(span, scrutinee_span, or_start, &mut [leaf_candidate]);
2144// In a case like `(P | Q, R | S)`, if `P` succeeds and `R | S` fails, we know `(Q,
2145 // R | S)` will fail too. If there is no guard, we skip testing of `Q` by branching
2146 // directly to `last_otherwise`. If there is a guard,
2147 // `leaf_candidate.otherwise_block` can be reached by guard failure as well, so we
2148 // can't skip `Q`.
2149let or_otherwise = if leaf_candidate.has_guard {
2150leaf_candidate.otherwise_block.unwrap()
2151 } else {
2152last_otherwise.unwrap()
2153 };
2154self.cfg.goto(otherwise, source_info, or_otherwise);
2155 });
2156 }
21572158/// Pick a test to run. Which test doesn't matter as long as it is guaranteed to fully match at
2159 /// least one match pair. We currently simply pick the test corresponding to the first match
2160 /// pair of the first candidate in the list.
2161 ///
2162 /// *Note:* taking the first match pair is somewhat arbitrary, and we might do better here by
2163 /// choosing more carefully what to test.
2164 ///
2165 /// For example, consider the following possible match-pairs:
2166 ///
2167 /// 1. `x @ Some(P)` -- we will do a [`Switch`] to decide what variant `x` has
2168 /// 2. `x @ 22` -- we will do a [`SwitchInt`] to decide what value `x` has
2169 /// 3. `x @ 3..5` -- we will do a [`Range`] test to decide what range `x` falls in
2170 /// 4. etc.
2171 ///
2172 /// [`Switch`]: TestKind::Switch
2173 /// [`SwitchInt`]: TestKind::SwitchInt
2174 /// [`Range`]: TestKind::Range
2175fn pick_test(&mut self, candidates: &[&mut Candidate<'tcx>]) -> (Place<'tcx>, Test<'tcx>) {
2176// Extract the match-pair from the highest priority candidate
2177let match_pair = &candidates[0].match_pairs[0];
2178let test = self.pick_test_for_match_pair(match_pair);
2179// Unwrap is ok after simplification.
2180let match_place = match_pair.place.unwrap();
2181{
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:2181",
"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(2181u32),
::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);
21822183 (match_place, test)
2184 }
21852186/// This is the most subtle part of the match lowering algorithm. At this point, there are
2187 /// no fully-satisfied candidates, and no or-patterns to expand, so we actually need to
2188 /// perform some sort of test to make progress.
2189 ///
2190 /// Once we pick what sort of test we are going to perform, this test will help us winnow down
2191 /// our candidates. So we walk over the candidates (from high to low priority) and check. We
2192 /// compute, for each outcome of the test, a list of (modified) candidates. If a candidate
2193 /// matches in exactly one branch of our test, we add it to the corresponding outcome. We also
2194 /// **mutate its list of match pairs** if appropriate, to reflect the fact that we know which
2195 /// outcome occurred.
2196 ///
2197 /// For example, if we are testing `x.0`'s variant, and we have a candidate `(x.0 @ Some(v), x.1
2198 /// @ 22)`, then we would have a resulting candidate of `((x.0 as Some).0 @ v, x.1 @ 22)` in the
2199 /// branch corresponding to `Some`. To ensure we make progress, we always pick a test that
2200 /// results in simplifying the first candidate.
2201 ///
2202 /// But there may also be candidates that the test doesn't
2203 /// apply to. The classical example is wildcards:
2204 ///
2205 /// ```
2206 /// # let (x, y, z) = (true, true, true);
2207 /// match (x, y, z) {
2208 /// (true , _ , true ) => true, // (0)
2209 /// (false, false, _ ) => false, // (1)
2210 /// (_ , true , _ ) => true, // (2)
2211 /// (true , _ , false) => false, // (3)
2212 /// }
2213 /// # ;
2214 /// ```
2215 ///
2216 /// Here, the traditional "decision tree" method would generate 2 separate code-paths for the 2
2217 /// possible values of `x`. This would however duplicate some candidates, which would need to be
2218 /// lowered several times.
2219 ///
2220 /// In some cases, this duplication can create an exponential amount of
2221 /// code. This is most easily seen by noticing that this method terminates
2222 /// with precisely the reachable arms being reachable - but that problem
2223 /// is trivially NP-complete:
2224 ///
2225 /// ```ignore (illustrative)
2226 /// match (var0, var1, var2, var3, ...) {
2227 /// (true , _ , _ , false, true, ...) => false,
2228 /// (_ , true, true , false, _ , ...) => false,
2229 /// (false, _ , false, false, _ , ...) => false,
2230 /// ...
2231 /// _ => true
2232 /// }
2233 /// ```
2234 ///
2235 /// Here the last arm is reachable only if there is an assignment to
2236 /// the variables that does not match any of the literals. Therefore,
2237 /// compilation would take an exponential amount of time in some cases.
2238 ///
2239 /// In rustc, we opt instead for the "backtracking automaton" approach. This guarantees we never
2240 /// duplicate a candidate (except in the presence of or-patterns). In fact this guarantee is
2241 /// ensured by the fact that we carry around `&mut Candidate`s which can't be duplicated.
2242 ///
2243 /// To make this work, whenever we decide to perform a test, if we encounter a candidate that
2244 /// could match in more than one branch of the test, we stop. We generate code for the test and
2245 /// for the candidates in its branches; the remaining candidates will be tested if the
2246 /// candidates in the branches fail to match.
2247 ///
2248 /// For example, if we test on `x` in the following:
2249 /// ```
2250 /// # fn foo((x, y, z): (bool, bool, bool)) -> u32 {
2251 /// match (x, y, z) {
2252 /// (true , _ , true ) => 0,
2253 /// (false, false, _ ) => 1,
2254 /// (_ , true , _ ) => 2,
2255 /// (true , _ , false) => 3,
2256 /// }
2257 /// # }
2258 /// ```
2259 /// this function generates code that looks more of less like:
2260 /// ```
2261 /// # fn foo((x, y, z): (bool, bool, bool)) -> u32 {
2262 /// if x {
2263 /// match (y, z) {
2264 /// (_, true) => return 0,
2265 /// _ => {} // continue matching
2266 /// }
2267 /// } else {
2268 /// match (y, z) {
2269 /// (false, _) => return 1,
2270 /// _ => {} // continue matching
2271 /// }
2272 /// }
2273 /// // the block here is `remainder_start`
2274 /// match (x, y, z) {
2275 /// (_ , true , _ ) => 2,
2276 /// (true , _ , false) => 3,
2277 /// _ => unreachable!(),
2278 /// }
2279 /// # }
2280 /// ```
2281 ///
2282 /// We return the unprocessed candidates.
2283fn test_candidates<'b, 'c>(
2284&mut self,
2285 span: Span,
2286 scrutinee_span: Span,
2287 candidates: &'b mut [&'c mut Candidate<'tcx>],
2288 start_block: BasicBlock,
2289 ) -> BlockAnd<&'b mut [&'c mut Candidate<'tcx>]> {
2290// Choose a match pair from the first candidate, and use it to determine a
2291 // test to perform that will confirm or refute that match pair.
2292let (match_place, test) = self.pick_test(candidates);
22932294// For each of the N possible test outcomes, build the vector of candidates that applies if
2295 // the test has that particular outcome. This also mutates the candidates to remove match
2296 // pairs that are fully satisfied by the relevant outcome.
2297let PartitionedCandidates { target_candidates, remaining_candidates } =
2298self.partition_candidates_into_buckets(match_place, &test, candidates);
22992300// The block that we should branch to if none of the `target_candidates` match.
2301let remainder_start = self.cfg.start_new_block();
23022303// For each outcome of the test, recursively lower the rest of the match tree
2304 // from that point. (Note that we haven't lowered the actual test yet!)
2305let target_blocks: FxIndexMap<_, _> = target_candidates2306 .into_iter()
2307 .map(|(branch, mut candidates)| {
2308let branch_start = self.cfg.start_new_block();
2309// Recursively lower the rest of the match tree after the relevant outcome.
2310let branch_otherwise =
2311self.match_candidates(span, scrutinee_span, branch_start, &mut *candidates);
23122313// Link up the `otherwise` block of the subtree to `remainder_start`.
2314let source_info = self.source_info(span);
2315self.cfg.goto(branch_otherwise, source_info, remainder_start);
2316 (branch, branch_start)
2317 })
2318 .collect();
23192320// Perform the chosen test, branching to one of the N subtrees prepared above
2321 // (or to `remainder_start` if no outcome was satisfied).
2322self.perform_test(
2323span,
2324scrutinee_span,
2325start_block,
2326remainder_start,
2327match_place,
2328&test,
2329target_blocks,
2330 );
23312332remainder_start.and(remaining_candidates)
2333 }
2334}
23352336///////////////////////////////////////////////////////////////////////////
2337// Pat binding - used for `let` and function parameters as well.
23382339impl<'a, 'tcx> Builder<'a, 'tcx> {
2340/// Lowers a `let` expression that appears in a suitable context
2341 /// (e.g. an `if` condition or match guard).
2342 ///
2343 /// Also used for lowering let-else statements, since they have similar
2344 /// needs despite not actually using `let` expressions.
2345 ///
2346 /// Use [`DeclareLetBindings`] to control whether the `let` bindings are
2347 /// declared or not.
2348pub(crate) fn lower_let_expr(
2349&mut self,
2350mut block: BasicBlock,
2351 expr_id: ExprId,
2352 pat: &Pat<'tcx>,
2353 source_scope: Option<SourceScope>,
2354 scope_span: Span,
2355 declare_let_bindings: DeclareLetBindings,
2356 ) -> BlockAnd<()> {
2357let expr_span = self.thir[expr_id].span;
2358let 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));
2359let built_tree = self.lower_match_tree(
2360block,
2361expr_span,
2362&scrutinee,
2363pat.span,
2364<[_]>::into_vec(::alloc::boxed::box_new([(pat, HasMatchGuard::No)]))vec![(pat, HasMatchGuard::No)],
2365true,
2366 );
2367let [branch] = built_tree.branches.try_into().unwrap();
23682369self.break_for_else(built_tree.otherwise_block, self.source_info(expr_span));
23702371match declare_let_bindings {
2372 DeclareLetBindings::Yes => {
2373let expr_place = scrutinee.try_to_place(self);
2374let opt_expr_place = expr_place.as_ref().map(|place| (Some(place), expr_span));
2375self.declare_bindings(
2376source_scope,
2377pat.span.to(scope_span),
2378pat,
2379None,
2380opt_expr_place,
2381 );
2382 }
2383 DeclareLetBindings::No => {} // Caller is responsible for bindings.
2384DeclareLetBindings::LetNotPermitted => {
2385self.tcx.dcx().span_bug(expr_span, "let expression not expected in this context")
2386 }
2387 }
23882389let success = self.bind_pattern(self.source_info(pat.span), branch, &[], expr_span, None);
23902391// If branch coverage is enabled, record this branch.
2392self.visit_coverage_conditional_let(pat, success, built_tree.otherwise_block);
23932394success.unit()
2395 }
23962397/// Initializes each of the bindings from the candidate by
2398 /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
2399 /// any, and then branches to the arm. Returns the block for the case where
2400 /// the guard succeeds.
2401 ///
2402 /// Note: we do not check earlier that if there is a guard,
2403 /// there cannot be move bindings. We avoid a use-after-move by only
2404 /// moving the binding once the guard has evaluated to true (see below).
2405fn bind_and_guard_matched_candidate(
2406&mut self,
2407 sub_branch: MatchTreeSubBranch<'tcx>,
2408 fake_borrows: &[(Place<'tcx>, Local, FakeBorrowKind)],
2409 scrutinee_span: Span,
2410 arm_match_scope: Option<(&Arm<'tcx>, region::Scope)>,
2411 schedule_drops: ScheduleDrops,
2412 ) -> BasicBlock {
2413{
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:2413",
"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(2413u32),
::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);
24142415let block = sub_branch.success_block;
24162417if sub_branch.is_never {
2418// This arm has a dummy body, we don't need to generate code for it. `block` is already
2419 // unreachable (except via false edge).
2420let source_info = self.source_info(sub_branch.span);
2421self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
2422return self.cfg.start_new_block();
2423 }
24242425self.ascribe_types(block, sub_branch.ascriptions);
24262427// Lower an instance of the arm guard (if present) for this candidate,
2428 // and then perform bindings for the arm body.
2429if let Some((arm, match_scope)) = arm_match_scope2430 && let Some(guard) = arm.guard
2431 {
2432let tcx = self.tcx;
24332434// Bindings for guards require some extra handling to automatically
2435 // insert implicit references/dereferences.
2436 // This always schedules storage drops, so we may need to unschedule them below.
2437self.bind_matched_candidate_for_guard(block, sub_branch.bindings.iter());
2438let guard_frame = GuardFrame {
2439 locals: sub_branch2440 .bindings
2441 .iter()
2442 .map(|b| GuardFrameLocal::new(b.var_id))
2443 .collect(),
2444 };
2445{
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:2445",
"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(2445u32),
::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);
2446self.guard_context.push(guard_frame);
24472448let re_erased = tcx.lifetimes.re_erased;
2449let scrutinee_source_info = self.source_info(scrutinee_span);
2450for &(place, temp, kind) in fake_borrows {
2451let borrow = Rvalue::Ref(re_erased, BorrowKind::Fake(kind), place);
2452self.cfg.push_assign(block, scrutinee_source_info, Place::from(temp), borrow);
2453 }
24542455let mut guard_span = rustc_span::DUMMY_SP;
24562457let (post_guard_block, otherwise_post_guard_block) =
2458self.in_if_then_scope(match_scope, guard_span, |this| {
2459guard_span = this.thir[guard].span;
2460this.then_else_break(
2461block,
2462guard,
2463None, // Use `self.local_scope()` as the temp scope
2464this.source_info(arm.span),
2465 DeclareLetBindings::No, // For guards, `let` bindings are declared separately
2466)
2467 });
24682469// If this isn't the final sub-branch being lowered, we need to unschedule drops of
2470 // bindings and temporaries created for and by the guard. As a result, the drop order
2471 // for the arm will correspond to the binding order of the final sub-branch lowered.
2472if #[allow(non_exhaustive_omitted_patterns)] match schedule_drops {
ScheduleDrops::No => true,
_ => false,
}matches!(schedule_drops, ScheduleDrops::No) {
2473self.clear_match_arm_and_guard_scopes(arm.scope);
2474 }
24752476let source_info = self.source_info(guard_span);
2477let guard_end = self.source_info(tcx.sess.source_map().end_point(guard_span));
2478let guard_frame = self.guard_context.pop().unwrap();
2479{
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:2479",
"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(2479u32),
::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);
24802481for &(_, temp, _) in fake_borrows {
2482let cause = FakeReadCause::ForMatchGuard;
2483self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
2484 }
24852486self.cfg.goto(otherwise_post_guard_block, source_info, sub_branch.otherwise_block);
24872488// We want to ensure that the matched candidates are bound
2489 // after we have confirmed this candidate *and* any
2490 // associated guard; Binding them on `block` is too soon,
2491 // because that would be before we've checked the result
2492 // from the guard.
2493 //
2494 // But binding them on the arm is *too late*, because
2495 // then all of the candidates for a single arm would be
2496 // bound in the same place, that would cause a case like:
2497 //
2498 // ```rust
2499 // match (30, 2) {
2500 // (mut x, 1) | (2, mut x) if { true } => { ... }
2501 // ... // ^^^^^^^ (this is `arm_block`)
2502 // }
2503 // ```
2504 //
2505 // would yield an `arm_block` something like:
2506 //
2507 // ```
2508 // StorageLive(_4); // _4 is `x`
2509 // _4 = &mut (_1.0: i32); // this is handling `(mut x, 1)` case
2510 // _4 = &mut (_1.1: i32); // this is handling `(2, mut x)` case
2511 // ```
2512 //
2513 // and that is clearly not correct.
2514let by_value_bindings = sub_branch2515 .bindings
2516 .iter()
2517 .filter(|binding| #[allow(non_exhaustive_omitted_patterns)] match binding.binding_mode.0 {
ByRef::No => true,
_ => false,
}matches!(binding.binding_mode.0, ByRef::No));
2518// Read all of the by reference bindings to ensure that the
2519 // place they refer to can't be modified by the guard.
2520for binding in by_value_bindings.clone() {
2521let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
2522let cause = FakeReadCause::ForGuardBinding;
2523self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
2524 }
2525// Only schedule drops for the last sub-branch we lower.
2526self.bind_matched_candidate_for_arm_body(
2527post_guard_block,
2528schedule_drops,
2529by_value_bindings,
2530 );
25312532post_guard_block2533 } else {
2534// (Here, it is not too early to bind the matched
2535 // candidate on `block`, because there is no guard result
2536 // that we have to inspect before we bind them.)
2537self.bind_matched_candidate_for_arm_body(
2538block,
2539schedule_drops,
2540sub_branch.bindings.iter(),
2541 );
2542block2543 }
2544 }
25452546/// Append `AscribeUserType` statements onto the end of `block`
2547 /// for each ascription
2548fn ascribe_types(
2549&mut self,
2550 block: BasicBlock,
2551 ascriptions: impl IntoIterator<Item = Ascription<'tcx>>,
2552 ) {
2553for ascription in ascriptions {
2554let source_info = self.source_info(ascription.annotation.span);
25552556let base = self.canonical_user_type_annotations.push(ascription.annotation);
2557self.cfg.push(
2558 block,
2559 Statement::new(
2560 source_info,
2561 StatementKind::AscribeUserType(
2562 Box::new((
2563 ascription.source,
2564 UserTypeProjection { base, projs: Vec::new() },
2565 )),
2566 ascription.variance,
2567 ),
2568 ),
2569 );
2570 }
2571 }
25722573/// Binding for guards is a bit different from binding for the arm body,
2574 /// because an extra layer of implicit reference/dereference is added.
2575 ///
2576 /// The idea is that any pattern bindings of type T will map to a `&T` within
2577 /// the context of the guard expression, but will continue to map to a `T`
2578 /// in the context of the arm body. To avoid surfacing this distinction in
2579 /// the user source code (which would be a severe change to the language and
2580 /// require far more revision to the compiler), any occurrence of the
2581 /// identifier in the guard expression will automatically get a deref op
2582 /// applied to it. (See the caller of [`Self::is_bound_var_in_guard`].)
2583 ///
2584 /// So an input like:
2585 ///
2586 /// ```ignore (illustrative)
2587 /// let place = Foo::new();
2588 /// match place { foo if inspect(foo)
2589 /// => feed(foo), ... }
2590 /// ```
2591 ///
2592 /// will be treated as if it were really something like:
2593 ///
2594 /// ```ignore (illustrative)
2595 /// let place = Foo::new();
2596 /// match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
2597 /// => { let tmp2 = place; feed(tmp2) }, ... }
2598 /// ```
2599 ///
2600 /// And an input like:
2601 ///
2602 /// ```ignore (illustrative)
2603 /// let place = Foo::new();
2604 /// match place { ref mut foo if inspect(foo)
2605 /// => feed(foo), ... }
2606 /// ```
2607 ///
2608 /// will be treated as if it were really something like:
2609 ///
2610 /// ```ignore (illustrative)
2611 /// let place = Foo::new();
2612 /// match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
2613 /// => { let tmp2 = &mut place; feed(tmp2) }, ... }
2614 /// ```
2615 /// ---
2616 ///
2617 /// ## Implementation notes
2618 ///
2619 /// To encode the distinction above, we must inject the
2620 /// temporaries `tmp1` and `tmp2`.
2621 ///
2622 /// There are two cases of interest: binding by-value, and binding by-ref.
2623 ///
2624 /// 1. Binding by-value: Things are simple.
2625 ///
2626 /// * Establishing `tmp1` creates a reference into the
2627 /// matched place. This code is emitted by
2628 /// [`Self::bind_matched_candidate_for_guard`].
2629 ///
2630 /// * `tmp2` is only initialized "lazily", after we have
2631 /// checked the guard. Thus, the code that can trigger
2632 /// moves out of the candidate can only fire after the
2633 /// guard evaluated to true. This initialization code is
2634 /// emitted by [`Self::bind_matched_candidate_for_arm_body`].
2635 ///
2636 /// 2. Binding by-reference: Things are tricky.
2637 ///
2638 /// * Here, the guard expression wants a `&&` or `&&mut`
2639 /// into the original input. This means we need to borrow
2640 /// the reference that we create for the arm.
2641 /// * So we eagerly create the reference for the arm and then take a
2642 /// reference to that.
2643 ///
2644 /// ---
2645 ///
2646 /// See these PRs for some historical context:
2647 /// - <https://github.com/rust-lang/rust/pull/49870> (introduction of autoref)
2648 /// - <https://github.com/rust-lang/rust/pull/59114> (always use autoref)
2649fn bind_matched_candidate_for_guard<'b>(
2650&mut self,
2651 block: BasicBlock,
2652 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
2653 ) where
2654'tcx: 'b,
2655 {
2656{
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:2656",
"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(2656u32),
::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);
26572658// Assign each of the bindings. Since we are binding for a
2659 // guard expression, this will never trigger moves out of the
2660 // candidate.
2661let re_erased = self.tcx.lifetimes.re_erased;
2662for binding in bindings {
2663{
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:2663",
"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(2663u32),
::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);
2664let source_info = self.source_info(binding.span);
26652666// For each pattern ident P of type T, `ref_for_guard` is
2667 // a reference R: &T pointing to the location matched by
2668 // the pattern, and every occurrence of P within a guard
2669 // denotes *R.
2670 // Drops must be scheduled to emit `StorageDead` on the guard's failure/break branches.
2671let ref_for_guard = self.storage_live_binding(
2672 block,
2673 binding.var_id,
2674 binding.span,
2675 binding.is_shorthand,
2676 RefWithinGuard,
2677 ScheduleDrops::Yes,
2678 );
2679match binding.binding_mode.0 {
2680 ByRef::No => {
2681// The arm binding will be by value, so for the guard binding
2682 // just take a shared reference to the matched place.
2683let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source);
2684self.cfg.push_assign(block, source_info, ref_for_guard, rvalue);
2685 }
2686 ByRef::Yes(pinnedness, mutbl) => {
2687// The arm binding will be by reference, so eagerly create it now // be scheduled to emit `StorageDead` on the guard's failure/break branches.
2688let value_for_arm = self.storage_live_binding(
2689 block,
2690 binding.var_id,
2691 binding.span,
2692 binding.is_shorthand,
2693 OutsideGuard,
2694 ScheduleDrops::Yes,
2695 );
26962697let rvalue =
2698 Rvalue::Ref(re_erased, util::ref_pat_borrow_kind(mutbl), binding.source);
2699let rvalue = match pinnedness {
2700 ty::Pinnedness::Not => rvalue,
2701 ty::Pinnedness::Pinned => {
2702self.pin_borrowed_local(block, value_for_arm.local, rvalue, source_info)
2703 }
2704 };
2705self.cfg.push_assign(block, source_info, value_for_arm, rvalue);
2706// For the guard binding, take a shared reference to that reference.
2707let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
2708self.cfg.push_assign(block, source_info, ref_for_guard, rvalue);
2709 }
2710 }
2711 }
2712 }
27132714fn bind_matched_candidate_for_arm_body<'b>(
2715&mut self,
2716 block: BasicBlock,
2717 schedule_drops: ScheduleDrops,
2718 bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
2719 ) where
2720'tcx: 'b,
2721 {
2722{
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:2722",
"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(2722u32),
::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);
27232724let re_erased = self.tcx.lifetimes.re_erased;
2725// Assign each of the bindings. This may trigger moves out of the candidate.
2726for binding in bindings {
2727let source_info = self.source_info(binding.span);
2728let local = self.storage_live_binding(
2729 block,
2730 binding.var_id,
2731 binding.span,
2732 binding.is_shorthand,
2733 OutsideGuard,
2734 schedule_drops,
2735 );
2736if #[allow(non_exhaustive_omitted_patterns)] match schedule_drops {
ScheduleDrops::Yes => true,
_ => false,
}matches!(schedule_drops, ScheduleDrops::Yes) {
2737self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
2738 }
2739let rvalue = match binding.binding_mode.0 {
2740 ByRef::No => Rvalue::Use(self.consume_by_copy_or_move(binding.source)),
2741 ByRef::Yes(pinnedness, mutbl) => {
2742let rvalue =
2743 Rvalue::Ref(re_erased, util::ref_pat_borrow_kind(mutbl), binding.source);
2744match pinnedness {
2745 ty::Pinnedness::Not => rvalue,
2746 ty::Pinnedness::Pinned => {
2747self.pin_borrowed_local(block, local.local, rvalue, source_info)
2748 }
2749 }
2750 }
2751 };
2752self.cfg.push_assign(block, source_info, local, rvalue);
2753 }
2754 }
27552756/// Given an rvalue `&[mut]borrow` and a local `local`, generate the pinned borrow for it:
2757 /// ```ignore (illustrative)
2758 /// pinned_temp = &borrow;
2759 /// local = Pin { __pointer: move pinned_temp };
2760 /// ```
2761fn pin_borrowed_local(
2762&mut self,
2763 block: BasicBlock,
2764 local: Local,
2765 borrow: Rvalue<'tcx>,
2766 source_info: SourceInfo,
2767 ) -> Rvalue<'tcx> {
2768if 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(..));
27692770let local_ty = self.local_decls[local].ty;
27712772let pinned_ty = local_ty.pinned_ty().unwrap_or_else(|| {
2773::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!(
2774source_info.span,
2775"expect type `Pin` for a pinned binding, found type {:?}",
2776 local_ty
2777 )2778 });
2779let pinned_temp =
2780Place::from(self.local_decls.push(LocalDecl::new(pinned_ty, source_info.span)));
2781self.cfg.push_assign(block, source_info, pinned_temp, borrow);
2782 Rvalue::Aggregate(
2783Box::new(AggregateKind::Adt(
2784self.tcx.require_lang_item(LangItem::Pin, source_info.span),
2785FIRST_VARIANT,
2786self.tcx.mk_args(&[pinned_ty.into()]),
2787None,
2788None,
2789 )),
2790 std::iter::once(Operand::Move(pinned_temp)).collect(),
2791 )
2792 }
27932794/// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
2795 /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
2796 /// first local is a binding for occurrences of `var` in the guard, which
2797 /// will have type `&T`. The second local is a binding for occurrences of
2798 /// `var` in the arm body, which will have type `T`.
2799#[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(2799u32),
::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:2869",
"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(2869u32),
::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")]2800fn declare_binding(
2801&mut self,
2802 source_info: SourceInfo,
2803 visibility_scope: SourceScope,
2804 name: Symbol,
2805 mode: BindingMode,
2806 var_id: LocalVarId,
2807 var_ty: Ty<'tcx>,
2808 user_ty: Option<Box<UserTypeProjections>>,
2809 has_guard: ArmHasGuard,
2810 opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
2811 pat_span: Span,
2812 ) {
2813let tcx = self.tcx;
2814let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
2815let local = LocalDecl {
2816 mutability: mode.1,
2817 ty: var_ty,
2818 user_ty,
2819 source_info,
2820 local_info: ClearCrossCrate::Set(Box::new(LocalInfo::User(BindingForm::Var(
2821 VarBindingForm {
2822 binding_mode: mode,
2823// hypothetically, `visit_primary_bindings` could try to unzip
2824 // an outermost hir::Ty as we descend, matching up
2825 // idents in pat; but complex w/ unclear UI payoff.
2826 // Instead, just abandon providing diagnostic info.
2827opt_ty_info: None,
2828 opt_match_place,
2829 pat_span,
2830 introductions: Vec::new(),
2831 },
2832 )))),
2833 };
2834let for_arm_body = self.local_decls.push(local);
2835if self.should_emit_debug_info_for_binding(name, var_id) {
2836self.var_debug_info.push(VarDebugInfo {
2837 name,
2838 source_info: debug_source_info,
2839 value: VarDebugInfoContents::Place(for_arm_body.into()),
2840 composite: None,
2841 argument_index: None,
2842 });
2843 }
2844let locals = if has_guard.0 {
2845let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
2846// This variable isn't mutated but has a name, so has to be
2847 // immutable to avoid the unused mut lint.
2848mutability: Mutability::Not,
2849 ty: Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, var_ty),
2850 user_ty: None,
2851 source_info,
2852 local_info: ClearCrossCrate::Set(Box::new(LocalInfo::User(
2853 BindingForm::RefForGuard(for_arm_body),
2854 ))),
2855 });
2856if self.should_emit_debug_info_for_binding(name, var_id) {
2857self.var_debug_info.push(VarDebugInfo {
2858 name,
2859 source_info: debug_source_info,
2860 value: VarDebugInfoContents::Place(ref_for_guard.into()),
2861 composite: None,
2862 argument_index: None,
2863 });
2864 }
2865 LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
2866 } else {
2867 LocalsForNode::One(for_arm_body)
2868 };
2869debug!(?locals);
2870self.var_indices.insert(var_id, locals);
2871 }
28722873/// Some bindings are introduced when producing HIR from the AST and don't
2874 /// actually exist in the source. Skip producing debug info for those when
2875 /// we can recognize them.
2876fn should_emit_debug_info_for_binding(&self, name: Symbol, var_id: LocalVarId) -> bool {
2877// For now we only recognize the output of desugaring assigns.
2878if name != sym::lhs {
2879return true;
2880 }
28812882let tcx = self.tcx;
2883for (_, node) in tcx.hir_parent_iter(var_id.0) {
2884// FIXME(khuey) at what point is it safe to bail on the iterator?
2885 // Can we stop at the first non-Pat node?
2886if #[allow(non_exhaustive_omitted_patterns)] match node {
Node::LetStmt(&LetStmt { source: LocalSource::AssignDesugar, .. }) =>
true,
_ => false,
}matches!(node, Node::LetStmt(&LetStmt { source: LocalSource::AssignDesugar, .. })) {
2887return false;
2888 }
2889 }
28902891true
2892}
28932894/// Attempt to statically pick the `BasicBlock` that a value would resolve to at runtime.
2895pub(crate) fn static_pattern_match(
2896&self,
2897 cx: &RustcPatCtxt<'_, 'tcx>,
2898 valtree: ValTree<'tcx>,
2899 arms: &[ArmId],
2900 built_match_tree: &BuiltMatchTree<'tcx>,
2901 ) -> Option<BasicBlock> {
2902let it = arms.iter().zip(built_match_tree.branches.iter());
2903for (&arm_id, branch) in it {
2904let pat = cx.lower_pat(&*self.thir.arms[arm_id].pattern);
29052906// Peel off or-patterns if they exist.
2907if let rustc_pattern_analysis::rustc::Constructor::Or = pat.ctor() {
2908for pat in pat.iter_fields() {
2909// For top-level or-patterns (the only ones we accept right now), when the
2910 // bindings are the same (e.g. there are none), the sub_branch is stored just
2911 // once.
2912let sub_branch = branch
2913 .sub_branches
2914 .get(pat.idx)
2915 .or_else(|| branch.sub_branches.last())
2916 .unwrap();
29172918match self.static_pattern_match_inner(valtree, &pat.pat) {
2919true => return Some(sub_branch.success_block),
2920false => continue,
2921 }
2922 }
2923 } else if self.static_pattern_match_inner(valtree, &pat) {
2924return Some(branch.sub_branches[0].success_block);
2925 }
2926 }
29272928None2929 }
29302931/// Helper for [`Self::static_pattern_match`], checking whether the value represented by the
2932 /// `ValTree` matches the given pattern. This function does not recurse, meaning that it does
2933 /// not handle or-patterns, or patterns for types with fields.
2934fn static_pattern_match_inner(
2935&self,
2936 valtree: ty::ValTree<'tcx>,
2937 pat: &DeconstructedPat<'_, 'tcx>,
2938 ) -> bool {
2939use rustc_pattern_analysis::constructor::{IntRange, MaybeInfiniteInt};
2940use rustc_pattern_analysis::rustc::Constructor;
29412942match pat.ctor() {
2943Constructor::Variant(variant_index) => {
2944let ValTreeKind::Branch(box [actual_variant_idx]) = *valtreeelse {
2945::rustc_middle::util::bug::bug_fmt(format_args!("malformed valtree for an enum"))bug!("malformed valtree for an enum")2946 };
29472948let ValTreeKind::Leaf(actual_variant_idx) = *actual_variant_idx.to_value().valtree
2949else {
2950::rustc_middle::util::bug::bug_fmt(format_args!("malformed valtree for an enum"))bug!("malformed valtree for an enum")2951 };
29522953*variant_index == VariantIdx::from_u32(actual_variant_idx.to_u32())
2954 }
2955Constructor::IntRange(int_range) => {
2956let size = pat.ty().primitive_size(self.tcx);
2957let actual_int = valtree.to_leaf().to_bits(size);
2958let actual_int = if pat.ty().is_signed() {
2959MaybeInfiniteInt::new_finite_int(actual_int, size.bits())
2960 } else {
2961MaybeInfiniteInt::new_finite_uint(actual_int)
2962 };
2963IntRange::from_singleton(actual_int).is_subrange(int_range)
2964 }
2965Constructor::Bool(pattern_value) => match valtree.to_leaf().try_to_bool() {
2966Ok(actual_value) => *pattern_value == actual_value,
2967Err(()) => ::rustc_middle::util::bug::bug_fmt(format_args!("bool value with invalid bits"))bug!("bool value with invalid bits"),
2968 },
2969Constructor::F16Range(l, h, end) => {
2970let actual = valtree.to_leaf().to_f16();
2971match end {
2972 RangeEnd::Included => (*l..=*h).contains(&actual),
2973 RangeEnd::Excluded => (*l..*h).contains(&actual),
2974 }
2975 }
2976Constructor::F32Range(l, h, end) => {
2977let actual = valtree.to_leaf().to_f32();
2978match end {
2979 RangeEnd::Included => (*l..=*h).contains(&actual),
2980 RangeEnd::Excluded => (*l..*h).contains(&actual),
2981 }
2982 }
2983Constructor::F64Range(l, h, end) => {
2984let actual = valtree.to_leaf().to_f64();
2985match end {
2986 RangeEnd::Included => (*l..=*h).contains(&actual),
2987 RangeEnd::Excluded => (*l..*h).contains(&actual),
2988 }
2989 }
2990Constructor::F128Range(l, h, end) => {
2991let actual = valtree.to_leaf().to_f128();
2992match end {
2993 RangeEnd::Included => (*l..=*h).contains(&actual),
2994 RangeEnd::Excluded => (*l..*h).contains(&actual),
2995 }
2996 }
2997Constructor::Wildcard => true,
29982999// Opaque patterns must not be matched on structurally.
3000Constructor::Opaque(_) => false,
30013002// These we may eventually support:
3003Constructor::Struct3004 | Constructor::Ref3005 | Constructor::DerefPattern(_)
3006 | Constructor::Slice(_)
3007 | Constructor::UnionField3008 | Constructor::Or3009 | Constructor::Str(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("unsupported pattern constructor {0:?}",
pat.ctor()))bug!("unsupported pattern constructor {:?}", pat.ctor()),
30103011// These should never occur here:
3012Constructor::Never3013 | Constructor::NonExhaustive3014 | Constructor::Hidden3015 | Constructor::Missing3016 | Constructor::PrivateUninhabited => {
3017::rustc_middle::util::bug::bug_fmt(format_args!("unsupported pattern constructor {0:?}",
pat.ctor()))bug!("unsupported pattern constructor {:?}", pat.ctor())3018 }
3019 }
3020 }
3021}