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