1//! See docs in build/expr/mod.rs
23use std::{assert_matches, iter};
45use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
6use rustc_hir::def_id::LocalDefId;
7use rustc_middle::hir::place::{Projectionas HirProjection, ProjectionKindas HirProjectionKind};
8use rustc_middle::mir::AssertKind::BoundsCheck;
9use rustc_middle::mir::*;
10use rustc_middle::thir::*;
11use rustc_middle::ty::{self, AdtDef, CanonicalUserTypeAnnotation, Ty, Variance};
12use rustc_middle::{bug, span_bug};
13use rustc_span::Span;
14use tracing::{debug, instrument, trace};
1516use crate::builder::ForGuard::{OutsideGuard, RefWithinGuard};
17use crate::builder::expr::category::Category;
18use crate::builder::scope::LintLevel;
19use crate::builder::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap};
2021/// The "outermost" place that holds this value.
22#[derive(#[automatically_derived]
impl ::core::marker::Copy for PlaceBase { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PlaceBase {
#[inline]
fn clone(&self) -> PlaceBase {
let _: ::core::clone::AssertParamIsClone<Local>;
let _: ::core::clone::AssertParamIsClone<LocalVarId>;
let _: ::core::clone::AssertParamIsClone<LocalDefId>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PlaceBase {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PlaceBase::Local(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Local",
&__self_0),
PlaceBase::Upvar { var_hir_id: __self_0, closure_def_id: __self_1
} =>
::core::fmt::Formatter::debug_struct_field2_finish(f, "Upvar",
"var_hir_id", __self_0, "closure_def_id", &__self_1),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for PlaceBase {
#[inline]
fn eq(&self, other: &PlaceBase) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(PlaceBase::Local(__self_0), PlaceBase::Local(__arg1_0)) =>
__self_0 == __arg1_0,
(PlaceBase::Upvar {
var_hir_id: __self_0, closure_def_id: __self_1 },
PlaceBase::Upvar {
var_hir_id: __arg1_0, closure_def_id: __arg1_1 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq)]
23pub(crate) enum PlaceBase {
24/// Denotes the start of a `Place`.
25Local(Local),
2627/// When building place for an expression within a closure, the place might start off a
28 /// captured path. When `capture_disjoint_fields` is enabled, we might not know the capture
29 /// index (within the desugared closure) of the captured path until most of the projections
30 /// are applied. We use `PlaceBase::Upvar` to keep track of the root variable off of which the
31 /// captured path starts, the closure the capture belongs to and the trait the closure
32 /// implements.
33 ///
34 /// Once we have figured out the capture index, we can convert the place builder to start from
35 /// `PlaceBase::Local`.
36 ///
37 /// Consider the following example
38 /// ```rust
39 /// let t = (((10, 10), 10), 10);
40 ///
41 /// let c = || {
42 /// println!("{}", t.0.0.0);
43 /// };
44 /// ```
45 /// Here the THIR expression for `t.0.0.0` will be something like
46 ///
47 /// ```ignore (illustrative)
48 /// * Field(0)
49 /// * Field(0)
50 /// * Field(0)
51 /// * UpvarRef(t)
52 /// ```
53 ///
54 /// When `capture_disjoint_fields` is enabled, `t.0.0.0` is captured and we won't be able to
55 /// figure out that it is captured until all the `Field` projections are applied.
56Upvar {
57/// HirId of the upvar
58var_hir_id: LocalVarId,
59/// DefId of the closure
60closure_def_id: LocalDefId,
61 },
62}
6364/// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
65/// place by pushing more and more projections onto the end, and then convert the final set into a
66/// place using the `to_place` method.
67///
68/// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
69/// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
70#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for PlaceBuilder<'tcx> {
#[inline]
fn clone(&self) -> PlaceBuilder<'tcx> {
PlaceBuilder {
base: ::core::clone::Clone::clone(&self.base),
projection: ::core::clone::Clone::clone(&self.projection),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PlaceBuilder<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "PlaceBuilder",
"base", &self.base, "projection", &&self.projection)
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for PlaceBuilder<'tcx> {
#[inline]
fn eq(&self, other: &PlaceBuilder<'tcx>) -> bool {
self.base == other.base && self.projection == other.projection
}
}PartialEq)]
71pub(in crate::builder) struct PlaceBuilder<'tcx> {
72 base: PlaceBase,
73 projection: Vec<PlaceElem<'tcx>>,
74}
7576/// Given a list of MIR projections, convert them to list of HIR ProjectionKind.
77/// The projections are truncated to represent a path that might be captured by a
78/// closure/coroutine. This implies the vector returned from this function doesn't contain
79/// ProjectionElems `Downcast`, `ConstantIndex`, `Index`, or `Subslice` because those will never be
80/// part of a path that is captured by a closure. We stop applying projections once we see the first
81/// projection that isn't captured by a closure.
82fn convert_to_hir_projections_and_truncate_for_capture(
83 mir_projections: &[PlaceElem<'_>],
84) -> Vec<HirProjectionKind> {
85let mut hir_projections = Vec::new();
86let mut variant = None;
8788for mir_projection in mir_projections {
89let hir_projection = match mir_projection {
90 ProjectionElem::Deref => HirProjectionKind::Deref,
91 ProjectionElem::Field(field, _) => {
92let variant = variant.unwrap_or(FIRST_VARIANT);
93 HirProjectionKind::Field(*field, variant)
94 }
95 ProjectionElem::Downcast(.., idx) => {
96// We don't expect to see multi-variant enums here, as earlier
97 // phases will have truncated them already. However, there can
98 // still be downcasts, thanks to single-variant enums.
99 // We keep track of VariantIdx so we can use this information
100 // if the next ProjectionElem is a Field.
101variant = Some(*idx);
102continue;
103 }
104 ProjectionElem::UnwrapUnsafeBinder(_) => HirProjectionKind::UnwrapUnsafeBinder,
105// These do not affect anything, they just make sure we know the right type.
106ProjectionElem::OpaqueCast(_) => continue,
107 ProjectionElem::Index(..)
108 | ProjectionElem::ConstantIndex { .. }
109 | ProjectionElem::Subslice { .. } => {
110// We don't capture array-access projections.
111 // We can stop here as arrays are captured completely.
112break;
113 }
114 };
115 variant = None;
116 hir_projections.push(hir_projection);
117 }
118119hir_projections120}
121122/// Return true if the `proj_possible_ancestor` represents an ancestor path
123/// to `proj_capture` or `proj_possible_ancestor` is same as `proj_capture`,
124/// assuming they both start off of the same root variable.
125///
126/// **Note:** It's the caller's responsibility to ensure that both lists of projections
127/// start off of the same root variable.
128///
129/// Eg: 1. `foo.x` which is represented using `projections=[Field(x)]` is an ancestor of
130/// `foo.x.y` which is represented using `projections=[Field(x), Field(y)]`.
131/// Note both `foo.x` and `foo.x.y` start off of the same root variable `foo`.
132/// 2. Since we only look at the projections here function will return `bar.x` as a valid
133/// ancestor of `foo.x.y`. It's the caller's responsibility to ensure that both projections
134/// list are being applied to the same root variable.
135fn is_ancestor_or_same_capture(
136 proj_possible_ancestor: &[HirProjectionKind],
137 proj_capture: &[HirProjectionKind],
138) -> bool {
139// We want to make sure `is_ancestor_or_same_capture("x.0.0", "x.0")` to return false.
140 // Therefore we can't just check if all projections are same in the zipped iterator below.
141if proj_possible_ancestor.len() > proj_capture.len() {
142return false;
143 }
144145 iter::zip(proj_possible_ancestor, proj_capture).all(|(a, b)| a == b)
146}
147148/// Given a closure, returns the index of a capture within the desugared closure struct and the
149/// `ty::CapturedPlace` which is the ancestor of the Place represented using the `var_hir_id`
150/// and `projection`.
151///
152/// Note there will be at most one ancestor for any given Place.
153///
154/// Returns None, when the ancestor is not found.
155fn find_capture_matching_projections<'a, 'tcx>(
156 upvars: &'a CaptureMap<'tcx>,
157 var_hir_id: LocalVarId,
158 projections: &[PlaceElem<'tcx>],
159) -> Option<(usize, &'a Capture<'tcx>)> {
160let hir_projections = convert_to_hir_projections_and_truncate_for_capture(projections);
161162upvars.get_by_key_enumerated(var_hir_id.0.local_id).find(|(_, capture)| {
163let possible_ancestor_proj_kinds: Vec<_> =
164capture.captured_place.place.projections.iter().map(|proj| proj.kind).collect();
165is_ancestor_or_same_capture(&possible_ancestor_proj_kinds, &hir_projections)
166 })
167}
168169/// Takes an upvar place and tries to resolve it into a `PlaceBuilder`
170/// with `PlaceBase::Local`
171x;#[instrument(level = "trace", skip(cx), ret)]172fn to_upvars_resolved_place_builder<'tcx>(
173 cx: &Builder<'_, 'tcx>,
174 var_hir_id: LocalVarId,
175 closure_def_id: LocalDefId,
176 projection: &[PlaceElem<'tcx>],
177) -> Option<PlaceBuilder<'tcx>> {
178let Some((capture_index, capture)) =
179 find_capture_matching_projections(&cx.upvars, var_hir_id, projection)
180else {
181let closure_span = cx.tcx.def_span(closure_def_id);
182if !enable_precise_capture(closure_span) {
183bug!(
184"No associated capture found for {:?}[{:#?}] even though \
185 capture_disjoint_fields isn't enabled",
186 var_hir_id,
187 projection
188 )
189 } else {
190debug!("No associated capture found for {:?}[{:#?}]", var_hir_id, projection,);
191 }
192return None;
193 };
194195// Access the capture by accessing the field within the Closure struct.
196let capture_info = &cx.upvars[capture_index];
197198let mut upvar_resolved_place_builder = PlaceBuilder::from(capture_info.use_place);
199200// We used some of the projections to build the capture itself,
201 // now we apply the remaining to the upvar resolved place.
202trace!(?capture.captured_place, ?projection);
203let remaining_projections = strip_prefix(
204 capture.captured_place.place.base_ty,
205 projection,
206&capture.captured_place.place.projections,
207 );
208 upvar_resolved_place_builder.projection.extend(remaining_projections);
209210Some(upvar_resolved_place_builder)
211}
212213/// Returns projections remaining after stripping an initial prefix of HIR
214/// projections.
215///
216/// Supports only HIR projection kinds that represent a path that might be
217/// captured by a closure or a coroutine, i.e., an `Index` or a `Subslice`
218/// projection kinds are unsupported.
219fn strip_prefix<'tcx>(
220mut base_ty: Ty<'tcx>,
221 projections: &[PlaceElem<'tcx>],
222 prefix_projections: &[HirProjection<'tcx>],
223) -> impl Iterator<Item = PlaceElem<'tcx>> {
224let mut iter = projections225 .iter()
226 .copied()
227// Filter out opaque casts, they are unnecessary in the prefix.
228 .filter(|elem| !#[allow(non_exhaustive_omitted_patterns)] match elem {
ProjectionElem::OpaqueCast(..) => true,
_ => false,
}matches!(elem, ProjectionElem::OpaqueCast(..)));
229for projection in prefix_projections {
230match projection.kind {
231 HirProjectionKind::Deref => {
232match iter.next() {
Some(ProjectionElem::Deref) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Some(ProjectionElem::Deref)", ::core::option::Option::None);
}
};assert_matches!(iter.next(), Some(ProjectionElem::Deref));
233 }
234 HirProjectionKind::Field(..) => {
235if base_ty.is_enum() {
236match iter.next() {
Some(ProjectionElem::Downcast(..)) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Some(ProjectionElem::Downcast(..))",
::core::option::Option::None);
}
};assert_matches!(iter.next(), Some(ProjectionElem::Downcast(..)));
237 }
238match iter.next() {
Some(ProjectionElem::Field(..)) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Some(ProjectionElem::Field(..))", ::core::option::Option::None);
}
};assert_matches!(iter.next(), Some(ProjectionElem::Field(..)));
239 }
240 HirProjectionKind::OpaqueCast => {
241match iter.next() {
Some(ProjectionElem::OpaqueCast(..)) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Some(ProjectionElem::OpaqueCast(..))",
::core::option::Option::None);
}
};assert_matches!(iter.next(), Some(ProjectionElem::OpaqueCast(..)));
242 }
243 HirProjectionKind::UnwrapUnsafeBinder => {
244match iter.next() {
Some(ProjectionElem::UnwrapUnsafeBinder(..)) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Some(ProjectionElem::UnwrapUnsafeBinder(..))",
::core::option::Option::None);
}
};assert_matches!(iter.next(), Some(ProjectionElem::UnwrapUnsafeBinder(..)));
245 }
246 HirProjectionKind::Index | HirProjectionKind::Subslice => {
247::rustc_middle::util::bug::bug_fmt(format_args!("unexpected projection kind: {0:?}",
projection));bug!("unexpected projection kind: {:?}", projection);
248 }
249 }
250 base_ty = projection.ty;
251 }
252iter253}
254255impl<'tcx> PlaceBuilder<'tcx> {
256pub(in crate::builder) fn to_place(&self, cx: &Builder<'_, 'tcx>) -> Place<'tcx> {
257self.try_to_place(cx).unwrap_or_else(|| match self.base {
258 PlaceBase::Local(local) => ::rustc_middle::util::bug::span_bug_fmt(cx.local_decls[local].source_info.span,
format_args!("could not resolve local: {1:#?} + {0:?}", self.projection,
local))span_bug!(
259cx.local_decls[local].source_info.span,
260"could not resolve local: {local:#?} + {:?}",
261self.projection
262 ),
263 PlaceBase::Upvar { var_hir_id, closure_def_id: _ } => ::rustc_middle::util::bug::span_bug_fmt(cx.tcx.hir_span(var_hir_id.0),
format_args!("could not resolve upvar: {1:?} + {0:?}", self.projection,
var_hir_id))span_bug!(
264cx.tcx.hir_span(var_hir_id.0),
265"could not resolve upvar: {var_hir_id:?} + {:?}",
266self.projection
267 ),
268 })
269 }
270271/// Creates a `Place` or returns `None` if an upvar cannot be resolved
272pub(in crate::builder) fn try_to_place(&self, cx: &Builder<'_, 'tcx>) -> Option<Place<'tcx>> {
273let resolved = self.resolve_upvar(cx);
274let builder = resolved.as_ref().unwrap_or(self);
275let PlaceBase::Local(local) = builder.base else { return None };
276let projection = cx.tcx.mk_place_elems(&builder.projection);
277Some(Place { local, projection })
278 }
279280/// Attempts to resolve the `PlaceBuilder`.
281 /// Returns `None` if this is not an upvar.
282 ///
283 /// Upvars resolve may fail for a `PlaceBuilder` when attempting to
284 /// resolve a disjoint field whose root variable is not captured
285 /// (destructured assignments) or when attempting to resolve a root
286 /// variable (discriminant matching with only wildcard arm) that is
287 /// not captured. This can happen because the final mir that will be
288 /// generated doesn't require a read for this place. Failures will only
289 /// happen inside closures.
290pub(in crate::builder) fn resolve_upvar(
291&self,
292 cx: &Builder<'_, 'tcx>,
293 ) -> Option<PlaceBuilder<'tcx>> {
294let PlaceBase::Upvar { var_hir_id, closure_def_id } = self.base else {
295return None;
296 };
297to_upvars_resolved_place_builder(cx, var_hir_id, closure_def_id, &self.projection)
298 }
299300pub(crate) fn base(&self) -> PlaceBase {
301self.base
302 }
303304pub(crate) fn projection(&self) -> &[PlaceElem<'tcx>] {
305&self.projection
306 }
307308pub(crate) fn field(self, f: FieldIdx, ty: Ty<'tcx>) -> Self {
309self.project(PlaceElem::Field(f, ty))
310 }
311312pub(crate) fn deref(self) -> Self {
313self.project(PlaceElem::Deref)
314 }
315316pub(crate) fn downcast(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx) -> Self {
317self.project(PlaceElem::Downcast(Some(adt_def.variant(variant_index).name), variant_index))
318 }
319320fn index(self, index: Local) -> Self {
321self.project(PlaceElem::Index(index))
322 }
323324pub(crate) fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
325self.projection.push(elem);
326self327 }
328329/// Same as `.clone().project(..)` but more efficient
330pub(crate) fn clone_project(&self, elem: PlaceElem<'tcx>) -> Self {
331Self {
332 base: self.base,
333 projection: Vec::from_iter(self.projection.iter().copied().chain([elem])),
334 }
335 }
336}
337338impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
339fn from(local: Local) -> Self {
340Self { base: PlaceBase::Local(local), projection: Vec::new() }
341 }
342}
343344impl<'tcx> From<PlaceBase> for PlaceBuilder<'tcx> {
345fn from(base: PlaceBase) -> Self {
346Self { base, projection: Vec::new() }
347 }
348}
349350impl<'tcx> From<Place<'tcx>> for PlaceBuilder<'tcx> {
351fn from(p: Place<'tcx>) -> Self {
352Self { base: PlaceBase::Local(p.local), projection: p.projection.to_vec() }
353 }
354}
355356impl<'a, 'tcx> Builder<'a, 'tcx> {
357/// Compile `expr`, yielding a place that we can move from etc.
358 ///
359 /// WARNING: Any user code might:
360 /// * Invalidate any slice bounds checks performed.
361 /// * Change the address that this `Place` refers to.
362 /// * Modify the memory that this place refers to.
363 /// * Invalidate the memory that this place refers to, this will be caught
364 /// by borrow checking.
365 ///
366 /// Extra care is needed if any user code is allowed to run between calling
367 /// this method and using it, as is the case for `match` and index
368 /// expressions.
369pub(crate) fn as_place(
370&mut self,
371mut block: BasicBlock,
372 expr_id: ExprId,
373 ) -> BlockAnd<Place<'tcx>> {
374let place_builder = { let BlockAnd(b, v) = self.as_place_builder(block, expr_id); block = b; v }unpack!(block = self.as_place_builder(block, expr_id));
375block.and(place_builder.to_place(self))
376 }
377378/// This is used when constructing a compound `Place`, so that we can avoid creating
379 /// intermediate `Place` values until we know the full set of projections.
380pub(crate) fn as_place_builder(
381&mut self,
382 block: BasicBlock,
383 expr_id: ExprId,
384 ) -> BlockAnd<PlaceBuilder<'tcx>> {
385self.expr_as_place(block, expr_id, Mutability::Mut, None)
386 }
387388/// Compile `expr`, yielding a place that we can move from etc.
389 /// Mutability note: The caller of this method promises only to read from the resulting
390 /// place. The place itself may or may not be mutable:
391 /// * If this expr is a place expr like a.b, then we will return that place.
392 /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
393pub(crate) fn as_read_only_place(
394&mut self,
395mut block: BasicBlock,
396 expr_id: ExprId,
397 ) -> BlockAnd<Place<'tcx>> {
398let place_builder = {
let BlockAnd(b, v) = self.as_read_only_place_builder(block, expr_id);
block = b;
v
}unpack!(block = self.as_read_only_place_builder(block, expr_id));
399block.and(place_builder.to_place(self))
400 }
401402/// This is used when constructing a compound `Place`, so that we can avoid creating
403 /// intermediate `Place` values until we know the full set of projections.
404 /// Mutability note: The caller of this method promises only to read from the resulting
405 /// place. The place itself may or may not be mutable:
406 /// * If this expr is a place expr like a.b, then we will return that place.
407 /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
408fn as_read_only_place_builder(
409&mut self,
410 block: BasicBlock,
411 expr_id: ExprId,
412 ) -> BlockAnd<PlaceBuilder<'tcx>> {
413self.expr_as_place(block, expr_id, Mutability::Not, None)
414 }
415416fn expr_as_place(
417&mut self,
418mut block: BasicBlock,
419 expr_id: ExprId,
420 mutability: Mutability,
421 fake_borrow_temps: Option<&mut Vec<Local>>,
422 ) -> BlockAnd<PlaceBuilder<'tcx>> {
423let expr = &self.thir[expr_id];
424{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/expr/as_place.rs:424",
"rustc_mir_build::builder::expr::as_place",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/expr/as_place.rs"),
::tracing_core::__macro_support::Option::Some(424u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_place"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("expr_as_place(block={0:?}, expr={1:?}, mutability={2:?})",
block, expr, mutability) as &dyn Value))])
});
} else { ; }
};debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
425426let this = self; // See "LET_THIS_SELF".
427let expr_span = expr.span;
428let source_info = this.source_info(expr_span);
429match expr.kind {
430 ExprKind::Scope { region_scope, hir_id, value } => {
431this.in_scope((region_scope, source_info), LintLevel::Explicit(hir_id), |this| {
432this.expr_as_place(block, value, mutability, fake_borrow_temps)
433 })
434 }
435 ExprKind::Field { lhs, variant_index, name } => {
436let lhs_expr = &this.thir[lhs];
437let mut place_builder =
438{
let BlockAnd(b, v) =
this.expr_as_place(block, lhs, mutability, fake_borrow_temps);
block = b;
v
}unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
439if let ty::Adt(adt_def, _) = lhs_expr.ty.kind() {
440if adt_def.is_enum() {
441place_builder = place_builder.downcast(*adt_def, variant_index);
442 }
443 }
444block.and(place_builder.field(name, expr.ty))
445 }
446 ExprKind::Deref { arg } => {
447let place_builder =
448{
let BlockAnd(b, v) =
this.expr_as_place(block, arg, mutability, fake_borrow_temps);
block = b;
v
}unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
449block.and(place_builder.deref())
450 }
451 ExprKind::Index { lhs, index } => this.lower_index_expression(
452block,
453lhs,
454index,
455mutability,
456fake_borrow_temps,
457expr_span,
458source_info,
459 ),
460 ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
461this.lower_captured_upvar(block, closure_def_id.expect_local(), var_hir_id)
462 }
463464 ExprKind::VarRef { id } => {
465let place_builder = if this.is_bound_var_in_guard(id) {
466let index = this.var_local_id(id, RefWithinGuard);
467PlaceBuilder::from(index).deref()
468 } else {
469let index = this.var_local_id(id, OutsideGuard);
470PlaceBuilder::from(index)
471 };
472block.and(place_builder)
473 }
474475 ExprKind::PlaceTypeAscription { source, ref user_ty, user_ty_span } => {
476let place_builder = {
let BlockAnd(b, v) =
this.expr_as_place(block, source, mutability, fake_borrow_temps);
block = b;
v
}unpack!(
477 block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
478 );
479if let Some(user_ty) = user_ty {
480let ty_source_info = this.source_info(user_ty_span);
481let annotation_index =
482this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
483 span: user_ty_span,
484 user_ty: user_ty.clone(),
485 inferred_ty: expr.ty,
486 });
487488let place = place_builder.to_place(this);
489this.cfg.push(
490block,
491Statement::new(
492ty_source_info,
493 StatementKind::AscribeUserType(
494Box::new((
495place,
496UserTypeProjection { base: annotation_index, projs: ::alloc::vec::Vec::new()vec![] },
497 )),
498 Variance::Invariant,
499 ),
500 ),
501 );
502 }
503block.and(place_builder)
504 }
505 ExprKind::ValueTypeAscription { source, ref user_ty, user_ty_span } => {
506let temp_lifetime =
507this.region_scope_tree.temporary_scope(this.thir[source].temp_scope_id);
508let temp = {
let BlockAnd(b, v) =
this.as_temp(block, temp_lifetime, source, mutability);
block = b;
v
}unpack!(block = this.as_temp(block, temp_lifetime, source, mutability));
509if let Some(user_ty) = user_ty {
510let ty_source_info = this.source_info(user_ty_span);
511let annotation_index =
512this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
513 span: user_ty_span,
514 user_ty: user_ty.clone(),
515 inferred_ty: expr.ty,
516 });
517this.cfg.push(
518block,
519Statement::new(
520ty_source_info,
521 StatementKind::AscribeUserType(
522Box::new((
523Place::from(temp),
524UserTypeProjection { base: annotation_index, projs: ::alloc::vec::Vec::new()vec![] },
525 )),
526 Variance::Invariant,
527 ),
528 ),
529 );
530 }
531block.and(PlaceBuilder::from(temp))
532 }
533534 ExprKind::PlaceUnwrapUnsafeBinder { source } => {
535let place_builder = {
let BlockAnd(b, v) =
this.expr_as_place(block, source, mutability, fake_borrow_temps);
block = b;
v
}unpack!(
536 block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
537 );
538block.and(place_builder.project(PlaceElem::UnwrapUnsafeBinder(expr.ty)))
539 }
540 ExprKind::ValueUnwrapUnsafeBinder { source } => {
541let temp_lifetime =
542this.region_scope_tree.temporary_scope(this.thir[source].temp_scope_id);
543let temp = {
let BlockAnd(b, v) =
this.as_temp(block, temp_lifetime, source, mutability);
block = b;
v
}unpack!(block = this.as_temp(block, temp_lifetime, source, mutability));
544block.and(PlaceBuilder::from(temp).project(PlaceElem::UnwrapUnsafeBinder(expr.ty)))
545 }
546547 ExprKind::Array { .. }
548 | ExprKind::Tuple { .. }
549 | ExprKind::Adt { .. }
550 | ExprKind::Closure { .. }
551 | ExprKind::Unary { .. }
552 | ExprKind::Binary { .. }
553 | ExprKind::LogicalOp { .. }
554 | ExprKind::Cast { .. }
555 | ExprKind::Use { .. }
556 | ExprKind::NeverToAny { .. }
557 | ExprKind::PointerCoercion { .. }
558 | ExprKind::Repeat { .. }
559 | ExprKind::Borrow { .. }
560 | ExprKind::RawBorrow { .. }
561 | ExprKind::Match { .. }
562 | ExprKind::If { .. }
563 | ExprKind::Loop { .. }
564 | ExprKind::LoopMatch { .. }
565 | ExprKind::Block { .. }
566 | ExprKind::Let { .. }
567 | ExprKind::Assign { .. }
568 | ExprKind::AssignOp { .. }
569 | ExprKind::Break { .. }
570 | ExprKind::Continue { .. }
571 | ExprKind::ConstContinue { .. }
572 | ExprKind::Return { .. }
573 | ExprKind::Become { .. }
574 | ExprKind::Literal { .. }
575 | ExprKind::NamedConst { .. }
576 | ExprKind::NonHirLiteral { .. }
577 | ExprKind::ZstLiteral { .. }
578 | ExprKind::ConstParam { .. }
579 | ExprKind::ConstBlock { .. }
580 | ExprKind::StaticRef { .. }
581 | ExprKind::InlineAsm { .. }
582 | ExprKind::Yield { .. }
583 | ExprKind::ThreadLocalRef(_)
584 | ExprKind::Call { .. }
585 | ExprKind::ByUse { .. }
586 | ExprKind::WrapUnsafeBinder { .. } => {
587// these are not places, so we need to make a temporary.
588if true {
if !!#[allow(non_exhaustive_omitted_patterns)] match Category::of(&expr.kind)
{
Some(Category::Place) => true,
_ => false,
} {
::core::panicking::panic("assertion failed: !matches!(Category::of(&expr.kind), Some(Category::Place))")
};
};debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
589let temp_lifetime = this.region_scope_tree.temporary_scope(expr.temp_scope_id);
590let temp = {
let BlockAnd(b, v) =
this.as_temp(block, temp_lifetime, expr_id, mutability);
block = b;
v
}unpack!(block = this.as_temp(block, temp_lifetime, expr_id, mutability));
591block.and(PlaceBuilder::from(temp))
592 }
593 }
594 }
595596/// Lower a captured upvar. Note we might not know the actual capture index,
597 /// so we create a place starting from `PlaceBase::Upvar`, which will be resolved
598 /// once all projections that allow us to identify a capture have been applied.
599fn lower_captured_upvar(
600&mut self,
601 block: BasicBlock,
602 closure_def_id: LocalDefId,
603 var_hir_id: LocalVarId,
604 ) -> BlockAnd<PlaceBuilder<'tcx>> {
605block.and(PlaceBuilder::from(PlaceBase::Upvar { var_hir_id, closure_def_id }))
606 }
607608/// Lower an index expression
609 ///
610 /// This has two complications;
611 ///
612 /// * We need to do a bounds check.
613 /// * We need to ensure that the bounds check can't be invalidated using an
614 /// expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
615 /// that this is the case.
616fn lower_index_expression(
617&mut self,
618mut block: BasicBlock,
619 base: ExprId,
620 index: ExprId,
621 mutability: Mutability,
622 fake_borrow_temps: Option<&mut Vec<Local>>,
623 expr_span: Span,
624 source_info: SourceInfo,
625 ) -> BlockAnd<PlaceBuilder<'tcx>> {
626let base_fake_borrow_temps = &mut Vec::new();
627let is_outermost_index = fake_borrow_temps.is_none();
628let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
629630let base_place =
631{
let BlockAnd(b, v) =
self.expr_as_place(block, base, mutability, Some(fake_borrow_temps));
block = b;
v
}unpack!(block = self.expr_as_place(block, base, mutability, Some(fake_borrow_temps),));
632633// Making this a *fresh* temporary means we do not have to worry about
634 // the index changing later: Nothing will ever change this temporary.
635 // The "retagging" transformation (for Stacked Borrows) relies on this.
636 // Using the enclosing temporary scope for the index ensures it will live past where this
637 // place is used. This lifetime may be larger than strictly necessary but it means we don't
638 // need to pass a scope for operands to `as_place`.
639let index_lifetime = self.region_scope_tree.temporary_scope(self.thir[index].temp_scope_id);
640let idx = {
let BlockAnd(b, v) =
self.as_temp(block, index_lifetime, index, Mutability::Not);
block = b;
v
}unpack!(block = self.as_temp(block, index_lifetime, index, Mutability::Not));
641642block = self.bounds_check(block, &base_place, idx, expr_span, source_info);
643644if is_outermost_index {
645self.read_fake_borrows(block, fake_borrow_temps, source_info)
646 } else {
647self.add_fake_borrows_of_base(
648base_place.to_place(self),
649block,
650fake_borrow_temps,
651expr_span,
652source_info,
653 );
654 }
655656block.and(base_place.index(idx))
657 }
658659/// Given a place that's either an array or a slice, returns an operand
660 /// with the length of the array/slice.
661 ///
662 /// For arrays it'll be `Operand::Constant` with the actual length;
663 /// For slices it'll be `Operand::Move` of a local using `PtrMetadata`.
664pub(in crate::builder) fn len_of_slice_or_array(
665&mut self,
666 block: BasicBlock,
667 place: Place<'tcx>,
668 span: Span,
669 source_info: SourceInfo,
670 ) -> Operand<'tcx> {
671let place_ty = place.ty(&self.local_decls, self.tcx).ty;
672match place_ty.kind() {
673 ty::Array(_elem_ty, len_const) => {
674// We know how long an array is, so just use that as a constant
675 // directly -- no locals needed. We do need one statement so
676 // that borrow- and initialization-checking consider it used,
677 // though. FIXME: Do we really *need* to count this as a use?
678 // Could partial array tracking work off something else instead?
679self.cfg.push_fake_read(block, source_info, FakeReadCause::ForIndex, place);
680let const_ = Const::Ty(self.tcx.types.usize, *len_const);
681 Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
682 }
683 ty::Slice(_elem_ty) => {
684let ptr_or_ref = if let [PlaceElem::Deref] = place.projection[..]
685 && let local_ty = self.local_decls[place.local].ty
686 && local_ty.is_trivially_pure_clone_copy()
687 {
688// It's extremely common that we have something that can be
689 // directly passed to `PtrMetadata`, so avoid an unnecessary
690 // temporary and statement in those cases. Note that we can
691 // only do that for `Copy` types -- not `&mut [_]` -- because
692 // the MIR we're building here needs to pass NLL later.
693Operand::Copy(Place::from(place.local))
694 } else {
695let ptr_ty = Ty::new_imm_ptr(self.tcx, place_ty);
696let slice_ptr = self.temp(ptr_ty, span);
697self.cfg.push_assign(
698block,
699source_info,
700slice_ptr,
701 Rvalue::RawPtr(RawPtrKind::FakeForPtrMetadata, place),
702 );
703 Operand::Move(slice_ptr)
704 };
705706let len = self.temp(self.tcx.types.usize, span);
707self.cfg.push_assign(
708block,
709source_info,
710len,
711 Rvalue::UnaryOp(UnOp::PtrMetadata, ptr_or_ref),
712 );
713714 Operand::Move(len)
715 }
716_ => {
717::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("len called on place of type {0:?}", place_ty))span_bug!(span, "len called on place of type {place_ty:?}")718 }
719 }
720 }
721722fn bounds_check(
723&mut self,
724 block: BasicBlock,
725 slice: &PlaceBuilder<'tcx>,
726 index: Local,
727 expr_span: Span,
728 source_info: SourceInfo,
729 ) -> BasicBlock {
730let slice = slice.to_place(self);
731732// len = len(slice)
733let len = self.len_of_slice_or_array(block, slice, expr_span, source_info);
734735// lt = idx < len
736let bool_ty = self.tcx.types.bool;
737let lt = self.temp(bool_ty, expr_span);
738self.cfg.push_assign(
739block,
740source_info,
741lt,
742 Rvalue::BinaryOp(
743 BinOp::Lt,
744Box::new((Operand::Copy(Place::from(index)), len.to_copy())),
745 ),
746 );
747let msg = BoundsCheck { len, index: Operand::Copy(Place::from(index)) };
748749// assert!(lt, "...")
750self.assert(block, Operand::Move(lt), true, msg, expr_span)
751 }
752753fn add_fake_borrows_of_base(
754&mut self,
755 base_place: Place<'tcx>,
756 block: BasicBlock,
757 fake_borrow_temps: &mut Vec<Local>,
758 expr_span: Span,
759 source_info: SourceInfo,
760 ) {
761let tcx = self.tcx;
762763let place_ty = base_place.ty(&self.local_decls, tcx);
764if let ty::Slice(_) = place_ty.ty.kind() {
765// We need to create fake borrows to ensure that the bounds
766 // check that we just did stays valid. Since we can't assign to
767 // unsized values, we only need to ensure that none of the
768 // pointers in the base place are modified.
769for (base_place, elem) in base_place.iter_projections().rev() {
770match elem {
771 ProjectionElem::Deref => {
772let fake_borrow_deref_ty = base_place.ty(&self.local_decls, tcx).ty;
773let fake_borrow_ty =
774 Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, fake_borrow_deref_ty);
775let fake_borrow_temp =
776self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
777let projection = tcx.mk_place_elems(base_place.projection);
778self.cfg.push_assign(
779 block,
780 source_info,
781 fake_borrow_temp.into(),
782 Rvalue::Ref(
783 tcx.lifetimes.re_erased,
784 BorrowKind::Fake(FakeBorrowKind::Shallow),
785 Place { local: base_place.local, projection },
786 ),
787 );
788 fake_borrow_temps.push(fake_borrow_temp);
789 }
790 ProjectionElem::Index(_) => {
791let index_ty = base_place.ty(&self.local_decls, tcx);
792match index_ty.ty.kind() {
793// The previous index expression has already
794 // done any index expressions needed here.
795ty::Slice(_) => break,
796 ty::Array(..) => (),
797_ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected index base"))bug!("unexpected index base"),
798 }
799 }
800 ProjectionElem::Field(..)
801 | ProjectionElem::Downcast(..)
802 | ProjectionElem::OpaqueCast(..)
803 | ProjectionElem::ConstantIndex { .. }
804 | ProjectionElem::Subslice { .. }
805 | ProjectionElem::UnwrapUnsafeBinder(_) => (),
806 }
807 }
808 }
809 }
810811fn read_fake_borrows(
812&mut self,
813 bb: BasicBlock,
814 fake_borrow_temps: &mut Vec<Local>,
815 source_info: SourceInfo,
816 ) {
817// All indexes have been evaluated now, read all of the
818 // fake borrows so that they are live across those index
819 // expressions.
820for temp in fake_borrow_temps {
821self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
822 }
823 }
824}
825826/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
827fn enable_precise_capture(closure_span: Span) -> bool {
828closure_span.at_least_rust_2021()
829}