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