1//! ### Inferring borrow kinds for upvars
2//!
3//! Whenever there is a closure expression, we need to determine how each
4//! upvar is used. We do this by initially assigning each upvar an
5//! immutable "borrow kind" (see `ty::BorrowKind` for details) and then
6//! "escalating" the kind as needed. The borrow kind proceeds according to
7//! the following lattice:
8//! ```ignore (not-rust)
9//! ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
10//! ```
11//! So, for example, if we see an assignment `x = 5` to an upvar `x`, we
12//! will promote its borrow kind to mutable borrow. If we see an `&mut x`
13//! we'll do the same. Naturally, this applies not just to the upvar, but
14//! to everything owned by `x`, so the result is the same for something
15//! like `x.f = 5` and so on (presuming `x` is not a borrowed pointer to a
16//! struct). These adjustments are performed in
17//! `adjust_for_non_move_closure` (you can trace backwards through the code
18//! from there).
19//!
20//! The fact that we are inferring borrow kinds as we go results in a
21//! semi-hacky interaction with the way `ExprUseVisitor` is computing
22//! `Place`s. In particular, it will query the current borrow kind as it
23//! goes, and we'll return the *current* value, but this may get
24//! adjusted later. Therefore, in this module, we generally ignore the
25//! borrow kind (and derived mutabilities) that `ExprUseVisitor` returns
26//! within `Place`s, since they may be inaccurate. (Another option
27//! would be to use a unification scheme, where instead of returning a
28//! concrete borrow kind like `ty::ImmBorrow`, we return a
29//! `ty::InferBorrow(upvar_id)` or something like that, but this would
30//! then mean that all later passes would have to check for these figments
31//! and report an error, and it just seems like more mess in the end.)
3233use std::iter;
3435use rustc_abi::FIRST_VARIANT;
36use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
37use rustc_data_structures::unord::{ExtendUnord, UnordSet};
38use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
39use rustc_hir::def_id::LocalDefId;
40use rustc_hir::intravisit::{self, Visitor};
41use rustc_hir::{selfas hir, HirId, find_attr};
42use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
43use rustc_middle::mir::FakeReadCause;
44use rustc_middle::traits::ObligationCauseCode;
45use rustc_middle::ty::{
46self, BorrowKind, ClosureSizeProfileData, Ty, TyCtxt, TypeVisitableExtas _, TypeckResults,
47Unnormalized, UpvarArgs, UpvarCapture,
48};
49use rustc_middle::{bug, span_bug};
50use rustc_session::lint;
51use rustc_span::{BytePos, Pos, Span, Symbol, sym};
52use rustc_trait_selection::infer::InferCtxtExt;
53use tracing::{debug, instrument};
5455use super::FnCtxt;
56use crate::expr_use_visitoras euv;
57use crate::expr_use_visitor::Delegateas _;
5859/// Describe the relationship between the paths of two places
60/// eg:
61/// - `foo` is ancestor of `foo.bar.baz`
62/// - `foo.bar.baz` is an descendant of `foo.bar`
63/// - `foo.bar` and `foo.baz` are divergent
64enum PlaceAncestryRelation {
65 Ancestor,
66 Descendant,
67 SamePlace,
68 Divergent,
69}
7071/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
72/// during capture analysis. Information in this map feeds into the minimum capture
73/// analysis pass.
74type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
7576impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
77pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
78InferBorrowKindVisitor { fcx: self }.visit_body(body);
7980// it's our job to process these.
81if !self.deferred_call_resolutions.borrow().is_empty() {
::core::panicking::panic("assertion failed: self.deferred_call_resolutions.borrow().is_empty()")
};assert!(self.deferred_call_resolutions.borrow().is_empty());
82 }
83}
8485/// Intermediate format to store the hir_id pointing to the use that resulted in the
86/// corresponding place being captured and a String which contains the captured value's
87/// name (i.e: a.b.c)
88#[derive(#[automatically_derived]
impl ::core::clone::Clone for UpvarMigrationInfo {
#[inline]
fn clone(&self) -> UpvarMigrationInfo {
match self {
UpvarMigrationInfo::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 } =>
UpvarMigrationInfo::CapturingPrecise {
source_expr: ::core::clone::Clone::clone(__self_0),
var_name: ::core::clone::Clone::clone(__self_1),
},
UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
UpvarMigrationInfo::CapturingNothing {
use_span: ::core::clone::Clone::clone(__self_0),
},
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for UpvarMigrationInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
UpvarMigrationInfo::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"CapturingPrecise", "source_expr", __self_0, "var_name",
&__self_1),
UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"CapturingNothing", "use_span", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for UpvarMigrationInfo {
#[inline]
fn eq(&self, other: &UpvarMigrationInfo) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(UpvarMigrationInfo::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 },
UpvarMigrationInfo::CapturingPrecise {
source_expr: __arg1_0, var_name: __arg1_1 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(UpvarMigrationInfo::CapturingNothing { use_span: __self_0 },
UpvarMigrationInfo::CapturingNothing { use_span: __arg1_0 })
=> __self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for UpvarMigrationInfo {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<HirId>>;
let _: ::core::cmp::AssertParamIsEq<String>;
let _: ::core::cmp::AssertParamIsEq<Span>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for UpvarMigrationInfo {
#[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 {
UpvarMigrationInfo::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 } => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
::core::hash::Hash::hash(__self_0, state),
}
}
}Hash)]
89enum UpvarMigrationInfo {
90/// We previously captured all of `x`, but now we capture some sub-path.
91CapturingPrecise { source_expr: Option<HirId>, var_name: String },
92 CapturingNothing {
93// where the variable appears in the closure (but is not captured)
94use_span: Span,
95 },
96}
9798/// Reasons that we might issue a migration warning.
99#[derive(#[automatically_derived]
impl ::core::clone::Clone for MigrationWarningReason {
#[inline]
fn clone(&self) -> MigrationWarningReason {
MigrationWarningReason {
auto_traits: ::core::clone::Clone::clone(&self.auto_traits),
drop_order: ::core::clone::Clone::clone(&self.drop_order),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for MigrationWarningReason {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"MigrationWarningReason", "auto_traits", &self.auto_traits,
"drop_order", &&self.drop_order)
}
}Debug, #[automatically_derived]
impl ::core::default::Default for MigrationWarningReason {
#[inline]
fn default() -> MigrationWarningReason {
MigrationWarningReason {
auto_traits: ::core::default::Default::default(),
drop_order: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]
impl ::core::cmp::PartialEq for MigrationWarningReason {
#[inline]
fn eq(&self, other: &MigrationWarningReason) -> bool {
self.drop_order == other.drop_order &&
self.auto_traits == other.auto_traits
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MigrationWarningReason {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Vec<&'static str>>;
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MigrationWarningReason {
#[inline]
fn partial_cmp(&self, other: &MigrationWarningReason)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MigrationWarningReason {
#[inline]
fn cmp(&self, other: &MigrationWarningReason) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.auto_traits, &other.auto_traits) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.drop_order, &other.drop_order),
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::hash::Hash for MigrationWarningReason {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.auto_traits, state);
::core::hash::Hash::hash(&self.drop_order, state)
}
}Hash)]
100struct MigrationWarningReason {
101/// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
102 /// in this vec, but now we don't.
103auto_traits: Vec<&'static str>,
104105/// When we used to capture `x` in its entirety, we would execute some destructors
106 /// at a different time.
107drop_order: bool,
108}
109110impl MigrationWarningReason {
111fn migration_message(&self) -> String {
112let base = "changes to closure capture in Rust 2021 will affect";
113if !self.auto_traits.is_empty() && self.drop_order {
114::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} drop order and which traits the closure implements",
base))
})format!("{base} drop order and which traits the closure implements")115 } else if self.drop_order {
116::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} drop order", base))
})format!("{base} drop order")117 } else {
118::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} which traits the closure implements",
base))
})format!("{base} which traits the closure implements")119 }
120 }
121}
122123/// Intermediate format to store information needed to generate a note in the migration lint.
124struct MigrationLintNote {
125 captures_info: UpvarMigrationInfo,
126127/// reasons why migration is needed for this capture
128reason: MigrationWarningReason,
129}
130131/// Intermediate format to store the hir id of the root variable and a HashSet containing
132/// information on why the root variable should be fully captured
133struct NeededMigration {
134 var_hir_id: HirId,
135 diagnostics_info: Vec<MigrationLintNote>,
136}
137138struct InferBorrowKindVisitor<'a, 'tcx> {
139 fcx: &'a FnCtxt<'a, 'tcx>,
140}
141142impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
143fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
144match expr.kind {
145 hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
146let body = self.fcx.tcx.hir_body(body_id);
147self.visit_body(body);
148self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
149 }
150_ => {}
151 }
152153 intravisit::walk_expr(self, expr);
154 }
155156fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
157let body = self.fcx.tcx.hir_body(c.body);
158self.visit_body(body);
159 }
160}
161162impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
163/// Analysis starting point.
164#[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("analyze_closure",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(164u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_hir_id",
"span", "body_id", "capture_clause"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_clause)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let ty = self.node_ty(closure_hir_id);
let (closure_def_id, args, infer_kind) =
match *ty.kind() {
ty::Closure(def_id, args) => {
(def_id, UpvarArgs::Closure(args),
self.closure_kind(ty).is_none())
}
ty::CoroutineClosure(def_id, args) => {
(def_id, UpvarArgs::CoroutineClosure(args),
self.closure_kind(ty).is_none())
}
ty::Coroutine(def_id, args) =>
(def_id, UpvarArgs::Coroutine(args), false),
ty::Error(_) => { return; }
_ => {
::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("type of closure expr {0:?} is not a closure {1:?}",
closure_hir_id, ty));
}
};
let args = self.resolve_vars_if_possible(args);
let closure_def_id = closure_def_id.expect_local();
match (&self.tcx.hir_body_owner_def_id(body.id()),
&closure_def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let closure_fcx =
FnCtxt::new(self, self.tcx.param_env(closure_def_id),
closure_def_id);
let mut delegate =
InferBorrowKind {
fcx: &closure_fcx,
closure_def_id,
capture_information: Default::default(),
fake_reads: Default::default(),
};
let _ =
euv::ExprUseVisitor::new(&closure_fcx,
&mut delegate).consume_body(body);
let explicit_captures =
match self.tcx.hir_node(closure_hir_id).expect_expr().kind {
hir::ExprKind::Closure(closure) =>
closure.explicit_captures,
_ =>
::rustc_middle::util::bug::bug_fmt(format_args!("expected closure expr for {0:?}",
closure_hir_id)),
};
for capture in explicit_captures {
let place =
closure_fcx.place_for_root_variable(closure_def_id,
capture.var_hir_id);
delegate.consume(&PlaceWithHirId {
hir_id: capture.var_hir_id,
place,
}, closure_hir_id);
}
if let UpvarArgs::Coroutine(..) = args &&
let hir::CoroutineKind::Desugared(_,
hir::CoroutineSource::Closure) =
self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
&&
let parent_hir_id =
self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
&& let parent_ty = self.node_ty(parent_hir_id) &&
let hir::CaptureBy::Value { move_kw } =
self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
{
if let Some(ty::ClosureKind::FnOnce) =
self.closure_kind(parent_ty) {
capture_clause = hir::CaptureBy::Value { move_kw };
} else if self.coroutine_body_consumes_upvars(closure_def_id,
body) {
capture_clause = hir::CaptureBy::Value { move_kw };
}
}
if let Some(hir::CoroutineKind::Desugared(_,
hir::CoroutineSource::Fn | hir::CoroutineSource::Closure)) =
self.tcx.coroutine_kind(closure_def_id) {
let hir::ExprKind::Block(block, _) =
body.value.kind else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));
};
for stmt in block.stmts {
let hir::StmtKind::Let(hir::LetStmt {
init: Some(init), source: hir::LocalSource::AsyncFn, pat, ..
}) =
stmt.kind else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));
};
let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No,
_), _, _, _) = pat.kind else { continue; };
let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) =
init.kind else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));
};
let hir::def::Res::Local(local_id) =
path.res else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));
};
let place =
closure_fcx.place_for_root_variable(closure_def_id,
local_id);
delegate.capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(init.hir_id),
path_expr_id: Some(init.hir_id),
capture_kind: UpvarCapture::ByValue,
}));
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:318",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(318u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::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!("For closure={0:?}, capture_information={1:#?}",
closure_def_id, delegate.capture_information) as
&dyn Value))])
});
} else { ; }
};
self.log_capture_analysis_first_pass(closure_def_id,
&delegate.capture_information, span);
let (capture_information, closure_kind, origin) =
self.process_collected_capture_information(capture_clause,
&delegate.capture_information);
self.compute_min_captures(closure_def_id, capture_information,
span);
let closure_hir_id =
self.tcx.local_def_id_to_hir_id(closure_def_id);
if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx,
closure_hir_id) {
self.perform_2229_migration_analysis(closure_def_id, body_id,
capture_clause, span);
}
let after_feature_tys = self.final_upvar_tys(closure_def_id);
if !enable_precise_capture(span) {
let mut capture_information:
InferredCaptureInformation<'tcx> = Default::default();
if let Some(upvars) =
self.tcx.upvars_mentioned(closure_def_id) {
for var_hir_id in upvars.keys() {
let place =
closure_fcx.place_for_root_variable(closure_def_id,
*var_hir_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:347",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(347u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::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!("seed place {0:?}",
place) as &dyn Value))])
});
} else { ; }
};
let capture_kind =
self.init_capture_kind_for_place(&place, capture_clause);
let fake_info =
ty::CaptureInfo {
capture_kind_expr_id: None,
path_expr_id: None,
capture_kind,
};
capture_information.push((place, fake_info));
}
}
self.compute_min_captures(closure_def_id, capture_information,
span);
}
let before_feature_tys = self.final_upvar_tys(closure_def_id);
if infer_kind {
let closure_kind_ty =
match args {
UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
UpvarArgs::CoroutineClosure(args) =>
args.as_coroutine_closure().kind_ty(),
UpvarArgs::Coroutine(_) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("coroutines don\'t have an inferred kind")));
}
};
self.demand_eqtype(span,
Ty::from_closure_kind(self.tcx, closure_kind),
closure_kind_ty);
if let Some(mut origin) = origin {
if !enable_precise_capture(span) {
origin.1.projections.clear()
}
self.typeck_results.borrow_mut().closure_kind_origins_mut().insert(closure_hir_id,
origin);
}
}
if let UpvarArgs::CoroutineClosure(args) = args {
if let Some(guar) = args.error_reported().err() {
self.demand_eqtype(span,
args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
Ty::new_error(self.tcx, guar));
} else {
let closure_env_region: ty::Region<'_> =
ty::Region::new_bound(self.tcx, ty::INNERMOST,
ty::BoundRegion {
var: ty::BoundVar::ZERO,
kind: ty::BoundRegionKind::ClosureEnv,
});
let num_args =
args.as_coroutine_closure().coroutine_closure_sig().skip_binder().tupled_inputs_ty.tuple_fields().len();
let typeck_results = self.typeck_results.borrow();
let tupled_upvars_ty_for_borrow =
Ty::new_tup_from_iter(self.tcx,
ty::analyze_coroutine_closure_captures(typeck_results.closure_min_captures_flattened(closure_def_id),
typeck_results.closure_min_captures_flattened(self.tcx.coroutine_for_closure(closure_def_id).expect_local()).skip(num_args),
|(_, parent_capture), (_, child_capture)|
{
let needs_ref =
should_reborrow_from_env_of_parent_coroutine_closure(parent_capture,
child_capture);
let upvar_ty = child_capture.place.ty();
let capture = child_capture.info.capture_kind;
apply_capture_kind_on_capture_ty(self.tcx, upvar_ty,
capture,
if needs_ref {
closure_env_region
} else { self.tcx.lifetimes.re_erased })
}));
let coroutine_captures_by_ref_ty =
Ty::new_fn_ptr(self.tcx,
ty::Binder::bind_with_vars(self.tcx.mk_fn_sig_safe_rust_abi([],
tupled_upvars_ty_for_borrow),
self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)])));
self.demand_eqtype(span,
args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
coroutine_captures_by_ref_ty);
if infer_kind {
let ty::Coroutine(_, coroutine_args) =
*self.typeck_results.borrow().expr_ty(body.value).kind() else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));
};
self.demand_eqtype(span,
coroutine_args.as_coroutine().kind_ty(),
Ty::from_coroutine_closure_kind(self.tcx, closure_kind));
}
}
}
self.log_closure_min_capture_info(closure_def_id, span);
let final_upvar_tys = self.final_upvar_tys(closure_def_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:519",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(519u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_hir_id",
"args", "final_upvar_tys"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&closure_hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&args) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&final_upvar_tys)
as &dyn Value))])
});
} else { ; }
};
if self.tcx.features().unsized_fn_params() {
for capture in
self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
{
if let UpvarCapture::ByValue = capture.info.capture_kind {
self.require_type_is_sized(capture.place.ty(),
capture.get_path_span(self.tcx),
ObligationCauseCode::SizedClosureCapture(closure_def_id));
}
}
}
let final_tupled_upvars_type =
Ty::new_tup(self.tcx, &final_upvar_tys);
self.demand_suptype(span, args.tupled_upvars_ty(),
final_tupled_upvars_type);
let fake_reads = delegate.fake_reads;
self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id,
fake_reads);
if self.tcx.sess.opts.unstable_opts.profile_closures {
self.typeck_results.borrow_mut().closure_size_eval.insert(closure_def_id,
ClosureSizeProfileData {
before_feature_tys: Ty::new_tup(self.tcx,
&before_feature_tys),
after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
});
}
let deferred_call_resolutions =
self.remove_deferred_call_resolutions(closure_def_id);
for deferred_call_resolution in deferred_call_resolutions {
deferred_call_resolution.resolve(&FnCtxt::new(self,
self.param_env, closure_def_id));
}
}
}
}#[instrument(skip(self, body), level = "debug")]165fn analyze_closure(
166&self,
167 closure_hir_id: HirId,
168 span: Span,
169 body_id: hir::BodyId,
170 body: &'tcx hir::Body<'tcx>,
171mut capture_clause: hir::CaptureBy,
172 ) {
173// Extract the type of the closure.
174let ty = self.node_ty(closure_hir_id);
175let (closure_def_id, args, infer_kind) = match *ty.kind() {
176 ty::Closure(def_id, args) => {
177 (def_id, UpvarArgs::Closure(args), self.closure_kind(ty).is_none())
178 }
179 ty::CoroutineClosure(def_id, args) => {
180 (def_id, UpvarArgs::CoroutineClosure(args), self.closure_kind(ty).is_none())
181 }
182 ty::Coroutine(def_id, args) => (def_id, UpvarArgs::Coroutine(args), false),
183 ty::Error(_) => {
184// #51714: skip analysis when we have already encountered type errors
185return;
186 }
187_ => {
188span_bug!(
189 span,
190"type of closure expr {:?} is not a closure {:?}",
191 closure_hir_id,
192 ty
193 );
194 }
195 };
196let args = self.resolve_vars_if_possible(args);
197let closure_def_id = closure_def_id.expect_local();
198199assert_eq!(self.tcx.hir_body_owner_def_id(body.id()), closure_def_id);
200201let closure_fcx = FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id);
202203let mut delegate = InferBorrowKind {
204 fcx: &closure_fcx,
205 closure_def_id,
206 capture_information: Default::default(),
207 fake_reads: Default::default(),
208 };
209210// First collect the captures implied by the operations in the closure
211 // body. This records how each place is actually used: borrowed, modified,
212 // moved, and so on.
213let _ = euv::ExprUseVisitor::new(&closure_fcx, &mut delegate).consume_body(body);
214215// `consume_body` only sees how the lowered closure body uses those
216 // places. For `move(foo).clone()`, the body may only borrow the
217 // synthetic local for `foo`, but the source `move(...)` still requires
218 // capturing that local by value.
219let explicit_captures = match self.tcx.hir_node(closure_hir_id).expect_expr().kind {
220 hir::ExprKind::Closure(closure) => closure.explicit_captures,
221_ => bug!("expected closure expr for {:?}", closure_hir_id),
222 };
223for capture in explicit_captures {
224let place = closure_fcx.place_for_root_variable(closure_def_id, capture.var_hir_id);
225 delegate.consume(&PlaceWithHirId { hir_id: capture.var_hir_id, place }, closure_hir_id);
226 }
227228// There are several curious situations with coroutine-closures where
229 // analysis is too aggressive with borrows when the coroutine-closure is
230 // marked `move`. Specifically:
231 //
232 // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
233 // inference, then it's still possible that we try to borrow upvars from
234 // the coroutine-closure because they are not used by the coroutine body
235 // in a way that forces a move. See the test:
236 // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
237 //
238 // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
239 // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
240 // would force the closure to `FnOnce`.
241 // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
242 //
243 // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
244 // coroutine bodies can't borrow from their parent closure. To fix this,
245 // we force the inner coroutine to also be `move`. This only matters for
246 // coroutine-closures that are `move` since otherwise they themselves will
247 // be borrowing from the outer environment, so there's no self-borrows occurring.
248if let UpvarArgs::Coroutine(..) = args
249 && let hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) =
250self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
251 && let parent_hir_id =
252self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
253 && let parent_ty = self.node_ty(parent_hir_id)
254 && let hir::CaptureBy::Value { move_kw } =
255self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
256 {
257// (1.) Closure signature inference forced this closure to `FnOnce`.
258if let Some(ty::ClosureKind::FnOnce) = self.closure_kind(parent_ty) {
259 capture_clause = hir::CaptureBy::Value { move_kw };
260 }
261// (2.) The way that the closure uses its upvars means it's `FnOnce`.
262else if self.coroutine_body_consumes_upvars(closure_def_id, body) {
263 capture_clause = hir::CaptureBy::Value { move_kw };
264 }
265 }
266267// As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
268 // to `ByRef` for the `async {}` block internal to async fns/closure. This means
269 // that we would *not* be moving all of the parameters into the async block in all cases.
270 // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
271 // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
272 //
273 // We force all of these arguments to be captured by move before we do expr use analysis.
274 //
275 // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
276 // moving all of the `LocalSource::AsyncFn` locals here.
277if let Some(hir::CoroutineKind::Desugared(
278_,
279 hir::CoroutineSource::Fn | hir::CoroutineSource::Closure,
280 )) = self.tcx.coroutine_kind(closure_def_id)
281 {
282let hir::ExprKind::Block(block, _) = body.value.kind else {
283bug!();
284 };
285for stmt in block.stmts {
286let hir::StmtKind::Let(hir::LetStmt {
287 init: Some(init),
288 source: hir::LocalSource::AsyncFn,
289 pat,
290 ..
291 }) = stmt.kind
292else {
293bug!();
294 };
295let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), _, _, _) = pat.kind
296else {
297// Complex pattern, skip the non-upvar local.
298continue;
299 };
300let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = init.kind else {
301bug!();
302 };
303let hir::def::Res::Local(local_id) = path.res else {
304bug!();
305 };
306let place = closure_fcx.place_for_root_variable(closure_def_id, local_id);
307 delegate.capture_information.push((
308 place,
309 ty::CaptureInfo {
310 capture_kind_expr_id: Some(init.hir_id),
311 path_expr_id: Some(init.hir_id),
312 capture_kind: UpvarCapture::ByValue,
313 },
314 ));
315 }
316 }
317318debug!(
319"For closure={:?}, capture_information={:#?}",
320 closure_def_id, delegate.capture_information
321 );
322323self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
324325let (capture_information, closure_kind, origin) = self
326.process_collected_capture_information(capture_clause, &delegate.capture_information);
327328self.compute_min_captures(closure_def_id, capture_information, span);
329330let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
331332if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
333self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
334 }
335336let after_feature_tys = self.final_upvar_tys(closure_def_id);
337338// We now fake capture information for all variables that are mentioned within the closure
339 // We do this after handling migrations so that min_captures computes before
340if !enable_precise_capture(span) {
341let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
342343if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
344for var_hir_id in upvars.keys() {
345let place = closure_fcx.place_for_root_variable(closure_def_id, *var_hir_id);
346347debug!("seed place {:?}", place);
348349let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
350let fake_info = ty::CaptureInfo {
351 capture_kind_expr_id: None,
352 path_expr_id: None,
353 capture_kind,
354 };
355356 capture_information.push((place, fake_info));
357 }
358 }
359360// This will update the min captures based on this new fake information.
361self.compute_min_captures(closure_def_id, capture_information, span);
362 }
363364let before_feature_tys = self.final_upvar_tys(closure_def_id);
365366if infer_kind {
367// Unify the (as yet unbound) type variable in the closure
368 // args with the kind we inferred.
369let closure_kind_ty = match args {
370 UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
371 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
372 UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
373 };
374self.demand_eqtype(
375 span,
376 Ty::from_closure_kind(self.tcx, closure_kind),
377 closure_kind_ty,
378 );
379380// If we have an origin, store it.
381if let Some(mut origin) = origin {
382if !enable_precise_capture(span) {
383// Without precise captures, we just capture the base and ignore
384 // the projections.
385origin.1.projections.clear()
386 }
387388self.typeck_results
389 .borrow_mut()
390 .closure_kind_origins_mut()
391 .insert(closure_hir_id, origin);
392 }
393 }
394395// For coroutine-closures, we additionally must compute the
396 // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
397 // version of the coroutine-closure's output coroutine.
398 //
399 // If the args already reference an error, computing the by-ref upvar
400 // tuple may itself reach malformed types. We still equate the
401 // `coroutine_captures_by_ref_ty` inference variable to an error type
402 // so downstream consumers (e.g. `has_self_borrows`) can rely on it
403 // being resolved to either an `FnPtr` or `Error` rather than remaining
404 // an unconstrained inference variable.
405if let UpvarArgs::CoroutineClosure(args) = args {
406if let Some(guar) = args.error_reported().err() {
407self.demand_eqtype(
408 span,
409 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
410 Ty::new_error(self.tcx, guar),
411 );
412 } else {
413let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
414self.tcx,
415 ty::INNERMOST,
416 ty::BoundRegion {
417 var: ty::BoundVar::ZERO,
418 kind: ty::BoundRegionKind::ClosureEnv,
419 },
420 );
421422let num_args = args
423 .as_coroutine_closure()
424 .coroutine_closure_sig()
425 .skip_binder()
426 .tupled_inputs_ty
427 .tuple_fields()
428 .len();
429let typeck_results = self.typeck_results.borrow();
430431let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
432self.tcx,
433 ty::analyze_coroutine_closure_captures(
434 typeck_results.closure_min_captures_flattened(closure_def_id),
435 typeck_results
436 .closure_min_captures_flattened(
437self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
438 )
439// Skip the captures that are just moving the closure's args
440 // into the coroutine. These are always by move, and we append
441 // those later in the `CoroutineClosureSignature` helper functions.
442.skip(num_args),
443 |(_, parent_capture), (_, child_capture)| {
444// This is subtle. See documentation on function.
445let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
446 parent_capture,
447 child_capture,
448 );
449450let upvar_ty = child_capture.place.ty();
451let capture = child_capture.info.capture_kind;
452// Not all upvars are captured by ref, so use
453 // `apply_capture_kind_on_capture_ty` to ensure that we
454 // compute the right captured type.
455apply_capture_kind_on_capture_ty(
456self.tcx,
457 upvar_ty,
458 capture,
459if needs_ref {
460 closure_env_region
461 } else {
462self.tcx.lifetimes.re_erased
463 },
464 )
465 },
466 ),
467 );
468let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
469self.tcx,
470 ty::Binder::bind_with_vars(
471self.tcx.mk_fn_sig_safe_rust_abi([], tupled_upvars_ty_for_borrow),
472self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
473 ty::BoundRegionKind::ClosureEnv,
474 )]),
475 ),
476 );
477self.demand_eqtype(
478 span,
479 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
480 coroutine_captures_by_ref_ty,
481 );
482483// Additionally, we can now constrain the coroutine's kind type.
484 //
485 // We only do this if `infer_kind`, because if we have constrained
486 // the kind from closure signature inference, the kind inferred
487 // for the inner coroutine may actually be more restrictive.
488if infer_kind {
489let ty::Coroutine(_, coroutine_args) =
490*self.typeck_results.borrow().expr_ty(body.value).kind()
491else {
492bug!();
493 };
494self.demand_eqtype(
495 span,
496 coroutine_args.as_coroutine().kind_ty(),
497 Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
498 );
499 }
500 }
501 }
502503self.log_closure_min_capture_info(closure_def_id, span);
504505// Now that we've analyzed the closure, we know how each
506 // variable is borrowed, and we know what traits the closure
507 // implements (Fn vs FnMut etc). We now have some updates to do
508 // with that information.
509 //
510 // Note that no closure type C may have an upvar of type C
511 // (though it may reference itself via a trait object). This
512 // results from the desugaring of closures to a struct like
513 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
514 // C, then the type would have infinite size (and the
515 // inference algorithm will reject it).
516517 // Equate the type variables for the upvars with the actual types.
518let final_upvar_tys = self.final_upvar_tys(closure_def_id);
519debug!(?closure_hir_id, ?args, ?final_upvar_tys);
520521if self.tcx.features().unsized_fn_params() {
522for capture in
523self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
524 {
525if let UpvarCapture::ByValue = capture.info.capture_kind {
526self.require_type_is_sized(
527 capture.place.ty(),
528 capture.get_path_span(self.tcx),
529 ObligationCauseCode::SizedClosureCapture(closure_def_id),
530 );
531 }
532 }
533 }
534535// Build a tuple (U0..Un) of the final upvar types U0..Un
536 // and unify the upvar tuple type in the closure with it:
537let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
538self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
539540let fake_reads = delegate.fake_reads;
541542self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
543544if self.tcx.sess.opts.unstable_opts.profile_closures {
545self.typeck_results.borrow_mut().closure_size_eval.insert(
546 closure_def_id,
547 ClosureSizeProfileData {
548 before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
549 after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
550 },
551 );
552 }
553554// If we are also inferred the closure kind here,
555 // process any deferred resolutions.
556let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
557for deferred_call_resolution in deferred_call_resolutions {
558 deferred_call_resolution.resolve(&FnCtxt::new(self, self.param_env, closure_def_id));
559 }
560 }
561562/// Determines whether the body of the coroutine uses its upvars in a way that
563 /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
564 /// In a more detailed comment above, we care whether this happens, since if
565 /// this happens, we want to force the coroutine to move all of the upvars it
566 /// would've borrowed from the parent coroutine-closure.
567 ///
568 /// This only really makes sense to be called on the child coroutine of a
569 /// coroutine-closure.
570fn coroutine_body_consumes_upvars(
571&self,
572 coroutine_def_id: LocalDefId,
573 body: &'tcx hir::Body<'tcx>,
574 ) -> bool {
575// This block contains argument capturing details. Since arguments
576 // aren't upvars, we do not care about them for determining if the
577 // coroutine body actually consumes its upvars.
578let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
579else {
580::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
581 };
582// Specifically, we only care about the *real* body of the coroutine.
583 // We skip out into the drop-temps within the block of the body in order
584 // to skip over the args of the desugaring.
585let hir::ExprKind::DropTemps(body) = body.kind else {
586::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
587 };
588589let coroutine_fcx =
590FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id);
591592let mut delegate = InferBorrowKind {
593 fcx: &coroutine_fcx,
594 closure_def_id: coroutine_def_id,
595 capture_information: Default::default(),
596 fake_reads: Default::default(),
597 };
598599let _ = euv::ExprUseVisitor::new(&coroutine_fcx, &mut delegate).consume_expr(body);
600601let (_, kind, _) = self.process_collected_capture_information(
602 hir::CaptureBy::Ref,
603&delegate.capture_information,
604 );
605606#[allow(non_exhaustive_omitted_patterns)] match kind {
ty::ClosureKind::FnOnce => true,
_ => false,
}matches!(kind, ty::ClosureKind::FnOnce)607 }
608609// Returns a list of `Ty`s for each upvar.
610fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
611self.typeck_results
612 .borrow()
613 .closure_min_captures_flattened(closure_id)
614 .map(|captured_place| {
615let upvar_ty = captured_place.place.ty();
616let capture = captured_place.info.capture_kind;
617618{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:618",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(618u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["captured_place.place",
"upvar_ty", "capture", "captured_place.mutability"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&captured_place.place)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&upvar_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&capture) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&captured_place.mutability)
as &dyn Value))])
});
} else { ; }
};debug!(?captured_place.place, ?upvar_ty, ?capture, ?captured_place.mutability);
619620apply_capture_kind_on_capture_ty(
621self.tcx,
622upvar_ty,
623capture,
624self.tcx.lifetimes.re_erased,
625 )
626 })
627 .collect()
628 }
629630/// Adjusts the closure capture information to ensure that the operations aren't unsafe,
631 /// and that the path can be captured with required capture kind (depending on use in closure,
632 /// move closure etc.)
633 ///
634 /// Returns the set of adjusted information along with the inferred closure kind and span
635 /// associated with the closure kind inference.
636 ///
637 /// Note that we *always* infer a minimal kind, even if
638 /// we don't always *use* that in the final result (i.e., sometimes
639 /// we've taken the closure kind from the expectations instead, and
640 /// for coroutines we don't even implement the closure traits
641 /// really).
642 ///
643 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
644 /// contains a `Some()` with the `Place` that caused us to do so.
645fn process_collected_capture_information(
646&self,
647 capture_clause: hir::CaptureBy,
648 capture_information: &InferredCaptureInformation<'tcx>,
649 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
650let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
651let mut origin: Option<(Span, Place<'tcx>)> = None;
652653let processed = capture_information654 .iter()
655 .cloned()
656 .map(|(place, mut capture_info)| {
657// Apply rules for safety before inferring closure kind
658let (place, capture_kind) =
659restrict_capture_precision(place, capture_info.capture_kind);
660661let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
662663let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
664self.tcx.hir_span(usage_expr)
665 } else {
666::core::panicking::panic("internal error: entered unreachable code")unreachable!()667 };
668669let updated = match capture_kind {
670 ty::UpvarCapture::ByValue => match closure_kind {
671 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
672 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
673 }
674// If closure is already FnOnce, don't update
675ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
676 },
677678 ty::UpvarCapture::ByRef(
679 ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
680 ) => {
681match closure_kind {
682 ty::ClosureKind::Fn => {
683 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
684 }
685// Don't update the origin
686ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
687 (closure_kind, origin.take())
688 }
689 }
690 }
691692_ => (closure_kind, origin.take()),
693 };
694695closure_kind = updated.0;
696origin = updated.1;
697698let (place, capture_kind) = match capture_clause {
699 hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
700 hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
701 hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
702 };
703704// This restriction needs to be applied after we have handled adjustments for `move`
705 // closures. We want to make sure any adjustment that might make us move the place into
706 // the closure gets handled.
707let (place, capture_kind) =
708restrict_precision_for_drop_types(self, place, capture_kind);
709710capture_info.capture_kind = capture_kind;
711 (place, capture_info)
712 })
713 .collect();
714715 (processed, closure_kind, origin)
716 }
717718/// Analyzes the information collected by `InferBorrowKind` to compute the min number of
719 /// Places (and corresponding capture kind) that we need to keep track of to support all
720 /// the required captured paths.
721 ///
722 ///
723 /// Note: If this function is called multiple times for the same closure, it will update
724 /// the existing min_capture map that is stored in TypeckResults.
725 ///
726 /// Eg:
727 /// ```
728 /// #[derive(Debug)]
729 /// struct Point { x: i32, y: i32 }
730 ///
731 /// let s = String::from("s"); // hir_id_s
732 /// let mut p = Point { x: 2, y: -2 }; // his_id_p
733 /// let c = || {
734 /// println!("{s:?}"); // L1
735 /// p.x += 10; // L2
736 /// println!("{}" , p.y); // L3
737 /// println!("{p:?}"); // L4
738 /// drop(s); // L5
739 /// };
740 /// ```
741 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
742 /// the lines L1..5 respectively.
743 ///
744 /// InferBorrowKind results in a structure like this:
745 ///
746 /// ```ignore (illustrative)
747 /// {
748 /// Place(base: hir_id_s, projections: [], ....) -> {
749 /// capture_kind_expr: hir_id_L5,
750 /// path_expr_id: hir_id_L5,
751 /// capture_kind: ByValue
752 /// },
753 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
754 /// capture_kind_expr: hir_id_L2,
755 /// path_expr_id: hir_id_L2,
756 /// capture_kind: ByValue
757 /// },
758 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
759 /// capture_kind_expr: hir_id_L3,
760 /// path_expr_id: hir_id_L3,
761 /// capture_kind: ByValue
762 /// },
763 /// Place(base: hir_id_p, projections: [], ...) -> {
764 /// capture_kind_expr: hir_id_L4,
765 /// path_expr_id: hir_id_L4,
766 /// capture_kind: ByValue
767 /// },
768 /// }
769 /// ```
770 ///
771 /// After the min capture analysis, we get:
772 /// ```ignore (illustrative)
773 /// {
774 /// hir_id_s -> [
775 /// Place(base: hir_id_s, projections: [], ....) -> {
776 /// capture_kind_expr: hir_id_L5,
777 /// path_expr_id: hir_id_L5,
778 /// capture_kind: ByValue
779 /// },
780 /// ],
781 /// hir_id_p -> [
782 /// Place(base: hir_id_p, projections: [], ...) -> {
783 /// capture_kind_expr: hir_id_L2,
784 /// path_expr_id: hir_id_L4,
785 /// capture_kind: ByValue
786 /// },
787 /// ],
788 /// }
789 /// ```
790#[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("compute_min_captures",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(790u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_def_id",
"capture_information", "closure_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_information)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if capture_information.is_empty() { return; }
let mut typeck_results = self.typeck_results.borrow_mut();
let mut root_var_min_capture_list =
typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
for (mut place, capture_info) in capture_information.into_iter() {
let var_hir_id =
match place.base {
PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
base =>
::rustc_middle::util::bug::bug_fmt(format_args!("Expected upvar, found={0:?}",
base)),
};
let var_ident = self.tcx.hir_ident(var_hir_id);
let Some(min_cap_list) =
root_var_min_capture_list.get_mut(&var_hir_id) else {
let mutability =
self.determine_capture_mutability(&typeck_results, &place);
let min_cap_list =
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ty::CapturedPlace {
var_ident,
place,
info: capture_info,
mutability,
}]));
root_var_min_capture_list.insert(var_hir_id, min_cap_list);
continue;
};
let mut descendant_found = false;
let mut updated_capture_info = capture_info;
min_cap_list.retain(|possible_descendant|
{
match determine_place_ancestry_relation(&place,
&possible_descendant.place) {
PlaceAncestryRelation::Ancestor => {
descendant_found = true;
let mut possible_descendant = possible_descendant.clone();
let backup_path_expr_id = updated_capture_info.path_expr_id;
truncate_place_to_len_and_update_capture_kind(&mut possible_descendant.place,
&mut possible_descendant.info.capture_kind,
place.projections.len());
updated_capture_info =
determine_capture_info(updated_capture_info,
possible_descendant.info);
updated_capture_info.path_expr_id = backup_path_expr_id;
false
}
_ => true,
}
});
let mut ancestor_found = false;
if !descendant_found {
for possible_ancestor in min_cap_list.iter_mut() {
match determine_place_ancestry_relation(&place,
&possible_ancestor.place) {
PlaceAncestryRelation::SamePlace => {
ancestor_found = true;
possible_ancestor.info =
determine_capture_info(possible_ancestor.info,
updated_capture_info);
break;
}
PlaceAncestryRelation::Descendant => {
ancestor_found = true;
let backup_path_expr_id =
possible_ancestor.info.path_expr_id;
truncate_place_to_len_and_update_capture_kind(&mut place,
&mut updated_capture_info.capture_kind,
possible_ancestor.place.projections.len());
possible_ancestor.info =
determine_capture_info(possible_ancestor.info,
updated_capture_info);
possible_ancestor.info.path_expr_id = backup_path_expr_id;
break;
}
_ => {}
}
}
}
if !ancestor_found {
let mutability =
self.determine_capture_mutability(&typeck_results, &place);
let captured_place =
ty::CapturedPlace {
var_ident,
place,
info: updated_capture_info,
mutability,
};
min_cap_list.push(captured_place);
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:915",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(915u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::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!("For closure={0:?}, min_captures before sorting={1:?}",
closure_def_id, root_var_min_capture_list) as &dyn Value))])
});
} else { ; }
};
for (_, captures) in &mut root_var_min_capture_list {
captures.sort_by(|capture1, capture2|
{
fn is_field<'a>(p: &&Projection<'a>) -> bool {
match p.kind {
ProjectionKind::Field(_, _) => true,
ProjectionKind::Deref | ProjectionKind::OpaqueCast |
ProjectionKind::UnwrapUnsafeBinder => false,
p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
::rustc_middle::util::bug::bug_fmt(format_args!("ProjectionKind {0:?} was unexpected",
p))
}
}
}
let capture1_field_projections =
capture1.place.projections.iter().filter(is_field);
let capture2_field_projections =
capture2.place.projections.iter().filter(is_field);
for (p1, p2) in
capture1_field_projections.zip(capture2_field_projections) {
match (p1.kind, p2.kind) {
(ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _))
=> {
if i1 != i2 { return i1.cmp(&i2); }
}
(l, r) =>
::rustc_middle::util::bug::bug_fmt(format_args!("ProjectionKinds {0:?} or {1:?} were unexpected",
l, r)),
}
}
self.dcx().span_delayed_bug(closure_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("two identical projections: ({0:?}, {1:?})",
capture1.place.projections, capture2.place.projections))
}));
std::cmp::Ordering::Equal
});
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:976",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(976u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::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!("For closure={0:?}, min_captures after sorting={1:#?}",
closure_def_id, root_var_min_capture_list) as &dyn Value))])
});
} else { ; }
};
typeck_results.closure_min_captures.insert(closure_def_id,
root_var_min_capture_list);
}
}
}#[instrument(level = "debug", skip(self))]791fn compute_min_captures(
792&self,
793 closure_def_id: LocalDefId,
794 capture_information: InferredCaptureInformation<'tcx>,
795 closure_span: Span,
796 ) {
797if capture_information.is_empty() {
798return;
799 }
800801let mut typeck_results = self.typeck_results.borrow_mut();
802803let mut root_var_min_capture_list =
804 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
805806for (mut place, capture_info) in capture_information.into_iter() {
807let var_hir_id = match place.base {
808 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
809 base => bug!("Expected upvar, found={:?}", base),
810 };
811let var_ident = self.tcx.hir_ident(var_hir_id);
812813let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
814let mutability = self.determine_capture_mutability(&typeck_results, &place);
815let min_cap_list =
816vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
817 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
818continue;
819 };
820821// Go through each entry in the current list of min_captures
822 // - if ancestor is found, update its capture kind to account for current place's
823 // capture information.
824 //
825 // - if descendant is found, remove it from the list, and update the current place's
826 // capture information to account for the descendant's capture kind.
827 //
828 // We can never be in a case where the list contains both an ancestor and a descendant
829 // Also there can only be ancestor but in case of descendants there might be
830 // multiple.
831832let mut descendant_found = false;
833let mut updated_capture_info = capture_info;
834 min_cap_list.retain(|possible_descendant| {
835match determine_place_ancestry_relation(&place, &possible_descendant.place) {
836// current place is ancestor of possible_descendant
837PlaceAncestryRelation::Ancestor => {
838 descendant_found = true;
839840let mut possible_descendant = possible_descendant.clone();
841let backup_path_expr_id = updated_capture_info.path_expr_id;
842843// Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
844 // possible change in capture mode.
845truncate_place_to_len_and_update_capture_kind(
846&mut possible_descendant.place,
847&mut possible_descendant.info.capture_kind,
848 place.projections.len(),
849 );
850851 updated_capture_info =
852 determine_capture_info(updated_capture_info, possible_descendant.info);
853854// we need to keep the ancestor's `path_expr_id`
855updated_capture_info.path_expr_id = backup_path_expr_id;
856false
857}
858859_ => true,
860 }
861 });
862863let mut ancestor_found = false;
864if !descendant_found {
865for possible_ancestor in min_cap_list.iter_mut() {
866match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
867 PlaceAncestryRelation::SamePlace => {
868 ancestor_found = true;
869 possible_ancestor.info = determine_capture_info(
870 possible_ancestor.info,
871 updated_capture_info,
872 );
873874// Only one related place will be in the list.
875break;
876 }
877// current place is descendant of possible_ancestor
878PlaceAncestryRelation::Descendant => {
879 ancestor_found = true;
880let backup_path_expr_id = possible_ancestor.info.path_expr_id;
881882// Truncate the descendant (current place) to be same as the ancestor to handle any
883 // possible change in capture mode.
884truncate_place_to_len_and_update_capture_kind(
885&mut place,
886&mut updated_capture_info.capture_kind,
887 possible_ancestor.place.projections.len(),
888 );
889890 possible_ancestor.info = determine_capture_info(
891 possible_ancestor.info,
892 updated_capture_info,
893 );
894895// we need to keep the ancestor's `path_expr_id`
896possible_ancestor.info.path_expr_id = backup_path_expr_id;
897898// Only one related place will be in the list.
899break;
900 }
901_ => {}
902 }
903 }
904 }
905906// Only need to insert when we don't have an ancestor in the existing min capture list
907if !ancestor_found {
908let mutability = self.determine_capture_mutability(&typeck_results, &place);
909let captured_place =
910 ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
911 min_cap_list.push(captured_place);
912 }
913 }
914915debug!(
916"For closure={:?}, min_captures before sorting={:?}",
917 closure_def_id, root_var_min_capture_list
918 );
919920// Now that we have the minimized list of captures, sort the captures by field id.
921 // This causes the closure to capture the upvars in the same order as the fields are
922 // declared which is also the drop order. Thus, in situations where we capture all the
923 // fields of some type, the observable drop order will remain the same as it previously
924 // was even though we're dropping each capture individually.
925 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
926 // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
927for (_, captures) in &mut root_var_min_capture_list {
928 captures.sort_by(|capture1, capture2| {
929fn is_field<'a>(p: &&Projection<'a>) -> bool {
930match p.kind {
931 ProjectionKind::Field(_, _) => true,
932 ProjectionKind::Deref
933 | ProjectionKind::OpaqueCast
934 | ProjectionKind::UnwrapUnsafeBinder => false,
935 p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
936bug!("ProjectionKind {:?} was unexpected", p)
937 }
938 }
939 }
940941// Need to sort only by Field projections, so filter away others.
942 // A previous implementation considered other projection types too
943 // but that caused ICE #118144
944let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
945let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
946947for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
948// We do not need to look at the `Projection.ty` fields here because at each
949 // step of the iteration, the projections will either be the same and therefore
950 // the types must be as well or the current projection will be different and
951 // we will return the result of comparing the field indexes.
952match (p1.kind, p2.kind) {
953 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
954// Compare only if paths are different.
955 // Otherwise continue to the next iteration
956if i1 != i2 {
957return i1.cmp(&i2);
958 }
959 }
960// Given the filter above, this arm should never be hit
961(l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
962 }
963 }
964965self.dcx().span_delayed_bug(
966 closure_span,
967format!(
968"two identical projections: ({:?}, {:?})",
969 capture1.place.projections, capture2.place.projections
970 ),
971 );
972 std::cmp::Ordering::Equal
973 });
974 }
975976debug!(
977"For closure={:?}, min_captures after sorting={:#?}",
978 closure_def_id, root_var_min_capture_list
979 );
980 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
981 }
982983/// Perform the migration analysis for RFC 2229, and emit lint
984 /// `disjoint_capture_drop_reorder` if needed.
985fn perform_2229_migration_analysis(
986&self,
987 closure_def_id: LocalDefId,
988 body_id: hir::BodyId,
989 capture_clause: hir::CaptureBy,
990 span: Span,
991 ) {
992struct MigrationLint<'a, 'tcx> {
993 closure_def_id: LocalDefId,
994 this: &'a FnCtxt<'a, 'tcx>,
995 body_id: hir::BodyId,
996 need_migrations: Vec<NeededMigration>,
997 migration_message: String,
998 }
9991000impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for MigrationLint<'b, 'tcx> {
1001fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
1002let Self { closure_def_id, this, body_id, need_migrations, migration_message } =
1003self;
1004let mut lint = Diag::new(dcx, level, migration_message);
10051006let (migration_string, migrated_variables_concat) =
1007migration_suggestion_for_2229(this.tcx, &need_migrations);
10081009let closure_hir_id = this.tcx.local_def_id_to_hir_id(closure_def_id);
1010let closure_head_span = this.tcx.def_span(closure_def_id);
10111012for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
1013// Labels all the usage of the captured variable and why they are responsible
1014 // for migration being needed
1015for lint_note in diagnostics_info.iter() {
1016match &lint_note.captures_info {
1017 UpvarMigrationInfo::CapturingPrecise {
1018 source_expr: Some(capture_expr_id),
1019 var_name: captured_name,
1020 } => {
1021let cause_span = this.tcx.hir_span(*capture_expr_id);
1022 lint.span_label(cause_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in Rust 2018, this closure captures all of `{0}`, but in Rust 2021, it will only capture `{1}`",
this.tcx.hir_name(*var_hir_id), captured_name))
})format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`",
1023 this.tcx.hir_name(*var_hir_id),
1024 captured_name,
1025 ));
1026 }
1027 UpvarMigrationInfo::CapturingNothing { use_span } => {
1028 lint.span_label(*use_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in Rust 2018, this causes the closure to capture `{0}`, but in Rust 2021, it has no effect",
this.tcx.hir_name(*var_hir_id)))
})format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
1029 this.tcx.hir_name(*var_hir_id),
1030 ));
1031 }
10321033_ => {}
1034 }
10351036// Add a label pointing to where a captured variable affected by drop order
1037 // is dropped
1038if lint_note.reason.drop_order {
1039let drop_location_span = drop_location_span(this.tcx, closure_hir_id);
10401041match &lint_note.captures_info {
1042 UpvarMigrationInfo::CapturingPrecise {
1043 var_name: captured_name,
1044 ..
1045 } => {
1046 lint.span_label(drop_location_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in Rust 2018, `{0}` is dropped here, but in Rust 2021, only `{1}` will be dropped here as part of the closure",
this.tcx.hir_name(*var_hir_id), captured_name))
})format!("in Rust 2018, `{}` is dropped here, but in Rust 2021, only `{}` will be dropped here as part of the closure",
1047 this.tcx.hir_name(*var_hir_id),
1048 captured_name,
1049 ));
1050 }
1051 UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1052 lint.span_label(drop_location_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in Rust 2018, `{0}` is dropped here along with the closure, but in Rust 2021 `{0}` is not part of the closure",
this.tcx.hir_name(*var_hir_id)))
})format!("in Rust 2018, `{v}` is dropped here along with the closure, but in Rust 2021 `{v}` is not part of the closure",
1053 v = this.tcx.hir_name(*var_hir_id),
1054 ));
1055 }
1056 }
1057 }
10581059// Add a label explaining why a closure no longer implements a trait
1060for &missing_trait in &lint_note.reason.auto_traits {
1061// not capturing something anymore cannot cause a trait to fail to be implemented:
1062match &lint_note.captures_info {
1063 UpvarMigrationInfo::CapturingPrecise {
1064 var_name: captured_name,
1065 ..
1066 } => {
1067let var_name = this.tcx.hir_name(*var_hir_id);
1068 lint.span_label(
1069 closure_head_span,
1070::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in Rust 2018, this closure implements {0} as `{1}` implements {0}, but in Rust 2021, this closure will no longer implement {0} because `{1}` is not fully captured and `{2}` does not implement {0}",
missing_trait, var_name, captured_name))
})format!(
1071"\
1072 in Rust 2018, this closure implements {missing_trait} \
1073 as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1074 this closure will no longer implement {missing_trait} \
1075 because `{var_name}` is not fully captured \
1076 and `{captured_name}` does not implement {missing_trait}"
1077),
1078 );
1079 }
10801081// Cannot happen: if we don't capture a variable, we impl strictly more traits
1082 UpvarMigrationInfo::CapturingNothing { use_span } => ::rustc_middle::util::bug::span_bug_fmt(*use_span,
format_args!("missing trait from not capturing something"))span_bug!(
1083*use_span,
1084"missing trait from not capturing something"
1085),
1086 }
1087 }
1088 }
1089 }
10901091let diagnostic_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add a dummy let to cause {0} to be fully captured",
migrated_variables_concat))
})format!(
1092"add a dummy let to cause {migrated_variables_concat} to be fully captured"
1093);
10941095let closure_span = this.tcx.hir_span_with_body(closure_hir_id);
1096let mut closure_body_span = {
1097// If the body was entirely expanded from a macro
1098 // invocation, i.e. the body is not contained inside the
1099 // closure span, then we walk up the expansion until we
1100 // find the span before the expansion.
1101let s = this.tcx.hir_span_with_body(body_id.hir_id);
1102s.find_ancestor_inside(closure_span).unwrap_or(s)
1103 };
11041105if let Ok(mut s) = this.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1106if s.starts_with('$') {
1107// Looks like a macro fragment. Try to find the real block.
1108if let hir::Node::Expr(&hir::Expr {
1109 kind: hir::ExprKind::Block(block, ..),
1110 ..
1111 }) = this.tcx.hir_node(body_id.hir_id)
1112 {
1113// If the body is a block (with `{..}`), we use the span of that block.
1114 // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1115 // Since we know it's a block, we know we can insert the `let _ = ..` without
1116 // breaking the macro syntax.
1117if let Ok(snippet) =
1118this.tcx.sess.source_map().span_to_snippet(block.span)
1119 {
1120closure_body_span = block.span;
1121s = snippet;
1122 }
1123 }
1124 }
11251126let mut lines = s.lines();
1127let line1 = lines.next().unwrap_or_default();
11281129if line1.trim_end() == "{" {
1130// This is a multi-line closure with just a `{` on the first line,
1131 // so we put the `let` on its own line.
1132 // We take the indentation from the next non-empty line.
1133let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1134let indent =
1135line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1136lint.span_suggestion(
1137closure_body_span1138 .with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len()))
1139 .shrink_to_lo(),
1140diagnostic_msg,
1141::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}{1};", indent,
migration_string))
})format!("\n{indent}{migration_string};"),
1142 Applicability::MachineApplicable,
1143 );
1144 } else if line1.starts_with('{') {
1145// This is a closure with its body wrapped in
1146 // braces, but with more than just the opening
1147 // brace on the first line. We put the `let`
1148 // directly after the `{`.
1149lint.span_suggestion(
1150closure_body_span1151 .with_lo(closure_body_span.lo() + BytePos(1))
1152 .shrink_to_lo(),
1153diagnostic_msg,
1154::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0};", migration_string))
})format!(" {migration_string};"),
1155 Applicability::MachineApplicable,
1156 );
1157 } else {
1158// This is a closure without braces around the body.
1159 // We add braces to add the `let` before the body.
1160lint.multipart_suggestion(
1161diagnostic_msg,
1162::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(closure_body_span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{ {0}; ",
migration_string))
})), (closure_body_span.shrink_to_hi(), " }".to_string())]))vec![
1163 (
1164 closure_body_span.shrink_to_lo(),
1165format!("{{ {migration_string}; "),
1166 ),
1167 (closure_body_span.shrink_to_hi(), " }".to_string()),
1168 ],
1169 Applicability::MachineApplicable,
1170 );
1171 }
1172 } else {
1173lint.span_suggestion(
1174closure_span,
1175diagnostic_msg,
1176migration_string,
1177 Applicability::HasPlaceholders,
1178 );
1179 }
1180lint1181 }
1182 }
11831184let (need_migrations, reasons) = self.compute_2229_migrations(
1185closure_def_id,
1186span,
1187capture_clause,
1188self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
1189 );
11901191if !need_migrations.is_empty() {
1192self.tcx.emit_node_span_lint(
1193 lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
1194self.tcx.local_def_id_to_hir_id(closure_def_id),
1195self.tcx.def_span(closure_def_id),
1196MigrationLint {
1197 this: self,
1198 migration_message: reasons.migration_message(),
1199closure_def_id,
1200body_id,
1201need_migrations,
1202 },
1203 );
1204 }
1205 }
12061207/// Combines all the reasons for 2229 migrations
1208fn compute_2229_migrations_reasons(
1209&self,
1210 auto_trait_reasons: UnordSet<&'static str>,
1211 drop_order: bool,
1212 ) -> MigrationWarningReason {
1213MigrationWarningReason {
1214 auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1215drop_order,
1216 }
1217 }
12181219/// Figures out the list of root variables (and their types) that aren't completely
1220 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1221 /// differ between the root variable and the captured paths.
1222 ///
1223 /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1224 /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1225fn compute_2229_migrations_for_trait(
1226&self,
1227 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1228 var_hir_id: HirId,
1229 closure_clause: hir::CaptureBy,
1230 ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1231let auto_traits_def_id = [
1232self.tcx.lang_items().clone_trait(),
1233self.tcx.lang_items().sync_trait(),
1234self.tcx.get_diagnostic_item(sym::Send),
1235self.tcx.lang_items().unpin_trait(),
1236self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1237self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1238 ];
1239const AUTO_TRAITS: [&str; 6] =
1240 ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
12411242let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
12431244let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
12451246let ty = match closure_clause {
1247 hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1248hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1249// For non move closure the capture kind is the max capture kind of all captures
1250 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1251let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1252for capture in root_var_min_capture_list.iter() {
1253 max_capture_info = determine_capture_info(max_capture_info, capture.info);
1254 }
12551256apply_capture_kind_on_capture_ty(
1257self.tcx,
1258ty,
1259max_capture_info.capture_kind,
1260self.tcx.lifetimes.re_erased,
1261 )
1262 }
1263 };
12641265let mut obligations_should_hold = Vec::new();
1266// Checks if a root variable implements any of the auto traits
1267for check_trait in auto_traits_def_id.iter() {
1268 obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1269self.infcx
1270 .type_implements_trait(check_trait, [ty], self.param_env)
1271 .must_apply_modulo_regions()
1272 }));
1273 }
12741275let mut problematic_captures = FxIndexMap::default();
1276// Check whether captured fields also implement the trait
1277for capture in root_var_min_capture_list.iter() {
1278let ty = apply_capture_kind_on_capture_ty(
1279self.tcx,
1280 capture.place.ty(),
1281 capture.info.capture_kind,
1282self.tcx.lifetimes.re_erased,
1283 );
12841285// Checks if a capture implements any of the auto traits
1286let mut obligations_holds_for_capture = Vec::new();
1287for check_trait in auto_traits_def_id.iter() {
1288 obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1289self.infcx
1290 .type_implements_trait(check_trait, [ty], self.param_env)
1291 .must_apply_modulo_regions()
1292 }));
1293 }
12941295let mut capture_problems = UnordSet::default();
12961297// Checks if for any of the auto traits, one or more trait is implemented
1298 // by the root variable but not by the capture
1299for (idx, _) in obligations_should_hold.iter().enumerate() {
1300if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1301 capture_problems.insert(AUTO_TRAITS[idx]);
1302 }
1303 }
13041305if !capture_problems.is_empty() {
1306 problematic_captures.insert(
1307 UpvarMigrationInfo::CapturingPrecise {
1308 source_expr: capture.info.path_expr_id,
1309 var_name: capture.to_string(self.tcx),
1310 },
1311 capture_problems,
1312 );
1313 }
1314 }
1315if !problematic_captures.is_empty() {
1316return Some(problematic_captures);
1317 }
1318None1319 }
13201321/// Figures out the list of root variables (and their types) that aren't completely
1322 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1323 /// some path starting at that root variable **might** be affected.
1324 ///
1325 /// The output list would include a root variable if:
1326 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1327 /// enabled, **and**
1328 /// - It wasn't completely captured by the closure, **and**
1329 /// - One of the paths starting at this root variable, that is not captured needs Drop.
1330 ///
1331 /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1332 /// are no significant drops than None is returned
1333#[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("compute_2229_migrations_for_drop",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1333u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_def_id",
"closure_span", "min_captures", "closure_clause",
"var_hir_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_captures)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_clause)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_hir_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Option<FxIndexSet<UpvarMigrationInfo>> = loop {};
return __tracing_attr_fake_return;
}
{
let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
if !ty.has_significant_drop(self.tcx,
ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id))
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:1349",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1349u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::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!("does not have significant drop")
as &dyn Value))])
});
} else { ; }
};
return None;
}
let Some(root_var_min_capture_list) =
min_captures.and_then(|m|
m.get(&var_hir_id)) else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:1362",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1362u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::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!("no path starting from it is used")
as &dyn Value))])
});
} else { ; }
};
match closure_clause {
hir::CaptureBy::Value { .. } => {
let mut diagnostics_info = FxIndexSet::default();
let upvars =
self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
let upvar = upvars[&var_hir_id];
diagnostics_info.insert(UpvarMigrationInfo::CapturingNothing {
use_span: upvar.span,
});
return Some(diagnostics_info);
}
hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
}
return None;
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:1380",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1380u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["root_var_min_capture_list"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&root_var_min_capture_list)
as &dyn Value))])
});
} else { ; }
};
let mut projections_list = Vec::new();
let mut diagnostics_info = FxIndexSet::default();
for captured_place in root_var_min_capture_list.iter() {
match captured_place.info.capture_kind {
ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
projections_list.push(captured_place.place.projections.as_slice());
diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
source_expr: captured_place.info.path_expr_id,
var_name: captured_place.to_string(self.tcx),
});
}
ty::UpvarCapture::ByRef(..) => {}
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:1399",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1399u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["projections_list"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&projections_list)
as &dyn Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:1400",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1400u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["diagnostics_info"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&diagnostics_info)
as &dyn Value))])
});
} else { ; }
};
let is_moved = !projections_list.is_empty();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:1403",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1403u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["is_moved"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&is_moved)
as &dyn Value))])
});
} else { ; }
};
let is_not_completely_captured =
root_var_min_capture_list.iter().any(|capture|
!capture.place.projections.is_empty());
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:1407",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1407u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["is_not_completely_captured"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&is_not_completely_captured)
as &dyn Value))])
});
} else { ; }
};
if is_moved && is_not_completely_captured &&
self.has_significant_drop_outside_of_captures(closure_def_id,
closure_span, ty, projections_list) {
return Some(diagnostics_info);
}
None
}
}
}#[instrument(level = "debug", skip(self))]1334fn compute_2229_migrations_for_drop(
1335&self,
1336 closure_def_id: LocalDefId,
1337 closure_span: Span,
1338 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1339 closure_clause: hir::CaptureBy,
1340 var_hir_id: HirId,
1341 ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1342let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
13431344// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1345if !ty.has_significant_drop(
1346self.tcx,
1347 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1348 ) {
1349debug!("does not have significant drop");
1350return None;
1351 }
13521353let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1354// The upvar is mentioned within the closure but no path starting from it is
1355 // used. This occurs when you have (e.g.)
1356 //
1357 // ```
1358 // let x = move || {
1359 // let _ = y;
1360 // });
1361 // ```
1362debug!("no path starting from it is used");
13631364match closure_clause {
1365// Only migrate if closure is a move closure
1366hir::CaptureBy::Value { .. } => {
1367let mut diagnostics_info = FxIndexSet::default();
1368let upvars =
1369self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1370let upvar = upvars[&var_hir_id];
1371 diagnostics_info
1372 .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1373return Some(diagnostics_info);
1374 }
1375 hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1376 }
13771378return None;
1379 };
1380debug!(?root_var_min_capture_list);
13811382let mut projections_list = Vec::new();
1383let mut diagnostics_info = FxIndexSet::default();
13841385for captured_place in root_var_min_capture_list.iter() {
1386match captured_place.info.capture_kind {
1387// Only care about captures that are moved into the closure
1388ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1389 projections_list.push(captured_place.place.projections.as_slice());
1390 diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1391 source_expr: captured_place.info.path_expr_id,
1392 var_name: captured_place.to_string(self.tcx),
1393 });
1394 }
1395 ty::UpvarCapture::ByRef(..) => {}
1396 }
1397 }
13981399debug!(?projections_list);
1400debug!(?diagnostics_info);
14011402let is_moved = !projections_list.is_empty();
1403debug!(?is_moved);
14041405let is_not_completely_captured =
1406 root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1407debug!(?is_not_completely_captured);
14081409if is_moved
1410 && is_not_completely_captured
1411 && self.has_significant_drop_outside_of_captures(
1412 closure_def_id,
1413 closure_span,
1414 ty,
1415 projections_list,
1416 )
1417 {
1418return Some(diagnostics_info);
1419 }
14201421None
1422}
14231424/// Figures out the list of root variables (and their types) that aren't completely
1425 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1426 /// order of some path starting at that root variable **might** be affected or auto-traits
1427 /// differ between the root variable and the captured paths.
1428 ///
1429 /// The output list would include a root variable if:
1430 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1431 /// enabled, **and**
1432 /// - It wasn't completely captured by the closure, **and**
1433 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1434 /// - One of the paths captured does not implement all the auto-traits its root variable
1435 /// implements.
1436 ///
1437 /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1438 /// containing the reason why root variables whose HirId is contained in the vector should
1439 /// be captured
1440#[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("compute_2229_migrations",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1440u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_def_id",
"closure_span", "closure_clause", "min_captures"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_clause)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_captures)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
(Vec<NeededMigration>, MigrationWarningReason) = loop {};
return __tracing_attr_fake_return;
}
{
let Some(upvars) =
self.tcx.upvars_mentioned(closure_def_id) else {
return (Vec::new(), MigrationWarningReason::default());
};
let mut need_migrations = Vec::new();
let mut auto_trait_migration_reasons = UnordSet::default();
let mut drop_migration_needed = false;
for (&var_hir_id, _) in upvars.iter() {
let mut diagnostics_info = Vec::new();
let auto_trait_diagnostic =
self.compute_2229_migrations_for_trait(min_captures,
var_hir_id, closure_clause).unwrap_or_default();
let drop_reorder_diagnostic =
if let Some(diagnostics_info) =
self.compute_2229_migrations_for_drop(closure_def_id,
closure_span, min_captures, closure_clause, var_hir_id) {
drop_migration_needed = true;
diagnostics_info
} else { FxIndexSet::default() };
let mut capture_diagnostic = drop_reorder_diagnostic.clone();
for key in auto_trait_diagnostic.keys() {
capture_diagnostic.insert(key.clone());
}
let mut capture_diagnostic =
capture_diagnostic.into_iter().collect::<Vec<_>>();
capture_diagnostic.sort_by_cached_key(|info|
match info {
UpvarMigrationInfo::CapturingPrecise {
source_expr: _, var_name } => {
(0, Some(var_name.clone()))
}
UpvarMigrationInfo::CapturingNothing { use_span: _ } =>
(1, None),
});
for captures_info in capture_diagnostic {
let capture_trait_reasons =
if let Some(reasons) =
auto_trait_diagnostic.get(&captures_info) {
reasons.clone()
} else { UnordSet::default() };
let capture_drop_reorder_reason =
drop_reorder_diagnostic.contains(&captures_info);
auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
diagnostics_info.push(MigrationLintNote {
captures_info,
reason: self.compute_2229_migrations_reasons(capture_trait_reasons,
capture_drop_reorder_reason),
});
}
if !diagnostics_info.is_empty() {
need_migrations.push(NeededMigration {
var_hir_id,
diagnostics_info,
});
}
}
(need_migrations,
self.compute_2229_migrations_reasons(auto_trait_migration_reasons,
drop_migration_needed))
}
}
}#[instrument(level = "debug", skip(self))]1441fn compute_2229_migrations(
1442&self,
1443 closure_def_id: LocalDefId,
1444 closure_span: Span,
1445 closure_clause: hir::CaptureBy,
1446 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1447 ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1448let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1449return (Vec::new(), MigrationWarningReason::default());
1450 };
14511452let mut need_migrations = Vec::new();
1453let mut auto_trait_migration_reasons = UnordSet::default();
1454let mut drop_migration_needed = false;
14551456// Perform auto-trait analysis
1457for (&var_hir_id, _) in upvars.iter() {
1458let mut diagnostics_info = Vec::new();
14591460let auto_trait_diagnostic = self
1461.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1462 .unwrap_or_default();
14631464let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1465.compute_2229_migrations_for_drop(
1466 closure_def_id,
1467 closure_span,
1468 min_captures,
1469 closure_clause,
1470 var_hir_id,
1471 ) {
1472 drop_migration_needed = true;
1473 diagnostics_info
1474 } else {
1475 FxIndexSet::default()
1476 };
14771478// Combine all the captures responsible for needing migrations into one IndexSet
1479let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1480for key in auto_trait_diagnostic.keys() {
1481 capture_diagnostic.insert(key.clone());
1482 }
14831484let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1485 capture_diagnostic.sort_by_cached_key(|info| match info {
1486 UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1487 (0, Some(var_name.clone()))
1488 }
1489 UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1490 });
1491for captures_info in capture_diagnostic {
1492// Get the auto trait reasons of why migration is needed because of that capture, if there are any
1493let capture_trait_reasons =
1494if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1495 reasons.clone()
1496 } else {
1497 UnordSet::default()
1498 };
14991500// Check if migration is needed because of drop reorder as a result of that capture
1501let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
15021503// Combine all the reasons of why the root variable should be captured as a result of
1504 // auto trait implementation issues
1505auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
15061507 diagnostics_info.push(MigrationLintNote {
1508 captures_info,
1509 reason: self.compute_2229_migrations_reasons(
1510 capture_trait_reasons,
1511 capture_drop_reorder_reason,
1512 ),
1513 });
1514 }
15151516if !diagnostics_info.is_empty() {
1517 need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1518 }
1519 }
1520 (
1521 need_migrations,
1522self.compute_2229_migrations_reasons(
1523 auto_trait_migration_reasons,
1524 drop_migration_needed,
1525 ),
1526 )
1527 }
15281529/// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1530 /// of a root variable and a list of captured paths starting at this root variable (expressed
1531 /// using list of `Projection` slices), it returns true if there is a path that is not
1532 /// captured starting at this root variable that implements Drop.
1533 ///
1534 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1535 /// path say P and then list of projection slices which represent the different captures moved
1536 /// into the closure starting off of P.
1537 ///
1538 /// This will make more sense with an example:
1539 ///
1540 /// ```rust,edition2021
1541 ///
1542 /// struct FancyInteger(i32); // This implements Drop
1543 ///
1544 /// struct Point { x: FancyInteger, y: FancyInteger }
1545 /// struct Color;
1546 ///
1547 /// struct Wrapper { p: Point, c: Color }
1548 ///
1549 /// fn f(w: Wrapper) {
1550 /// let c = || {
1551 /// // Closure captures w.p.x and w.c by move.
1552 /// };
1553 ///
1554 /// c();
1555 /// }
1556 /// ```
1557 ///
1558 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1559 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1560 /// therefore Drop ordering would change and we want this function to return true.
1561 ///
1562 /// Call stack to figure out if we need to migrate for `w` would look as follows:
1563 ///
1564 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1565 /// `w[c]`.
1566 /// Notation:
1567 /// - Ty(place): Type of place
1568 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1569 /// respectively.
1570 /// ```ignore (illustrative)
1571 /// (Ty(w), [ &[p, x], &[c] ])
1572 /// // |
1573 /// // ----------------------------
1574 /// // | |
1575 /// // v v
1576 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
1577 /// // | |
1578 /// // v v
1579 /// (Ty(w.p), [ &[x] ]) false
1580 /// // |
1581 /// // |
1582 /// // -------------------------------
1583 /// // | |
1584 /// // v v
1585 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
1586 /// // | |
1587 /// // v v
1588 /// false NeedsSignificantDrop(Ty(w.p.y))
1589 /// // |
1590 /// // v
1591 /// true
1592 /// ```
1593 ///
1594 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1595 /// This implies that the `w.c` is completely captured by the closure.
1596 /// Since drop for this path will be called when the closure is
1597 /// dropped we don't need to migrate for it.
1598 ///
1599 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1600 /// path wasn't captured by the closure. Also note that even
1601 /// though we didn't capture this path, the function visits it,
1602 /// which is kind of the point of this function. We then return
1603 /// if the type of `w.p.y` implements Drop, which in this case is
1604 /// true.
1605 ///
1606 /// Consider another example:
1607 ///
1608 /// ```ignore (pseudo-rust)
1609 /// struct X;
1610 /// impl Drop for X {}
1611 ///
1612 /// struct Y(X);
1613 /// impl Drop for Y {}
1614 ///
1615 /// fn foo() {
1616 /// let y = Y(X);
1617 /// let c = || move(y.0);
1618 /// }
1619 /// ```
1620 ///
1621 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1622 /// return true, because even though all paths starting at `y` are captured, `y` itself
1623 /// implements Drop which will be affected since `y` isn't completely captured.
1624fn has_significant_drop_outside_of_captures(
1625&self,
1626 closure_def_id: LocalDefId,
1627 closure_span: Span,
1628 base_path_ty: Ty<'tcx>,
1629 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1630 ) -> bool {
1631// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1632let needs_drop = |ty: Ty<'tcx>| {
1633ty.has_significant_drop(
1634self.tcx,
1635 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1636 )
1637 };
16381639let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1640let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, closure_span);
1641self.infcx
1642 .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1643 .must_apply_modulo_regions()
1644 };
16451646let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
16471648// If there is a case where no projection is applied on top of current place
1649 // then there must be exactly one capture corresponding to such a case. Note that this
1650 // represents the case of the path being completely captured by the variable.
1651 //
1652 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1653 // capture `a.b.c`, because that violates min capture.
1654let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
16551656if !(!is_completely_captured || (captured_by_move_projs.len() == 1)) {
::core::panicking::panic("assertion failed: !is_completely_captured || (captured_by_move_projs.len() == 1)")
};assert!(!is_completely_captured || (captured_by_move_projs.len() == 1));
16571658if is_completely_captured {
1659// The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1660 // when the closure is dropped.
1661return false;
1662 }
16631664if captured_by_move_projs.is_empty() {
1665return needs_drop(base_path_ty);
1666 }
16671668if is_drop_defined_for_ty {
1669// If drop is implemented for this type then we need it to be fully captured,
1670 // and we know it is not completely captured because of the previous checks.
16711672 // Note that this is a bug in the user code that will be reported by the
1673 // borrow checker, since we can't move out of drop types.
16741675 // The bug exists in the user's code pre-migration, and we don't migrate here.
1676return false;
1677 }
16781679match base_path_ty.kind() {
1680// Observations:
1681 // - `captured_by_move_projs` is not empty. Therefore we can call
1682 // `captured_by_move_projs.first().unwrap()` safely.
1683 // - All entries in `captured_by_move_projs` have at least one projection.
1684 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
16851686 // We don't capture derefs in case of move captures, which would have be applied to
1687 // access any further paths.
1688 ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1689 ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1690 ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
16911692 ty::Adt(def, args) => {
1693// Multi-variant enums are captured in entirety,
1694 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1695match (&def.variants().len(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(def.variants().len(), 1);
16961697// Only Field projections can be applied to a non-box Adt.
1698if !captured_by_move_projs.iter().all(|projs|
#[allow(non_exhaustive_omitted_patterns)] match projs.first().unwrap().kind
{
ProjectionKind::Field(..) => true,
_ => false,
}) {
::core::panicking::panic("assertion failed: captured_by_move_projs.iter().all(|projs|\n matches!(projs.first().unwrap().kind, ProjectionKind::Field(..)))")
};assert!(
1699 captured_by_move_projs.iter().all(|projs| matches!(
1700 projs.first().unwrap().kind,
1701 ProjectionKind::Field(..)
1702 ))
1703 );
1704def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1705 |(i, field)| {
1706let paths_using_field = captured_by_move_projs1707 .iter()
1708 .filter_map(|projs| {
1709if let ProjectionKind::Field(field_idx, _) =
1710projs.first().unwrap().kind
1711 {
1712if field_idx == i { Some(&projs[1..]) } else { None }
1713 } else {
1714::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1715 }
1716 })
1717 .collect();
17181719let after_field_ty = field.ty(self.tcx, args).skip_norm_wip();
1720self.has_significant_drop_outside_of_captures(
1721closure_def_id,
1722closure_span,
1723after_field_ty,
1724paths_using_field,
1725 )
1726 },
1727 )
1728 }
17291730 ty::Tuple(fields) => {
1731// Only Field projections can be applied to a tuple.
1732if !captured_by_move_projs.iter().all(|projs|
#[allow(non_exhaustive_omitted_patterns)] match projs.first().unwrap().kind
{
ProjectionKind::Field(..) => true,
_ => false,
}) {
::core::panicking::panic("assertion failed: captured_by_move_projs.iter().all(|projs|\n matches!(projs.first().unwrap().kind, ProjectionKind::Field(..)))")
};assert!(
1733 captured_by_move_projs.iter().all(|projs| matches!(
1734 projs.first().unwrap().kind,
1735 ProjectionKind::Field(..)
1736 ))
1737 );
17381739fields.iter().enumerate().any(|(i, element_ty)| {
1740let paths_using_field = captured_by_move_projs1741 .iter()
1742 .filter_map(|projs| {
1743if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1744 {
1745if field_idx.index() == i { Some(&projs[1..]) } else { None }
1746 } else {
1747::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1748 }
1749 })
1750 .collect();
17511752self.has_significant_drop_outside_of_captures(
1753closure_def_id,
1754closure_span,
1755element_ty,
1756paths_using_field,
1757 )
1758 })
1759 }
17601761// Anything else would be completely captured and therefore handled already.
1762_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1763 }
1764 }
17651766fn init_capture_kind_for_place(
1767&self,
1768 place: &Place<'tcx>,
1769 capture_clause: hir::CaptureBy,
1770 ) -> ty::UpvarCapture {
1771match capture_clause {
1772// In case of a move closure if the data is accessed through a reference we
1773 // want to capture by ref to allow precise capture using reborrows.
1774 //
1775 // If the data will be moved out of this place, then the place will be truncated
1776 // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1777 //
1778 // For example:
1779 //
1780 // struct Buffer<'a> {
1781 // x: &'a String,
1782 // y: Vec<u8>,
1783 // }
1784 //
1785 // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1786 // let c = move || b.x;
1787 // drop(b);
1788 // c
1789 // }
1790 //
1791 // Even though the closure is declared as move, when we are capturing borrowed data (in
1792 // this case, *b.x) we prefer to capture by reference.
1793 // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1794 // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1795 // before, which is also an error.
1796hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1797 ty::UpvarCapture::ByValue1798 }
1799 hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1800 ty::UpvarCapture::ByUse1801 }
1802 hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1803 ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1804 }
1805 }
1806 }
18071808fn place_for_root_variable(
1809&self,
1810 closure_def_id: LocalDefId,
1811 var_hir_id: HirId,
1812 ) -> Place<'tcx> {
1813let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
18141815let place = Place {
1816 base_ty: self.node_ty(var_hir_id),
1817 base: PlaceBase::Upvar(upvar_id),
1818 projections: Default::default(),
1819 };
18201821// Normalize eagerly when inserting into `capture_information`, so all downstream
1822 // capture analysis can assume a normalized `Place`.
1823self.normalize(self.tcx.hir_span(var_hir_id), Unnormalized::new_wip(place))
1824 }
18251826fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1827self.has_rustc_attrs && {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(closure_def_id,
&self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcCaptureAnalysis) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, closure_def_id, RustcCaptureAnalysis)1828 }
18291830fn log_capture_analysis_first_pass(
1831&self,
1832 closure_def_id: LocalDefId,
1833 capture_information: &InferredCaptureInformation<'tcx>,
1834 closure_span: Span,
1835 ) {
1836if self.should_log_capture_analysis(closure_def_id) {
1837let mut diag =
1838self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1839for (place, capture_info) in capture_information {
1840let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1841let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
})format!("Capturing {capture_str}");
18421843let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1844 diag.span_note(span, output_str);
1845 }
1846diag.emit();
1847 }
1848 }
18491850fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1851if self.should_log_capture_analysis(closure_def_id) {
1852if let Some(min_captures) =
1853self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1854 {
1855let mut diag =
1856self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
18571858for (_, min_captures_for_var) in min_captures {
1859for capture in min_captures_for_var {
1860let place = &capture.place;
1861let capture_info = &capture.info;
18621863let capture_str =
1864 construct_capture_info_string(self.tcx, place, capture_info);
1865let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
})format!("Min Capture {capture_str}");
18661867if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1868let path_span = capture_info
1869 .path_expr_id
1870 .map_or(closure_span, |e| self.tcx.hir_span(e));
1871let capture_kind_span = capture_info
1872 .capture_kind_expr_id
1873 .map_or(closure_span, |e| self.tcx.hir_span(e));
18741875let mut multi_span: MultiSpan =
1876 MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[path_span, capture_kind_span]))vec![path_span, capture_kind_span]);
18771878let capture_kind_label =
1879 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1880let path_label = construct_path_string(self.tcx, place);
18811882 multi_span.push_span_label(path_span, path_label);
1883 multi_span.push_span_label(capture_kind_span, capture_kind_label);
18841885 diag.span_note(multi_span, output_str);
1886 } else {
1887let span = capture_info
1888 .path_expr_id
1889 .map_or(closure_span, |e| self.tcx.hir_span(e));
18901891 diag.span_note(span, output_str);
1892 };
1893 }
1894 }
1895diag.emit();
1896 }
1897 }
1898 }
18991900/// A captured place is mutable if
1901 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1902 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1903fn determine_capture_mutability(
1904&self,
1905 typeck_results: &'a TypeckResults<'tcx>,
1906 place: &Place<'tcx>,
1907 ) -> hir::Mutability {
1908let var_hir_id = match place.base {
1909 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1910_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1911 };
19121913let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
19141915let mut is_mutbl = bm.1;
19161917for pointer_ty in place.deref_tys() {
1918match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
1919// We don't capture derefs of raw ptrs
1920 ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
19211922// Dereferencing a mut-ref allows us to mut the Place if we don't deref
1923 // an immut-ref after on top of this.
1924ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
19251926// The place isn't mutable once we dereference an immutable reference.
1927ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
19281929// Dereferencing a box doesn't change mutability
1930ty::Adt(def, ..) if def.is_box() => {}
19311932 unexpected_ty => ::rustc_middle::util::bug::span_bug_fmt(self.tcx.hir_span(var_hir_id),
format_args!("deref of unexpected pointer type {0:?}", unexpected_ty))span_bug!(
1933self.tcx.hir_span(var_hir_id),
1934"deref of unexpected pointer type {:?}",
1935 unexpected_ty
1936 ),
1937 }
1938 }
19391940is_mutbl1941 }
1942}
19431944/// Determines whether a child capture that is derived from a parent capture
1945/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1946///
1947/// There are two cases when this needs to happen:
1948///
1949/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1950/// that is the case by checking if the parent capture is by move, EXCEPT if we
1951/// apply a deref projection of an immutable reference, reborrows of immutable
1952/// references which aren't restricted to the LUB of the lifetimes of the deref
1953/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1954///
1955/// ```rust
1956/// let x = &1i32; // Let's call this lifetime `'1`.
1957/// let c = async move || {
1958/// println!("{:?}", *x);
1959/// // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1960/// // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1961/// };
1962/// ```
1963///
1964/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1965/// mutable borrow cannot live for longer than either the parent *or* the borrow
1966/// that we have on the original upvar. Therefore we always need to borrow the
1967/// child capture with the lifetime of the parent coroutine-closure's env.
1968///
1969/// ```rust
1970/// let mut x = 1i32;
1971/// let c = async || {
1972/// x = 1;
1973/// // The parent borrows `x` for some `&'1 mut i32`.
1974/// // However, when we call `c()`, we implicitly autoref for the signature of
1975/// // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1976/// // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1977/// // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1978/// };
1979/// ```
1980///
1981/// If either of these cases apply, then we should capture the borrow with the
1982/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1983/// not correct, then the program is not unsound, since we still borrowck and validate
1984/// the choices made from this function -- the only side-effect is that the user
1985/// may receive unnecessary borrowck errors.
1986fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
1987 parent_capture: &ty::CapturedPlace<'tcx>,
1988 child_capture: &ty::CapturedPlace<'tcx>,
1989) -> bool {
1990// (1.)
1991(!parent_capture.is_by_ref()
1992// This is just inlined `place.deref_tys()` but truncated to just
1993 // the child projections. Namely, look for a `&T` deref, since we
1994 // can always extend `&'short mut &'long T` to `&'long T`.
1995&& !child_capture1996 .place
1997 .projections
1998 .iter()
1999 .enumerate()
2000 .skip(parent_capture.place.projections.len())
2001 .any(|(idx, proj)| {
2002#[allow(non_exhaustive_omitted_patterns)] match proj.kind {
ProjectionKind::Deref => true,
_ => false,
}matches!(proj.kind, ProjectionKind::Deref)2003 && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
{
ty::Ref(.., ty::Mutability::Not) => true,
_ => false,
}matches!(
2004 child_capture.place.ty_before_projection(idx).kind(),
2005 ty::Ref(.., ty::Mutability::Not)
2006 )2007 }))
2008// (2.)
2009 || #[allow(non_exhaustive_omitted_patterns)] match child_capture.info.capture_kind
{
UpvarCapture::ByRef(ty::BorrowKind::Mutable) => true,
_ => false,
}matches!(child_capture.info.capture_kind, UpvarCapture::ByRef(ty::BorrowKind::Mutable))2010}
20112012/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
2013/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
2014fn restrict_repr_packed_field_ref_capture<'tcx>(
2015mut place: Place<'tcx>,
2016mut curr_borrow_kind: ty::UpvarCapture,
2017) -> (Place<'tcx>, ty::UpvarCapture) {
2018let pos = place.projections.iter().enumerate().position(|(i, p)| {
2019let ty = place.ty_before_projection(i);
20202021// Return true for fields of packed structs.
2022match p.kind {
2023 ProjectionKind::Field(..) => match ty.kind() {
2024 ty::Adt(def, _) if def.repr().packed() => {
2025// We stop here regardless of field alignment. Field alignment can change as
2026 // types change, including the types of private fields in other crates, and that
2027 // shouldn't affect how we compute our captures.
2028true
2029}
20302031_ => false,
2032 },
2033_ => false,
2034 }
2035 });
20362037if let Some(pos) = pos {
2038truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
2039 }
20402041 (place, curr_borrow_kind)
2042}
20432044/// Returns a Ty that applies the specified capture kind on the provided capture Ty
2045fn apply_capture_kind_on_capture_ty<'tcx>(
2046 tcx: TyCtxt<'tcx>,
2047 ty: Ty<'tcx>,
2048 capture_kind: UpvarCapture,
2049 region: ty::Region<'tcx>,
2050) -> Ty<'tcx> {
2051match capture_kind {
2052 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
2053 ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
2054 }
2055}
20562057/// Returns the Span of where the value with the provided HirId would be dropped
2058fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
2059let owner_id = tcx.hir_get_enclosing_scope(hir_id).unwrap();
20602061let owner_node = tcx.hir_node(owner_id);
2062let owner_span = match owner_node {
2063 hir::Node::Item(item) => match item.kind {
2064 hir::ItemKind::Fn { body: owner_id, .. } => tcx.hir_span(owner_id.hir_id),
2065_ => {
2066::rustc_middle::util::bug::bug_fmt(format_args!("Drop location span error: need to handle more ItemKind \'{0:?}\'",
item.kind));bug!("Drop location span error: need to handle more ItemKind '{:?}'", item.kind);
2067 }
2068 },
2069 hir::Node::Block(block) => tcx.hir_span(block.hir_id),
2070 hir::Node::TraitItem(item) => tcx.hir_span(item.hir_id()),
2071 hir::Node::ImplItem(item) => tcx.hir_span(item.hir_id()),
2072_ => {
2073::rustc_middle::util::bug::bug_fmt(format_args!("Drop location span error: need to handle more Node \'{0:?}\'",
owner_node));bug!("Drop location span error: need to handle more Node '{:?}'", owner_node);
2074 }
2075 };
2076tcx.sess.source_map().end_point(owner_span)
2077}
20782079struct InferBorrowKind<'a, 'tcx> {
2080 fcx: &'a FnCtxt<'a, 'tcx>,
2081// The def-id of the closure whose kind and upvar accesses are being inferred.
2082closure_def_id: LocalDefId,
20832084/// For each Place that is captured by the closure, we track the minimal kind of
2085 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2086 ///
2087 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2088 /// s.str2 via a MutableBorrow
2089 ///
2090 /// ```rust,no_run
2091 /// struct SomeStruct { str1: String, str2: String };
2092 ///
2093 /// // Assume that the HirId for the variable definition is `V1`
2094 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2095 ///
2096 /// let fix_s = |new_s2| {
2097 /// // Assume that the HirId for the expression `s.str1` is `E1`
2098 /// println!("Updating SomeStruct with str1={0}", s.str1);
2099 /// // Assume that the HirId for the expression `*s.str2` is `E2`
2100 /// s.str2 = new_s2;
2101 /// };
2102 /// ```
2103 ///
2104 /// For closure `fix_s`, (at a high level) the map contains
2105 ///
2106 /// ```ignore (illustrative)
2107 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2108 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2109 /// ```
2110capture_information: InferredCaptureInformation<'tcx>,
2111 fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2112}
21132114impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
2115#[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("fake_read",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2115u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["place_with_id",
"cause", "diag_expr_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let PlaceBase::Upvar(_) =
place_with_id.place.base else { return };
let dummy_capture_kind =
ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
let span = self.fcx.tcx.hir_span(diag_expr_id);
let place =
self.fcx.normalize(span,
Unnormalized::new_wip(place_with_id.place.clone()));
let (place, _) =
restrict_capture_precision(place, dummy_capture_kind);
let (place, _) =
restrict_repr_packed_field_ref_capture(place,
dummy_capture_kind);
self.fake_reads.push((place, cause, diag_expr_id));
}
}
}#[instrument(skip(self), level = "debug")]2116fn fake_read(
2117&mut self,
2118 place_with_id: &PlaceWithHirId<'tcx>,
2119 cause: FakeReadCause,
2120 diag_expr_id: HirId,
2121 ) {
2122let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
21232124// We need to restrict Fake Read precision to avoid fake reading unsafe code,
2125 // such as deref of a raw pointer.
2126let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
21272128let span = self.fcx.tcx.hir_span(diag_expr_id);
2129let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
21302131let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
21322133let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2134self.fake_reads.push((place, cause, diag_expr_id));
2135 }
21362137#[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("consume",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2137u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["place_with_id",
"diag_expr_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let PlaceBase::Upvar(upvar_id) =
place_with_id.place.base else { return };
match (&self.closure_def_id, &upvar_id.closure_expr_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let span = self.fcx.tcx.hir_span(diag_expr_id);
let place =
self.fcx.normalize(span,
Unnormalized::new_wip(place_with_id.place.clone()));
self.capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(diag_expr_id),
path_expr_id: Some(diag_expr_id),
capture_kind: ty::UpvarCapture::ByValue,
}));
}
}
}#[instrument(skip(self), level = "debug")]2138fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2139let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2140assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21412142let span = self.fcx.tcx.hir_span(diag_expr_id);
2143let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
21442145self.capture_information.push((
2146 place,
2147 ty::CaptureInfo {
2148 capture_kind_expr_id: Some(diag_expr_id),
2149 path_expr_id: Some(diag_expr_id),
2150 capture_kind: ty::UpvarCapture::ByValue,
2151 },
2152 ));
2153 }
21542155#[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("use_cloned",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2155u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["place_with_id",
"diag_expr_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let PlaceBase::Upvar(upvar_id) =
place_with_id.place.base else { return };
match (&self.closure_def_id, &upvar_id.closure_expr_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let span = self.fcx.tcx.hir_span(diag_expr_id);
let place =
self.fcx.normalize(span,
Unnormalized::new_wip(place_with_id.place.clone()));
self.capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(diag_expr_id),
path_expr_id: Some(diag_expr_id),
capture_kind: ty::UpvarCapture::ByUse,
}));
}
}
}#[instrument(skip(self), level = "debug")]2156fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2157let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2158assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21592160let span = self.fcx.tcx.hir_span(diag_expr_id);
2161let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
21622163self.capture_information.push((
2164 place,
2165 ty::CaptureInfo {
2166 capture_kind_expr_id: Some(diag_expr_id),
2167 path_expr_id: Some(diag_expr_id),
2168 capture_kind: ty::UpvarCapture::ByUse,
2169 },
2170 ));
2171 }
21722173#[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("borrow",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2173u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["place_with_id",
"diag_expr_id", "bk"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bk)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let PlaceBase::Upvar(upvar_id) =
place_with_id.place.base else { return };
match (&self.closure_def_id, &upvar_id.closure_expr_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let capture_kind = ty::UpvarCapture::ByRef(bk);
let span = self.fcx.tcx.hir_span(diag_expr_id);
let place =
self.fcx.normalize(span,
Unnormalized::new_wip(place_with_id.place.clone()));
let (place, mut capture_kind) =
restrict_repr_packed_field_ref_capture(place, capture_kind);
if place.deref_tys().any(Ty::is_raw_ptr) {
capture_kind =
ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
}
self.capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(diag_expr_id),
path_expr_id: Some(diag_expr_id),
capture_kind,
}));
}
}
}#[instrument(skip(self), level = "debug")]2174fn borrow(
2175&mut self,
2176 place_with_id: &PlaceWithHirId<'tcx>,
2177 diag_expr_id: HirId,
2178 bk: ty::BorrowKind,
2179 ) {
2180let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2181assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21822183// The region here will get discarded/ignored
2184let capture_kind = ty::UpvarCapture::ByRef(bk);
21852186let span = self.fcx.tcx.hir_span(diag_expr_id);
2187let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
21882189// We only want repr packed restriction to be applied to reading references into a packed
2190 // struct, and not when the data is being moved. Therefore we call this method here instead
2191 // of in `restrict_capture_precision`.
2192let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(place, capture_kind);
21932194// Raw pointers don't inherit mutability
2195if place.deref_tys().any(Ty::is_raw_ptr) {
2196 capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2197 }
21982199self.capture_information.push((
2200 place,
2201 ty::CaptureInfo {
2202 capture_kind_expr_id: Some(diag_expr_id),
2203 path_expr_id: Some(diag_expr_id),
2204 capture_kind,
2205 },
2206 ));
2207 }
22082209#[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("mutate",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2209u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["assignee_place",
"diag_expr_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&assignee_place)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.borrow(assignee_place, diag_expr_id,
ty::BorrowKind::Mutable);
}
}
}#[instrument(skip(self), level = "debug")]2210fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2211self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2212 }
2213}
22142215/// Rust doesn't permit moving fields out of a type that implements drop
2216x;#[instrument(skip(fcx), ret, level = "debug")]2217fn restrict_precision_for_drop_types<'a, 'tcx>(
2218 fcx: &'a FnCtxt<'a, 'tcx>,
2219mut place: Place<'tcx>,
2220mut curr_mode: ty::UpvarCapture,
2221) -> (Place<'tcx>, ty::UpvarCapture) {
2222let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
22232224if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2225for i in 0..place.projections.len() {
2226match place.ty_before_projection(i).kind() {
2227 ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2228 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2229break;
2230 }
2231_ => {}
2232 }
2233 }
2234 }
22352236 (place, curr_mode)
2237}
22382239/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2240/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2241/// them completely.
2242/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2243fn restrict_precision_for_unsafe(
2244mut place: Place<'_>,
2245mut curr_mode: ty::UpvarCapture,
2246) -> (Place<'_>, ty::UpvarCapture) {
2247if place.base_ty.is_raw_ptr() {
2248truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2249 }
22502251if place.base_ty.is_union() {
2252truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2253 }
22542255for (i, proj) in place.projections.iter().enumerate() {
2256if proj.ty.is_raw_ptr() {
2257// Don't apply any projections on top of a raw ptr.
2258truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2259break;
2260 }
22612262if proj.ty.is_union() {
2263// Don't capture precise fields of a union.
2264truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2265break;
2266 }
2267 }
22682269 (place, curr_mode)
2270}
22712272/// Truncate projections so that the following rules are obeyed by the captured `place`:
2273/// - No Index projections are captured, since arrays are captured completely.
2274/// - No unsafe block is required to capture `place`.
2275///
2276/// Returns the truncated place and updated capture mode.
2277x;#[instrument(ret, level = "debug")]2278fn restrict_capture_precision(
2279 place: Place<'_>,
2280 curr_mode: ty::UpvarCapture,
2281) -> (Place<'_>, ty::UpvarCapture) {
2282let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
22832284if place.projections.is_empty() {
2285// Nothing to do here
2286return (place, curr_mode);
2287 }
22882289for (i, proj) in place.projections.iter().enumerate() {
2290match proj.kind {
2291 ProjectionKind::Index | ProjectionKind::Subslice => {
2292// Arrays are completely captured, so we drop Index and Subslice projections
2293truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2294return (place, curr_mode);
2295 }
2296 ProjectionKind::Deref => {}
2297 ProjectionKind::OpaqueCast => {}
2298 ProjectionKind::Field(..) => {}
2299 ProjectionKind::UnwrapUnsafeBinder => {}
2300 }
2301 }
23022303 (place, curr_mode)
2304}
23052306/// Truncate deref of any reference.
2307x;#[instrument(ret, level = "debug")]2308fn adjust_for_move_closure(
2309mut place: Place<'_>,
2310mut kind: ty::UpvarCapture,
2311) -> (Place<'_>, ty::UpvarCapture) {
2312let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
23132314if let Some(idx) = first_deref {
2315 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2316 }
23172318 (place, ty::UpvarCapture::ByValue)
2319}
23202321/// Truncate deref of any reference.
2322x;#[instrument(ret, level = "debug")]2323fn adjust_for_use_closure(
2324mut place: Place<'_>,
2325mut kind: ty::UpvarCapture,
2326) -> (Place<'_>, ty::UpvarCapture) {
2327let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
23282329if let Some(idx) = first_deref {
2330 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2331 }
23322333 (place, ty::UpvarCapture::ByUse)
2334}
23352336/// Adjust closure capture just that if taking ownership of data, only move data
2337/// from enclosing stack frame.
2338x;#[instrument(ret, level = "debug")]2339fn adjust_for_non_move_closure(
2340mut place: Place<'_>,
2341mut kind: ty::UpvarCapture,
2342) -> (Place<'_>, ty::UpvarCapture) {
2343let contains_deref =
2344 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
23452346match kind {
2347 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2348if let Some(idx) = contains_deref {
2349 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2350 }
2351 }
23522353 ty::UpvarCapture::ByRef(..) => {}
2354 }
23552356 (place, kind)
2357}
23582359fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2360let variable_name = match place.base {
2361 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2362_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Capture_information should only contain upvars"))bug!("Capture_information should only contain upvars"),
2363 };
23642365let mut projections_str = String::new();
2366for (i, item) in place.projections.iter().enumerate() {
2367let proj = match item.kind {
2368 ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
})format!("({a:?}, {b:?})"),
2369 ProjectionKind::Deref => String::from("Deref"),
2370 ProjectionKind::Index => String::from("Index"),
2371 ProjectionKind::Subslice => String::from("Subslice"),
2372 ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2373 ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2374 };
2375if i != 0 {
2376 projections_str.push(',');
2377 }
2378 projections_str.push_str(proj.as_str());
2379 }
23802381::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
projections_str))
})format!("{variable_name}[{projections_str}]")2382}
23832384fn construct_capture_kind_reason_string<'tcx>(
2385 tcx: TyCtxt<'_>,
2386 place: &Place<'tcx>,
2387 capture_info: &ty::CaptureInfo,
2388) -> String {
2389let place_str = construct_place_string(tcx, place);
23902391let capture_kind_str = match capture_info.capture_kind {
2392 ty::UpvarCapture::ByValue => "ByValue".into(),
2393 ty::UpvarCapture::ByUse => "ByUse".into(),
2394 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2395 };
23962397::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} captured as {1} here",
place_str, capture_kind_str))
})format!("{place_str} captured as {capture_kind_str} here")2398}
23992400fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2401let place_str = construct_place_string(tcx, place);
24022403::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} used here", place_str))
})format!("{place_str} used here")2404}
24052406fn construct_capture_info_string<'tcx>(
2407 tcx: TyCtxt<'_>,
2408 place: &Place<'tcx>,
2409 capture_info: &ty::CaptureInfo,
2410) -> String {
2411let place_str = construct_place_string(tcx, place);
24122413let capture_kind_str = match capture_info.capture_kind {
2414 ty::UpvarCapture::ByValue => "ByValue".into(),
2415 ty::UpvarCapture::ByUse => "ByUse".into(),
2416 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2417 };
2418::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
capture_kind_str))
})format!("{place_str} -> {capture_kind_str}")2419}
24202421fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2422tcx.hir_name(var_hir_id)
2423}
24242425#[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("should_do_rust_2021_incompatible_closure_captures_analysis",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2425u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if tcx.sess.at_least_rust_2021() { return false; }
!tcx.lint_level_spec_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
closure_id).is_allow()
}
}
}#[instrument(level = "debug", skip(tcx))]2426fn should_do_rust_2021_incompatible_closure_captures_analysis(
2427 tcx: TyCtxt<'_>,
2428 closure_id: HirId,
2429) -> bool {
2430if tcx.sess.at_least_rust_2021() {
2431return false;
2432 }
24332434 !tcx.lint_level_spec_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2435 .is_allow()
2436}
24372438/// Return a two string tuple (s1, s2)
2439/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2440/// - s2: Comma separated names of the variables being migrated.
2441fn migration_suggestion_for_2229(
2442 tcx: TyCtxt<'_>,
2443 need_migrations: &[NeededMigration],
2444) -> (String, String) {
2445let need_migrations_variables = need_migrations2446 .iter()
2447 .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2448 .collect::<Vec<_>>();
24492450let migration_ref_concat =
2451need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
24522453let migration_string = if 1 == need_migrations.len() {
2454::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = {0}",
migration_ref_concat))
})format!("let _ = {migration_ref_concat}")2455 } else {
2456::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = ({0})",
migration_ref_concat))
})format!("let _ = ({migration_ref_concat})")2457 };
24582459let migrated_variables_concat =
2460need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", v))
})format!("`{v}`")).collect::<Vec<_>>().join(", ");
24612462 (migration_string, migrated_variables_concat)
2463}
24642465/// Helper function to determine if we need to escalate CaptureKind from
2466/// CaptureInfo A to B and returns the escalated CaptureInfo.
2467/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2468///
2469/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2470/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2471///
2472/// It is the caller's duty to figure out which path_expr_id to use.
2473///
2474/// If both the CaptureKind and Expression are considered to be equivalent,
2475/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2476/// expressions reported back to the user as part of diagnostics based on which appears earlier
2477/// in the closure. This can be achieved simply by calling
2478/// `determine_capture_info(existing_info, current_info)`. This works out because the
2479/// expressions that occur earlier in the closure body than the current expression are processed before.
2480/// Consider the following example
2481/// ```rust,no_run
2482/// struct Point { x: i32, y: i32 }
2483/// let mut p = Point { x: 10, y: 10 };
2484///
2485/// let c = || {
2486/// p.x += 10; // E1
2487/// // ...
2488/// // More code
2489/// // ...
2490/// p.x += 10; // E2
2491/// };
2492/// ```
2493/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2494/// and both have an expression associated, however for diagnostics we prefer reporting
2495/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2496/// would've already handled `E1`, and have an existing capture_information for it.
2497/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2498/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2499fn determine_capture_info(
2500 capture_info_a: ty::CaptureInfo,
2501 capture_info_b: ty::CaptureInfo,
2502) -> ty::CaptureInfo {
2503// If the capture kind is equivalent then, we don't need to escalate and can compare the
2504 // expressions.
2505let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2506 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2507 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2508 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2509 (ty::UpvarCapture::ByValue, _)
2510 | (ty::UpvarCapture::ByUse, _)
2511 | (ty::UpvarCapture::ByRef(_), _) => false,
2512 };
25132514if eq_capture_kind {
2515match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2516 (Some(_), _) | (None, None) => capture_info_a,
2517 (None, Some(_)) => capture_info_b,
2518 }
2519 } else {
2520// We select the CaptureKind which ranks higher based the following priority order:
2521 // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2522match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2523 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2524 | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2525::rustc_middle::util::bug::bug_fmt(format_args!("Same capture can\'t be ByUse and ByValue at the same time"))bug!("Same capture can't be ByUse and ByValue at the same time")2526 }
2527 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2528 | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2529 | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2530capture_info_a2531 }
2532 (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2533capture_info_b2534 }
2535 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2536match (ref_a, ref_b) {
2537// Take LHS:
2538(BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2539 | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
25402541// Take RHS:
2542(BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2543 | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
25442545 (BorrowKind::Immutable, BorrowKind::Immutable)
2546 | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2547 | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2548::rustc_middle::util::bug::bug_fmt(format_args!("Expected unequal capture kinds"));bug!("Expected unequal capture kinds");
2549 }
2550 }
2551 }
2552 }
2553 }
2554}
25552556/// Truncates `place` to have up to `len` projections.
2557/// `curr_mode` is the current required capture kind for the place.
2558/// Returns the truncated `place` and the updated required capture kind.
2559///
2560/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2561/// contained `Deref` of `&mut`.
2562fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2563 place: &mut Place<'tcx>,
2564 curr_mode: &mut ty::UpvarCapture,
2565 len: usize,
2566) {
2567let is_mut_ref = |ty: Ty<'_>| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Ref(.., hir::Mutability::Mut) => true,
_ => false,
}matches!(ty.kind(), ty::Ref(.., hir::Mutability::Mut));
25682569// If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2570 // UniqueImmBorrow
2571 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2572 // we don't need to worry about that case here.
2573match curr_mode {
2574 ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2575for i in len..place.projections.len() {
2576if place.projections[i].kind == ProjectionKind::Deref
2577 && is_mut_ref(place.ty_before_projection(i))
2578 {
2579*curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2580break;
2581 }
2582 }
2583 }
25842585 ty::UpvarCapture::ByRef(..) => {}
2586 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2587 }
25882589place.projections.truncate(len);
2590}
25912592/// Determines the Ancestry relationship of Place A relative to Place B
2593///
2594/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2595/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2596/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2597fn determine_place_ancestry_relation<'tcx>(
2598 place_a: &Place<'tcx>,
2599 place_b: &Place<'tcx>,
2600) -> PlaceAncestryRelation {
2601// If Place A and Place B don't start off from the same root variable, they are divergent.
2602if place_a.base != place_b.base {
2603return PlaceAncestryRelation::Divergent;
2604 }
26052606// Assume of length of projections_a = n
2607let projections_a = &place_a.projections;
26082609// Assume of length of projections_b = m
2610let projections_b = &place_b.projections;
26112612let same_initial_projections =
2613 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
26142615if same_initial_projections {
2616use std::cmp::Ordering;
26172618// First min(n, m) projections are the same
2619 // Select Ancestor/Descendant
2620match projections_b.len().cmp(&projections_a.len()) {
2621 Ordering::Greater => PlaceAncestryRelation::Ancestor,
2622 Ordering::Equal => PlaceAncestryRelation::SamePlace,
2623 Ordering::Less => PlaceAncestryRelation::Descendant,
2624 }
2625 } else {
2626 PlaceAncestryRelation::Divergent2627 }
2628}
26292630/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2631/// borrow checking perspective, allowing us to save us on the size of the capture.
2632///
2633///
2634/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2635/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2636/// rightmost deref of the capture if the deref is applied to a shared ref.
2637///
2638/// Reason we only drop the last deref is because of the following edge case:
2639///
2640/// ```
2641/// # struct A { field_of_a: Box<i32> }
2642/// # struct B {}
2643/// # struct C<'a>(&'a i32);
2644/// struct MyStruct<'a> {
2645/// a: &'static A,
2646/// b: B,
2647/// c: C<'a>,
2648/// }
2649///
2650/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2651/// || drop(&*m.a.field_of_a)
2652/// // Here we really do want to capture `*m.a` because that outlives `'static`
2653///
2654/// // If we capture `m`, then the closure no longer outlives `'static`
2655/// // it is constrained to `'a`
2656/// }
2657/// ```
2658x;#[instrument(ret, level = "debug")]2659fn truncate_capture_for_optimization(
2660mut place: Place<'_>,
2661mut curr_mode: ty::UpvarCapture,
2662) -> (Place<'_>, ty::UpvarCapture) {
2663let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
26642665// Find the rightmost deref (if any). All the projections that come after this
2666 // are fields or other "in-place pointer adjustments"; these refer therefore to
2667 // data owned by whatever pointer is being dereferenced here.
2668let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
26692670match idx {
2671// If that pointer is a shared reference, then we don't need those fields.
2672Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2673 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2674 }
2675None | Some(_) => {}
2676 }
26772678 (place, curr_mode)
2679}
26802681/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2682/// `span` is the span of the closure.
2683fn enable_precise_capture(span: Span) -> bool {
2684// We use span here to ensure that if the closure was generated by a macro with a different
2685 // edition.
2686span.at_least_rust_2021()
2687}