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