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 &&
!args.references_error() {
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:503",
"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(503u32),
::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.
398if let UpvarArgs::CoroutineClosure(args) = args
399 && !args.references_error()
400 {
401let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
402self.tcx,
403 ty::INNERMOST,
404 ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::ClosureEnv },
405 );
406407let num_args = args
408 .as_coroutine_closure()
409 .coroutine_closure_sig()
410 .skip_binder()
411 .tupled_inputs_ty
412 .tuple_fields()
413 .len();
414let typeck_results = self.typeck_results.borrow();
415416let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
417self.tcx,
418 ty::analyze_coroutine_closure_captures(
419 typeck_results.closure_min_captures_flattened(closure_def_id),
420 typeck_results
421 .closure_min_captures_flattened(
422self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
423 )
424// Skip the captures that are just moving the closure's args
425 // into the coroutine. These are always by move, and we append
426 // those later in the `CoroutineClosureSignature` helper functions.
427.skip(num_args),
428 |(_, parent_capture), (_, child_capture)| {
429// This is subtle. See documentation on function.
430let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
431 parent_capture,
432 child_capture,
433 );
434435let upvar_ty = child_capture.place.ty();
436let capture = child_capture.info.capture_kind;
437// Not all upvars are captured by ref, so use
438 // `apply_capture_kind_on_capture_ty` to ensure that we
439 // compute the right captured type.
440apply_capture_kind_on_capture_ty(
441self.tcx,
442 upvar_ty,
443 capture,
444if needs_ref {
445 closure_env_region
446 } else {
447self.tcx.lifetimes.re_erased
448 },
449 )
450 },
451 ),
452 );
453let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
454self.tcx,
455 ty::Binder::bind_with_vars(
456self.tcx.mk_fn_sig_safe_rust_abi([], tupled_upvars_ty_for_borrow),
457self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
458 ty::BoundRegionKind::ClosureEnv,
459 )]),
460 ),
461 );
462self.demand_eqtype(
463 span,
464 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
465 coroutine_captures_by_ref_ty,
466 );
467468// Additionally, we can now constrain the coroutine's kind type.
469 //
470 // We only do this if `infer_kind`, because if we have constrained
471 // the kind from closure signature inference, the kind inferred
472 // for the inner coroutine may actually be more restrictive.
473if infer_kind {
474let ty::Coroutine(_, coroutine_args) =
475*self.typeck_results.borrow().expr_ty(body.value).kind()
476else {
477bug!();
478 };
479self.demand_eqtype(
480 span,
481 coroutine_args.as_coroutine().kind_ty(),
482 Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
483 );
484 }
485 }
486487self.log_closure_min_capture_info(closure_def_id, span);
488489// Now that we've analyzed the closure, we know how each
490 // variable is borrowed, and we know what traits the closure
491 // implements (Fn vs FnMut etc). We now have some updates to do
492 // with that information.
493 //
494 // Note that no closure type C may have an upvar of type C
495 // (though it may reference itself via a trait object). This
496 // results from the desugaring of closures to a struct like
497 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
498 // C, then the type would have infinite size (and the
499 // inference algorithm will reject it).
500501 // Equate the type variables for the upvars with the actual types.
502let final_upvar_tys = self.final_upvar_tys(closure_def_id);
503debug!(?closure_hir_id, ?args, ?final_upvar_tys);
504505if self.tcx.features().unsized_fn_params() {
506for capture in
507self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
508 {
509if let UpvarCapture::ByValue = capture.info.capture_kind {
510self.require_type_is_sized(
511 capture.place.ty(),
512 capture.get_path_span(self.tcx),
513 ObligationCauseCode::SizedClosureCapture(closure_def_id),
514 );
515 }
516 }
517 }
518519// Build a tuple (U0..Un) of the final upvar types U0..Un
520 // and unify the upvar tuple type in the closure with it:
521let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
522self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
523524let fake_reads = delegate.fake_reads;
525526self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
527528if self.tcx.sess.opts.unstable_opts.profile_closures {
529self.typeck_results.borrow_mut().closure_size_eval.insert(
530 closure_def_id,
531 ClosureSizeProfileData {
532 before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
533 after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
534 },
535 );
536 }
537538// If we are also inferred the closure kind here,
539 // process any deferred resolutions.
540let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
541for deferred_call_resolution in deferred_call_resolutions {
542 deferred_call_resolution.resolve(&FnCtxt::new(self, self.param_env, closure_def_id));
543 }
544 }
545546/// Determines whether the body of the coroutine uses its upvars in a way that
547 /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
548 /// In a more detailed comment above, we care whether this happens, since if
549 /// this happens, we want to force the coroutine to move all of the upvars it
550 /// would've borrowed from the parent coroutine-closure.
551 ///
552 /// This only really makes sense to be called on the child coroutine of a
553 /// coroutine-closure.
554fn coroutine_body_consumes_upvars(
555&self,
556 coroutine_def_id: LocalDefId,
557 body: &'tcx hir::Body<'tcx>,
558 ) -> bool {
559// This block contains argument capturing details. Since arguments
560 // aren't upvars, we do not care about them for determining if the
561 // coroutine body actually consumes its upvars.
562let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
563else {
564::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
565 };
566// Specifically, we only care about the *real* body of the coroutine.
567 // We skip out into the drop-temps within the block of the body in order
568 // to skip over the args of the desugaring.
569let hir::ExprKind::DropTemps(body) = body.kind else {
570::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
571 };
572573let coroutine_fcx =
574FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id);
575576let mut delegate = InferBorrowKind {
577 fcx: &coroutine_fcx,
578 closure_def_id: coroutine_def_id,
579 capture_information: Default::default(),
580 fake_reads: Default::default(),
581 };
582583let _ = euv::ExprUseVisitor::new(&coroutine_fcx, &mut delegate).consume_expr(body);
584585let (_, kind, _) = self.process_collected_capture_information(
586 hir::CaptureBy::Ref,
587&delegate.capture_information,
588 );
589590#[allow(non_exhaustive_omitted_patterns)] match kind {
ty::ClosureKind::FnOnce => true,
_ => false,
}matches!(kind, ty::ClosureKind::FnOnce)591 }
592593// Returns a list of `Ty`s for each upvar.
594fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
595self.typeck_results
596 .borrow()
597 .closure_min_captures_flattened(closure_id)
598 .map(|captured_place| {
599let upvar_ty = captured_place.place.ty();
600let capture = captured_place.info.capture_kind;
601602{
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:602",
"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(602u32),
::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);
603604apply_capture_kind_on_capture_ty(
605self.tcx,
606upvar_ty,
607capture,
608self.tcx.lifetimes.re_erased,
609 )
610 })
611 .collect()
612 }
613614/// Adjusts the closure capture information to ensure that the operations aren't unsafe,
615 /// and that the path can be captured with required capture kind (depending on use in closure,
616 /// move closure etc.)
617 ///
618 /// Returns the set of adjusted information along with the inferred closure kind and span
619 /// associated with the closure kind inference.
620 ///
621 /// Note that we *always* infer a minimal kind, even if
622 /// we don't always *use* that in the final result (i.e., sometimes
623 /// we've taken the closure kind from the expectations instead, and
624 /// for coroutines we don't even implement the closure traits
625 /// really).
626 ///
627 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
628 /// contains a `Some()` with the `Place` that caused us to do so.
629fn process_collected_capture_information(
630&self,
631 capture_clause: hir::CaptureBy,
632 capture_information: &InferredCaptureInformation<'tcx>,
633 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
634let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
635let mut origin: Option<(Span, Place<'tcx>)> = None;
636637let processed = capture_information638 .iter()
639 .cloned()
640 .map(|(place, mut capture_info)| {
641// Apply rules for safety before inferring closure kind
642let (place, capture_kind) =
643restrict_capture_precision(place, capture_info.capture_kind);
644645let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
646647let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
648self.tcx.hir_span(usage_expr)
649 } else {
650::core::panicking::panic("internal error: entered unreachable code")unreachable!()651 };
652653let updated = match capture_kind {
654 ty::UpvarCapture::ByValue => match closure_kind {
655 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
656 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
657 }
658// If closure is already FnOnce, don't update
659ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
660 },
661662 ty::UpvarCapture::ByRef(
663 ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
664 ) => {
665match closure_kind {
666 ty::ClosureKind::Fn => {
667 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
668 }
669// Don't update the origin
670ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
671 (closure_kind, origin.take())
672 }
673 }
674 }
675676_ => (closure_kind, origin.take()),
677 };
678679closure_kind = updated.0;
680origin = updated.1;
681682let (place, capture_kind) = match capture_clause {
683 hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
684 hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
685 hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
686 };
687688// This restriction needs to be applied after we have handled adjustments for `move`
689 // closures. We want to make sure any adjustment that might make us move the place into
690 // the closure gets handled.
691let (place, capture_kind) =
692restrict_precision_for_drop_types(self, place, capture_kind);
693694capture_info.capture_kind = capture_kind;
695 (place, capture_info)
696 })
697 .collect();
698699 (processed, closure_kind, origin)
700 }
701702/// Analyzes the information collected by `InferBorrowKind` to compute the min number of
703 /// Places (and corresponding capture kind) that we need to keep track of to support all
704 /// the required captured paths.
705 ///
706 ///
707 /// Note: If this function is called multiple times for the same closure, it will update
708 /// the existing min_capture map that is stored in TypeckResults.
709 ///
710 /// Eg:
711 /// ```
712 /// #[derive(Debug)]
713 /// struct Point { x: i32, y: i32 }
714 ///
715 /// let s = String::from("s"); // hir_id_s
716 /// let mut p = Point { x: 2, y: -2 }; // his_id_p
717 /// let c = || {
718 /// println!("{s:?}"); // L1
719 /// p.x += 10; // L2
720 /// println!("{}" , p.y); // L3
721 /// println!("{p:?}"); // L4
722 /// drop(s); // L5
723 /// };
724 /// ```
725 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
726 /// the lines L1..5 respectively.
727 ///
728 /// InferBorrowKind results in a structure like this:
729 ///
730 /// ```ignore (illustrative)
731 /// {
732 /// Place(base: hir_id_s, projections: [], ....) -> {
733 /// capture_kind_expr: hir_id_L5,
734 /// path_expr_id: hir_id_L5,
735 /// capture_kind: ByValue
736 /// },
737 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
738 /// capture_kind_expr: hir_id_L2,
739 /// path_expr_id: hir_id_L2,
740 /// capture_kind: ByValue
741 /// },
742 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
743 /// capture_kind_expr: hir_id_L3,
744 /// path_expr_id: hir_id_L3,
745 /// capture_kind: ByValue
746 /// },
747 /// Place(base: hir_id_p, projections: [], ...) -> {
748 /// capture_kind_expr: hir_id_L4,
749 /// path_expr_id: hir_id_L4,
750 /// capture_kind: ByValue
751 /// },
752 /// }
753 /// ```
754 ///
755 /// After the min capture analysis, we get:
756 /// ```ignore (illustrative)
757 /// {
758 /// hir_id_s -> [
759 /// Place(base: hir_id_s, projections: [], ....) -> {
760 /// capture_kind_expr: hir_id_L5,
761 /// path_expr_id: hir_id_L5,
762 /// capture_kind: ByValue
763 /// },
764 /// ],
765 /// hir_id_p -> [
766 /// Place(base: hir_id_p, projections: [], ...) -> {
767 /// capture_kind_expr: hir_id_L2,
768 /// path_expr_id: hir_id_L4,
769 /// capture_kind: ByValue
770 /// },
771 /// ],
772 /// }
773 /// ```
774#[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(774u32),
::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:899",
"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(899u32),
::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:960",
"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(960u32),
::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))]775fn compute_min_captures(
776&self,
777 closure_def_id: LocalDefId,
778 capture_information: InferredCaptureInformation<'tcx>,
779 closure_span: Span,
780 ) {
781if capture_information.is_empty() {
782return;
783 }
784785let mut typeck_results = self.typeck_results.borrow_mut();
786787let mut root_var_min_capture_list =
788 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
789790for (mut place, capture_info) in capture_information.into_iter() {
791let var_hir_id = match place.base {
792 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
793 base => bug!("Expected upvar, found={:?}", base),
794 };
795let var_ident = self.tcx.hir_ident(var_hir_id);
796797let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
798let mutability = self.determine_capture_mutability(&typeck_results, &place);
799let min_cap_list =
800vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
801 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
802continue;
803 };
804805// Go through each entry in the current list of min_captures
806 // - if ancestor is found, update its capture kind to account for current place's
807 // capture information.
808 //
809 // - if descendant is found, remove it from the list, and update the current place's
810 // capture information to account for the descendant's capture kind.
811 //
812 // We can never be in a case where the list contains both an ancestor and a descendant
813 // Also there can only be ancestor but in case of descendants there might be
814 // multiple.
815816let mut descendant_found = false;
817let mut updated_capture_info = capture_info;
818 min_cap_list.retain(|possible_descendant| {
819match determine_place_ancestry_relation(&place, &possible_descendant.place) {
820// current place is ancestor of possible_descendant
821PlaceAncestryRelation::Ancestor => {
822 descendant_found = true;
823824let mut possible_descendant = possible_descendant.clone();
825let backup_path_expr_id = updated_capture_info.path_expr_id;
826827// Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
828 // possible change in capture mode.
829truncate_place_to_len_and_update_capture_kind(
830&mut possible_descendant.place,
831&mut possible_descendant.info.capture_kind,
832 place.projections.len(),
833 );
834835 updated_capture_info =
836 determine_capture_info(updated_capture_info, possible_descendant.info);
837838// we need to keep the ancestor's `path_expr_id`
839updated_capture_info.path_expr_id = backup_path_expr_id;
840false
841}
842843_ => true,
844 }
845 });
846847let mut ancestor_found = false;
848if !descendant_found {
849for possible_ancestor in min_cap_list.iter_mut() {
850match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
851 PlaceAncestryRelation::SamePlace => {
852 ancestor_found = true;
853 possible_ancestor.info = determine_capture_info(
854 possible_ancestor.info,
855 updated_capture_info,
856 );
857858// Only one related place will be in the list.
859break;
860 }
861// current place is descendant of possible_ancestor
862PlaceAncestryRelation::Descendant => {
863 ancestor_found = true;
864let backup_path_expr_id = possible_ancestor.info.path_expr_id;
865866// Truncate the descendant (current place) to be same as the ancestor to handle any
867 // possible change in capture mode.
868truncate_place_to_len_and_update_capture_kind(
869&mut place,
870&mut updated_capture_info.capture_kind,
871 possible_ancestor.place.projections.len(),
872 );
873874 possible_ancestor.info = determine_capture_info(
875 possible_ancestor.info,
876 updated_capture_info,
877 );
878879// we need to keep the ancestor's `path_expr_id`
880possible_ancestor.info.path_expr_id = backup_path_expr_id;
881882// Only one related place will be in the list.
883break;
884 }
885_ => {}
886 }
887 }
888 }
889890// Only need to insert when we don't have an ancestor in the existing min capture list
891if !ancestor_found {
892let mutability = self.determine_capture_mutability(&typeck_results, &place);
893let captured_place =
894 ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
895 min_cap_list.push(captured_place);
896 }
897 }
898899debug!(
900"For closure={:?}, min_captures before sorting={:?}",
901 closure_def_id, root_var_min_capture_list
902 );
903904// Now that we have the minimized list of captures, sort the captures by field id.
905 // This causes the closure to capture the upvars in the same order as the fields are
906 // declared which is also the drop order. Thus, in situations where we capture all the
907 // fields of some type, the observable drop order will remain the same as it previously
908 // was even though we're dropping each capture individually.
909 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
910 // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
911for (_, captures) in &mut root_var_min_capture_list {
912 captures.sort_by(|capture1, capture2| {
913fn is_field<'a>(p: &&Projection<'a>) -> bool {
914match p.kind {
915 ProjectionKind::Field(_, _) => true,
916 ProjectionKind::Deref
917 | ProjectionKind::OpaqueCast
918 | ProjectionKind::UnwrapUnsafeBinder => false,
919 p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
920bug!("ProjectionKind {:?} was unexpected", p)
921 }
922 }
923 }
924925// Need to sort only by Field projections, so filter away others.
926 // A previous implementation considered other projection types too
927 // but that caused ICE #118144
928let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
929let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
930931for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
932// We do not need to look at the `Projection.ty` fields here because at each
933 // step of the iteration, the projections will either be the same and therefore
934 // the types must be as well or the current projection will be different and
935 // we will return the result of comparing the field indexes.
936match (p1.kind, p2.kind) {
937 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
938// Compare only if paths are different.
939 // Otherwise continue to the next iteration
940if i1 != i2 {
941return i1.cmp(&i2);
942 }
943 }
944// Given the filter above, this arm should never be hit
945(l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
946 }
947 }
948949self.dcx().span_delayed_bug(
950 closure_span,
951format!(
952"two identical projections: ({:?}, {:?})",
953 capture1.place.projections, capture2.place.projections
954 ),
955 );
956 std::cmp::Ordering::Equal
957 });
958 }
959960debug!(
961"For closure={:?}, min_captures after sorting={:#?}",
962 closure_def_id, root_var_min_capture_list
963 );
964 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
965 }
966967/// Perform the migration analysis for RFC 2229, and emit lint
968 /// `disjoint_capture_drop_reorder` if needed.
969fn perform_2229_migration_analysis(
970&self,
971 closure_def_id: LocalDefId,
972 body_id: hir::BodyId,
973 capture_clause: hir::CaptureBy,
974 span: Span,
975 ) {
976struct MigrationLint<'a, 'tcx> {
977 closure_def_id: LocalDefId,
978 this: &'a FnCtxt<'a, 'tcx>,
979 body_id: hir::BodyId,
980 need_migrations: Vec<NeededMigration>,
981 migration_message: String,
982 }
983984impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for MigrationLint<'b, 'tcx> {
985fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
986let Self { closure_def_id, this, body_id, need_migrations, migration_message } =
987self;
988let mut lint = Diag::new(dcx, level, migration_message);
989990let (migration_string, migrated_variables_concat) =
991migration_suggestion_for_2229(this.tcx, &need_migrations);
992993let closure_hir_id = this.tcx.local_def_id_to_hir_id(closure_def_id);
994let closure_head_span = this.tcx.def_span(closure_def_id);
995996for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
997// Labels all the usage of the captured variable and why they are responsible
998 // for migration being needed
999for lint_note in diagnostics_info.iter() {
1000match &lint_note.captures_info {
1001 UpvarMigrationInfo::CapturingPrecise {
1002 source_expr: Some(capture_expr_id),
1003 var_name: captured_name,
1004 } => {
1005let cause_span = this.tcx.hir_span(*capture_expr_id);
1006 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 `{}`",
1007 this.tcx.hir_name(*var_hir_id),
1008 captured_name,
1009 ));
1010 }
1011 UpvarMigrationInfo::CapturingNothing { use_span } => {
1012 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",
1013 this.tcx.hir_name(*var_hir_id),
1014 ));
1015 }
10161017_ => {}
1018 }
10191020// Add a label pointing to where a captured variable affected by drop order
1021 // is dropped
1022if lint_note.reason.drop_order {
1023let drop_location_span = drop_location_span(this.tcx, closure_hir_id);
10241025match &lint_note.captures_info {
1026 UpvarMigrationInfo::CapturingPrecise {
1027 var_name: captured_name,
1028 ..
1029 } => {
1030 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",
1031 this.tcx.hir_name(*var_hir_id),
1032 captured_name,
1033 ));
1034 }
1035 UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1036 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",
1037 v = this.tcx.hir_name(*var_hir_id),
1038 ));
1039 }
1040 }
1041 }
10421043// Add a label explaining why a closure no longer implements a trait
1044for &missing_trait in &lint_note.reason.auto_traits {
1045// not capturing something anymore cannot cause a trait to fail to be implemented:
1046match &lint_note.captures_info {
1047 UpvarMigrationInfo::CapturingPrecise {
1048 var_name: captured_name,
1049 ..
1050 } => {
1051let var_name = this.tcx.hir_name(*var_hir_id);
1052 lint.span_label(
1053 closure_head_span,
1054::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!(
1055"\
1056 in Rust 2018, this closure implements {missing_trait} \
1057 as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1058 this closure will no longer implement {missing_trait} \
1059 because `{var_name}` is not fully captured \
1060 and `{captured_name}` does not implement {missing_trait}"
1061),
1062 );
1063 }
10641065// Cannot happen: if we don't capture a variable, we impl strictly more traits
1066 UpvarMigrationInfo::CapturingNothing { use_span } => ::rustc_middle::util::bug::span_bug_fmt(*use_span,
format_args!("missing trait from not capturing something"))span_bug!(
1067*use_span,
1068"missing trait from not capturing something"
1069),
1070 }
1071 }
1072 }
1073 }
10741075let 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!(
1076"add a dummy let to cause {migrated_variables_concat} to be fully captured"
1077);
10781079let closure_span = this.tcx.hir_span_with_body(closure_hir_id);
1080let mut closure_body_span = {
1081// If the body was entirely expanded from a macro
1082 // invocation, i.e. the body is not contained inside the
1083 // closure span, then we walk up the expansion until we
1084 // find the span before the expansion.
1085let s = this.tcx.hir_span_with_body(body_id.hir_id);
1086s.find_ancestor_inside(closure_span).unwrap_or(s)
1087 };
10881089if let Ok(mut s) = this.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1090if s.starts_with('$') {
1091// Looks like a macro fragment. Try to find the real block.
1092if let hir::Node::Expr(&hir::Expr {
1093 kind: hir::ExprKind::Block(block, ..),
1094 ..
1095 }) = this.tcx.hir_node(body_id.hir_id)
1096 {
1097// If the body is a block (with `{..}`), we use the span of that block.
1098 // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1099 // Since we know it's a block, we know we can insert the `let _ = ..` without
1100 // breaking the macro syntax.
1101if let Ok(snippet) =
1102this.tcx.sess.source_map().span_to_snippet(block.span)
1103 {
1104closure_body_span = block.span;
1105s = snippet;
1106 }
1107 }
1108 }
11091110let mut lines = s.lines();
1111let line1 = lines.next().unwrap_or_default();
11121113if line1.trim_end() == "{" {
1114// This is a multi-line closure with just a `{` on the first line,
1115 // so we put the `let` on its own line.
1116 // We take the indentation from the next non-empty line.
1117let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1118let indent =
1119line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1120lint.span_suggestion(
1121closure_body_span1122 .with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len()))
1123 .shrink_to_lo(),
1124diagnostic_msg,
1125::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}{1};", indent,
migration_string))
})format!("\n{indent}{migration_string};"),
1126 Applicability::MachineApplicable,
1127 );
1128 } else if line1.starts_with('{') {
1129// This is a closure with its body wrapped in
1130 // braces, but with more than just the opening
1131 // brace on the first line. We put the `let`
1132 // directly after the `{`.
1133lint.span_suggestion(
1134closure_body_span1135 .with_lo(closure_body_span.lo() + BytePos(1))
1136 .shrink_to_lo(),
1137diagnostic_msg,
1138::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0};", migration_string))
})format!(" {migration_string};"),
1139 Applicability::MachineApplicable,
1140 );
1141 } else {
1142// This is a closure without braces around the body.
1143 // We add braces to add the `let` before the body.
1144lint.multipart_suggestion(
1145diagnostic_msg,
1146::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![
1147 (
1148 closure_body_span.shrink_to_lo(),
1149format!("{{ {migration_string}; "),
1150 ),
1151 (closure_body_span.shrink_to_hi(), " }".to_string()),
1152 ],
1153 Applicability::MachineApplicable,
1154 );
1155 }
1156 } else {
1157lint.span_suggestion(
1158closure_span,
1159diagnostic_msg,
1160migration_string,
1161 Applicability::HasPlaceholders,
1162 );
1163 }
1164lint1165 }
1166 }
11671168let (need_migrations, reasons) = self.compute_2229_migrations(
1169closure_def_id,
1170span,
1171capture_clause,
1172self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
1173 );
11741175if !need_migrations.is_empty() {
1176self.tcx.emit_node_span_lint(
1177 lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
1178self.tcx.local_def_id_to_hir_id(closure_def_id),
1179self.tcx.def_span(closure_def_id),
1180MigrationLint {
1181 this: self,
1182 migration_message: reasons.migration_message(),
1183closure_def_id,
1184body_id,
1185need_migrations,
1186 },
1187 );
1188 }
1189 }
11901191/// Combines all the reasons for 2229 migrations
1192fn compute_2229_migrations_reasons(
1193&self,
1194 auto_trait_reasons: UnordSet<&'static str>,
1195 drop_order: bool,
1196 ) -> MigrationWarningReason {
1197MigrationWarningReason {
1198 auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1199drop_order,
1200 }
1201 }
12021203/// Figures out the list of root variables (and their types) that aren't completely
1204 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1205 /// differ between the root variable and the captured paths.
1206 ///
1207 /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1208 /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1209fn compute_2229_migrations_for_trait(
1210&self,
1211 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1212 var_hir_id: HirId,
1213 closure_clause: hir::CaptureBy,
1214 ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1215let auto_traits_def_id = [
1216self.tcx.lang_items().clone_trait(),
1217self.tcx.lang_items().sync_trait(),
1218self.tcx.get_diagnostic_item(sym::Send),
1219self.tcx.lang_items().unpin_trait(),
1220self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1221self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1222 ];
1223const AUTO_TRAITS: [&str; 6] =
1224 ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
12251226let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
12271228let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
12291230let ty = match closure_clause {
1231 hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1232hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1233// For non move closure the capture kind is the max capture kind of all captures
1234 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1235let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1236for capture in root_var_min_capture_list.iter() {
1237 max_capture_info = determine_capture_info(max_capture_info, capture.info);
1238 }
12391240apply_capture_kind_on_capture_ty(
1241self.tcx,
1242ty,
1243max_capture_info.capture_kind,
1244self.tcx.lifetimes.re_erased,
1245 )
1246 }
1247 };
12481249let mut obligations_should_hold = Vec::new();
1250// Checks if a root variable implements any of the auto traits
1251for check_trait in auto_traits_def_id.iter() {
1252 obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1253self.infcx
1254 .type_implements_trait(check_trait, [ty], self.param_env)
1255 .must_apply_modulo_regions()
1256 }));
1257 }
12581259let mut problematic_captures = FxIndexMap::default();
1260// Check whether captured fields also implement the trait
1261for capture in root_var_min_capture_list.iter() {
1262let ty = apply_capture_kind_on_capture_ty(
1263self.tcx,
1264 capture.place.ty(),
1265 capture.info.capture_kind,
1266self.tcx.lifetimes.re_erased,
1267 );
12681269// Checks if a capture implements any of the auto traits
1270let mut obligations_holds_for_capture = Vec::new();
1271for check_trait in auto_traits_def_id.iter() {
1272 obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1273self.infcx
1274 .type_implements_trait(check_trait, [ty], self.param_env)
1275 .must_apply_modulo_regions()
1276 }));
1277 }
12781279let mut capture_problems = UnordSet::default();
12801281// Checks if for any of the auto traits, one or more trait is implemented
1282 // by the root variable but not by the capture
1283for (idx, _) in obligations_should_hold.iter().enumerate() {
1284if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1285 capture_problems.insert(AUTO_TRAITS[idx]);
1286 }
1287 }
12881289if !capture_problems.is_empty() {
1290 problematic_captures.insert(
1291 UpvarMigrationInfo::CapturingPrecise {
1292 source_expr: capture.info.path_expr_id,
1293 var_name: capture.to_string(self.tcx),
1294 },
1295 capture_problems,
1296 );
1297 }
1298 }
1299if !problematic_captures.is_empty() {
1300return Some(problematic_captures);
1301 }
1302None1303 }
13041305/// Figures out the list of root variables (and their types) that aren't completely
1306 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1307 /// some path starting at that root variable **might** be affected.
1308 ///
1309 /// The output list would include a root variable if:
1310 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1311 /// enabled, **and**
1312 /// - It wasn't completely captured by the closure, **and**
1313 /// - One of the paths starting at this root variable, that is not captured needs Drop.
1314 ///
1315 /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1316 /// are no significant drops than None is returned
1317#[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(1317u32),
::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:1333",
"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(&["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:1346",
"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(1346u32),
::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:1364",
"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(1364u32),
::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:1383",
"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(1383u32),
::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:1384",
"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(1384u32),
::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:1387",
"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(1387u32),
::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:1391",
"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(1391u32),
::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))]1318fn compute_2229_migrations_for_drop(
1319&self,
1320 closure_def_id: LocalDefId,
1321 closure_span: Span,
1322 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1323 closure_clause: hir::CaptureBy,
1324 var_hir_id: HirId,
1325 ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1326let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
13271328// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1329if !ty.has_significant_drop(
1330self.tcx,
1331 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1332 ) {
1333debug!("does not have significant drop");
1334return None;
1335 }
13361337let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1338// The upvar is mentioned within the closure but no path starting from it is
1339 // used. This occurs when you have (e.g.)
1340 //
1341 // ```
1342 // let x = move || {
1343 // let _ = y;
1344 // });
1345 // ```
1346debug!("no path starting from it is used");
13471348match closure_clause {
1349// Only migrate if closure is a move closure
1350hir::CaptureBy::Value { .. } => {
1351let mut diagnostics_info = FxIndexSet::default();
1352let upvars =
1353self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1354let upvar = upvars[&var_hir_id];
1355 diagnostics_info
1356 .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1357return Some(diagnostics_info);
1358 }
1359 hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1360 }
13611362return None;
1363 };
1364debug!(?root_var_min_capture_list);
13651366let mut projections_list = Vec::new();
1367let mut diagnostics_info = FxIndexSet::default();
13681369for captured_place in root_var_min_capture_list.iter() {
1370match captured_place.info.capture_kind {
1371// Only care about captures that are moved into the closure
1372ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1373 projections_list.push(captured_place.place.projections.as_slice());
1374 diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1375 source_expr: captured_place.info.path_expr_id,
1376 var_name: captured_place.to_string(self.tcx),
1377 });
1378 }
1379 ty::UpvarCapture::ByRef(..) => {}
1380 }
1381 }
13821383debug!(?projections_list);
1384debug!(?diagnostics_info);
13851386let is_moved = !projections_list.is_empty();
1387debug!(?is_moved);
13881389let is_not_completely_captured =
1390 root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1391debug!(?is_not_completely_captured);
13921393if is_moved
1394 && is_not_completely_captured
1395 && self.has_significant_drop_outside_of_captures(
1396 closure_def_id,
1397 closure_span,
1398 ty,
1399 projections_list,
1400 )
1401 {
1402return Some(diagnostics_info);
1403 }
14041405None
1406}
14071408/// Figures out the list of root variables (and their types) that aren't completely
1409 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1410 /// order of some path starting at that root variable **might** be affected or auto-traits
1411 /// differ between the root variable and the captured paths.
1412 ///
1413 /// The output list would include a root variable if:
1414 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1415 /// enabled, **and**
1416 /// - It wasn't completely captured by the closure, **and**
1417 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1418 /// - One of the paths captured does not implement all the auto-traits its root variable
1419 /// implements.
1420 ///
1421 /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1422 /// containing the reason why root variables whose HirId is contained in the vector should
1423 /// be captured
1424#[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(1424u32),
::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))]1425fn compute_2229_migrations(
1426&self,
1427 closure_def_id: LocalDefId,
1428 closure_span: Span,
1429 closure_clause: hir::CaptureBy,
1430 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1431 ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1432let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1433return (Vec::new(), MigrationWarningReason::default());
1434 };
14351436let mut need_migrations = Vec::new();
1437let mut auto_trait_migration_reasons = UnordSet::default();
1438let mut drop_migration_needed = false;
14391440// Perform auto-trait analysis
1441for (&var_hir_id, _) in upvars.iter() {
1442let mut diagnostics_info = Vec::new();
14431444let auto_trait_diagnostic = self
1445.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1446 .unwrap_or_default();
14471448let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1449.compute_2229_migrations_for_drop(
1450 closure_def_id,
1451 closure_span,
1452 min_captures,
1453 closure_clause,
1454 var_hir_id,
1455 ) {
1456 drop_migration_needed = true;
1457 diagnostics_info
1458 } else {
1459 FxIndexSet::default()
1460 };
14611462// Combine all the captures responsible for needing migrations into one IndexSet
1463let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1464for key in auto_trait_diagnostic.keys() {
1465 capture_diagnostic.insert(key.clone());
1466 }
14671468let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1469 capture_diagnostic.sort_by_cached_key(|info| match info {
1470 UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1471 (0, Some(var_name.clone()))
1472 }
1473 UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1474 });
1475for captures_info in capture_diagnostic {
1476// Get the auto trait reasons of why migration is needed because of that capture, if there are any
1477let capture_trait_reasons =
1478if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1479 reasons.clone()
1480 } else {
1481 UnordSet::default()
1482 };
14831484// Check if migration is needed because of drop reorder as a result of that capture
1485let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
14861487// Combine all the reasons of why the root variable should be captured as a result of
1488 // auto trait implementation issues
1489auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
14901491 diagnostics_info.push(MigrationLintNote {
1492 captures_info,
1493 reason: self.compute_2229_migrations_reasons(
1494 capture_trait_reasons,
1495 capture_drop_reorder_reason,
1496 ),
1497 });
1498 }
14991500if !diagnostics_info.is_empty() {
1501 need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1502 }
1503 }
1504 (
1505 need_migrations,
1506self.compute_2229_migrations_reasons(
1507 auto_trait_migration_reasons,
1508 drop_migration_needed,
1509 ),
1510 )
1511 }
15121513/// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1514 /// of a root variable and a list of captured paths starting at this root variable (expressed
1515 /// using list of `Projection` slices), it returns true if there is a path that is not
1516 /// captured starting at this root variable that implements Drop.
1517 ///
1518 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1519 /// path say P and then list of projection slices which represent the different captures moved
1520 /// into the closure starting off of P.
1521 ///
1522 /// This will make more sense with an example:
1523 ///
1524 /// ```rust,edition2021
1525 ///
1526 /// struct FancyInteger(i32); // This implements Drop
1527 ///
1528 /// struct Point { x: FancyInteger, y: FancyInteger }
1529 /// struct Color;
1530 ///
1531 /// struct Wrapper { p: Point, c: Color }
1532 ///
1533 /// fn f(w: Wrapper) {
1534 /// let c = || {
1535 /// // Closure captures w.p.x and w.c by move.
1536 /// };
1537 ///
1538 /// c();
1539 /// }
1540 /// ```
1541 ///
1542 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1543 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1544 /// therefore Drop ordering would change and we want this function to return true.
1545 ///
1546 /// Call stack to figure out if we need to migrate for `w` would look as follows:
1547 ///
1548 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1549 /// `w[c]`.
1550 /// Notation:
1551 /// - Ty(place): Type of place
1552 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1553 /// respectively.
1554 /// ```ignore (illustrative)
1555 /// (Ty(w), [ &[p, x], &[c] ])
1556 /// // |
1557 /// // ----------------------------
1558 /// // | |
1559 /// // v v
1560 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
1561 /// // | |
1562 /// // v v
1563 /// (Ty(w.p), [ &[x] ]) false
1564 /// // |
1565 /// // |
1566 /// // -------------------------------
1567 /// // | |
1568 /// // v v
1569 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
1570 /// // | |
1571 /// // v v
1572 /// false NeedsSignificantDrop(Ty(w.p.y))
1573 /// // |
1574 /// // v
1575 /// true
1576 /// ```
1577 ///
1578 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1579 /// This implies that the `w.c` is completely captured by the closure.
1580 /// Since drop for this path will be called when the closure is
1581 /// dropped we don't need to migrate for it.
1582 ///
1583 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1584 /// path wasn't captured by the closure. Also note that even
1585 /// though we didn't capture this path, the function visits it,
1586 /// which is kind of the point of this function. We then return
1587 /// if the type of `w.p.y` implements Drop, which in this case is
1588 /// true.
1589 ///
1590 /// Consider another example:
1591 ///
1592 /// ```ignore (pseudo-rust)
1593 /// struct X;
1594 /// impl Drop for X {}
1595 ///
1596 /// struct Y(X);
1597 /// impl Drop for Y {}
1598 ///
1599 /// fn foo() {
1600 /// let y = Y(X);
1601 /// let c = || move(y.0);
1602 /// }
1603 /// ```
1604 ///
1605 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1606 /// return true, because even though all paths starting at `y` are captured, `y` itself
1607 /// implements Drop which will be affected since `y` isn't completely captured.
1608fn has_significant_drop_outside_of_captures(
1609&self,
1610 closure_def_id: LocalDefId,
1611 closure_span: Span,
1612 base_path_ty: Ty<'tcx>,
1613 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1614 ) -> bool {
1615// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1616let needs_drop = |ty: Ty<'tcx>| {
1617ty.has_significant_drop(
1618self.tcx,
1619 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1620 )
1621 };
16221623let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1624let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, closure_span);
1625self.infcx
1626 .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1627 .must_apply_modulo_regions()
1628 };
16291630let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
16311632// If there is a case where no projection is applied on top of current place
1633 // then there must be exactly one capture corresponding to such a case. Note that this
1634 // represents the case of the path being completely captured by the variable.
1635 //
1636 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1637 // capture `a.b.c`, because that violates min capture.
1638let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
16391640if !(!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));
16411642if is_completely_captured {
1643// The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1644 // when the closure is dropped.
1645return false;
1646 }
16471648if captured_by_move_projs.is_empty() {
1649return needs_drop(base_path_ty);
1650 }
16511652if is_drop_defined_for_ty {
1653// If drop is implemented for this type then we need it to be fully captured,
1654 // and we know it is not completely captured because of the previous checks.
16551656 // Note that this is a bug in the user code that will be reported by the
1657 // borrow checker, since we can't move out of drop types.
16581659 // The bug exists in the user's code pre-migration, and we don't migrate here.
1660return false;
1661 }
16621663match base_path_ty.kind() {
1664// Observations:
1665 // - `captured_by_move_projs` is not empty. Therefore we can call
1666 // `captured_by_move_projs.first().unwrap()` safely.
1667 // - All entries in `captured_by_move_projs` have at least one projection.
1668 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
16691670 // We don't capture derefs in case of move captures, which would have be applied to
1671 // access any further paths.
1672 ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1673 ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1674 ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
16751676 ty::Adt(def, args) => {
1677// Multi-variant enums are captured in entirety,
1678 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1679match (&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);
16801681// Only Field projections can be applied to a non-box Adt.
1682if !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!(
1683 captured_by_move_projs.iter().all(|projs| matches!(
1684 projs.first().unwrap().kind,
1685 ProjectionKind::Field(..)
1686 ))
1687 );
1688def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1689 |(i, field)| {
1690let paths_using_field = captured_by_move_projs1691 .iter()
1692 .filter_map(|projs| {
1693if let ProjectionKind::Field(field_idx, _) =
1694projs.first().unwrap().kind
1695 {
1696if field_idx == i { Some(&projs[1..]) } else { None }
1697 } else {
1698::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1699 }
1700 })
1701 .collect();
17021703let after_field_ty = field.ty(self.tcx, args).skip_norm_wip();
1704self.has_significant_drop_outside_of_captures(
1705closure_def_id,
1706closure_span,
1707after_field_ty,
1708paths_using_field,
1709 )
1710 },
1711 )
1712 }
17131714 ty::Tuple(fields) => {
1715// Only Field projections can be applied to a tuple.
1716if !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!(
1717 captured_by_move_projs.iter().all(|projs| matches!(
1718 projs.first().unwrap().kind,
1719 ProjectionKind::Field(..)
1720 ))
1721 );
17221723fields.iter().enumerate().any(|(i, element_ty)| {
1724let paths_using_field = captured_by_move_projs1725 .iter()
1726 .filter_map(|projs| {
1727if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1728 {
1729if field_idx.index() == i { Some(&projs[1..]) } else { None }
1730 } else {
1731::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1732 }
1733 })
1734 .collect();
17351736self.has_significant_drop_outside_of_captures(
1737closure_def_id,
1738closure_span,
1739element_ty,
1740paths_using_field,
1741 )
1742 })
1743 }
17441745// Anything else would be completely captured and therefore handled already.
1746_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1747 }
1748 }
17491750fn init_capture_kind_for_place(
1751&self,
1752 place: &Place<'tcx>,
1753 capture_clause: hir::CaptureBy,
1754 ) -> ty::UpvarCapture {
1755match capture_clause {
1756// In case of a move closure if the data is accessed through a reference we
1757 // want to capture by ref to allow precise capture using reborrows.
1758 //
1759 // If the data will be moved out of this place, then the place will be truncated
1760 // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1761 //
1762 // For example:
1763 //
1764 // struct Buffer<'a> {
1765 // x: &'a String,
1766 // y: Vec<u8>,
1767 // }
1768 //
1769 // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1770 // let c = move || b.x;
1771 // drop(b);
1772 // c
1773 // }
1774 //
1775 // Even though the closure is declared as move, when we are capturing borrowed data (in
1776 // this case, *b.x) we prefer to capture by reference.
1777 // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1778 // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1779 // before, which is also an error.
1780hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1781 ty::UpvarCapture::ByValue1782 }
1783 hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1784 ty::UpvarCapture::ByUse1785 }
1786 hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1787 ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1788 }
1789 }
1790 }
17911792fn place_for_root_variable(
1793&self,
1794 closure_def_id: LocalDefId,
1795 var_hir_id: HirId,
1796 ) -> Place<'tcx> {
1797let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
17981799let place = Place {
1800 base_ty: self.node_ty(var_hir_id),
1801 base: PlaceBase::Upvar(upvar_id),
1802 projections: Default::default(),
1803 };
18041805// Normalize eagerly when inserting into `capture_information`, so all downstream
1806 // capture analysis can assume a normalized `Place`.
1807self.normalize(self.tcx.hir_span(var_hir_id), Unnormalized::new_wip(place))
1808 }
18091810fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1811self.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)1812 }
18131814fn log_capture_analysis_first_pass(
1815&self,
1816 closure_def_id: LocalDefId,
1817 capture_information: &InferredCaptureInformation<'tcx>,
1818 closure_span: Span,
1819 ) {
1820if self.should_log_capture_analysis(closure_def_id) {
1821let mut diag =
1822self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1823for (place, capture_info) in capture_information {
1824let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1825let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
})format!("Capturing {capture_str}");
18261827let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1828 diag.span_note(span, output_str);
1829 }
1830diag.emit();
1831 }
1832 }
18331834fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1835if self.should_log_capture_analysis(closure_def_id) {
1836if let Some(min_captures) =
1837self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1838 {
1839let mut diag =
1840self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
18411842for (_, min_captures_for_var) in min_captures {
1843for capture in min_captures_for_var {
1844let place = &capture.place;
1845let capture_info = &capture.info;
18461847let capture_str =
1848 construct_capture_info_string(self.tcx, place, capture_info);
1849let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
})format!("Min Capture {capture_str}");
18501851if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1852let path_span = capture_info
1853 .path_expr_id
1854 .map_or(closure_span, |e| self.tcx.hir_span(e));
1855let capture_kind_span = capture_info
1856 .capture_kind_expr_id
1857 .map_or(closure_span, |e| self.tcx.hir_span(e));
18581859let mut multi_span: MultiSpan =
1860 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]);
18611862let capture_kind_label =
1863 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1864let path_label = construct_path_string(self.tcx, place);
18651866 multi_span.push_span_label(path_span, path_label);
1867 multi_span.push_span_label(capture_kind_span, capture_kind_label);
18681869 diag.span_note(multi_span, output_str);
1870 } else {
1871let span = capture_info
1872 .path_expr_id
1873 .map_or(closure_span, |e| self.tcx.hir_span(e));
18741875 diag.span_note(span, output_str);
1876 };
1877 }
1878 }
1879diag.emit();
1880 }
1881 }
1882 }
18831884/// A captured place is mutable if
1885 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1886 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1887fn determine_capture_mutability(
1888&self,
1889 typeck_results: &'a TypeckResults<'tcx>,
1890 place: &Place<'tcx>,
1891 ) -> hir::Mutability {
1892let var_hir_id = match place.base {
1893 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1894_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1895 };
18961897let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
18981899let mut is_mutbl = bm.1;
19001901for pointer_ty in place.deref_tys() {
1902match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
1903// We don't capture derefs of raw ptrs
1904 ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
19051906// Dereferencing a mut-ref allows us to mut the Place if we don't deref
1907 // an immut-ref after on top of this.
1908ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
19091910// The place isn't mutable once we dereference an immutable reference.
1911ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
19121913// Dereferencing a box doesn't change mutability
1914ty::Adt(def, ..) if def.is_box() => {}
19151916 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!(
1917self.tcx.hir_span(var_hir_id),
1918"deref of unexpected pointer type {:?}",
1919 unexpected_ty
1920 ),
1921 }
1922 }
19231924is_mutbl1925 }
1926}
19271928/// Determines whether a child capture that is derived from a parent capture
1929/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1930///
1931/// There are two cases when this needs to happen:
1932///
1933/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1934/// that is the case by checking if the parent capture is by move, EXCEPT if we
1935/// apply a deref projection of an immutable reference, reborrows of immutable
1936/// references which aren't restricted to the LUB of the lifetimes of the deref
1937/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1938///
1939/// ```rust
1940/// let x = &1i32; // Let's call this lifetime `'1`.
1941/// let c = async move || {
1942/// println!("{:?}", *x);
1943/// // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1944/// // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1945/// };
1946/// ```
1947///
1948/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1949/// mutable borrow cannot live for longer than either the parent *or* the borrow
1950/// that we have on the original upvar. Therefore we always need to borrow the
1951/// child capture with the lifetime of the parent coroutine-closure's env.
1952///
1953/// ```rust
1954/// let mut x = 1i32;
1955/// let c = async || {
1956/// x = 1;
1957/// // The parent borrows `x` for some `&'1 mut i32`.
1958/// // However, when we call `c()`, we implicitly autoref for the signature of
1959/// // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1960/// // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1961/// // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1962/// };
1963/// ```
1964///
1965/// If either of these cases apply, then we should capture the borrow with the
1966/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1967/// not correct, then the program is not unsound, since we still borrowck and validate
1968/// the choices made from this function -- the only side-effect is that the user
1969/// may receive unnecessary borrowck errors.
1970fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
1971 parent_capture: &ty::CapturedPlace<'tcx>,
1972 child_capture: &ty::CapturedPlace<'tcx>,
1973) -> bool {
1974// (1.)
1975(!parent_capture.is_by_ref()
1976// This is just inlined `place.deref_tys()` but truncated to just
1977 // the child projections. Namely, look for a `&T` deref, since we
1978 // can always extend `&'short mut &'long T` to `&'long T`.
1979&& !child_capture1980 .place
1981 .projections
1982 .iter()
1983 .enumerate()
1984 .skip(parent_capture.place.projections.len())
1985 .any(|(idx, proj)| {
1986#[allow(non_exhaustive_omitted_patterns)] match proj.kind {
ProjectionKind::Deref => true,
_ => false,
}matches!(proj.kind, ProjectionKind::Deref)1987 && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
{
ty::Ref(.., ty::Mutability::Not) => true,
_ => false,
}matches!(
1988 child_capture.place.ty_before_projection(idx).kind(),
1989 ty::Ref(.., ty::Mutability::Not)
1990 )1991 }))
1992// (2.)
1993 || #[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))1994}
19951996/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1997/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1998fn restrict_repr_packed_field_ref_capture<'tcx>(
1999mut place: Place<'tcx>,
2000mut curr_borrow_kind: ty::UpvarCapture,
2001) -> (Place<'tcx>, ty::UpvarCapture) {
2002let pos = place.projections.iter().enumerate().position(|(i, p)| {
2003let ty = place.ty_before_projection(i);
20042005// Return true for fields of packed structs.
2006match p.kind {
2007 ProjectionKind::Field(..) => match ty.kind() {
2008 ty::Adt(def, _) if def.repr().packed() => {
2009// We stop here regardless of field alignment. Field alignment can change as
2010 // types change, including the types of private fields in other crates, and that
2011 // shouldn't affect how we compute our captures.
2012true
2013}
20142015_ => false,
2016 },
2017_ => false,
2018 }
2019 });
20202021if let Some(pos) = pos {
2022truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
2023 }
20242025 (place, curr_borrow_kind)
2026}
20272028/// Returns a Ty that applies the specified capture kind on the provided capture Ty
2029fn apply_capture_kind_on_capture_ty<'tcx>(
2030 tcx: TyCtxt<'tcx>,
2031 ty: Ty<'tcx>,
2032 capture_kind: UpvarCapture,
2033 region: ty::Region<'tcx>,
2034) -> Ty<'tcx> {
2035match capture_kind {
2036 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
2037 ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
2038 }
2039}
20402041/// Returns the Span of where the value with the provided HirId would be dropped
2042fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
2043let owner_id = tcx.hir_get_enclosing_scope(hir_id).unwrap();
20442045let owner_node = tcx.hir_node(owner_id);
2046let owner_span = match owner_node {
2047 hir::Node::Item(item) => match item.kind {
2048 hir::ItemKind::Fn { body: owner_id, .. } => tcx.hir_span(owner_id.hir_id),
2049_ => {
2050::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);
2051 }
2052 },
2053 hir::Node::Block(block) => tcx.hir_span(block.hir_id),
2054 hir::Node::TraitItem(item) => tcx.hir_span(item.hir_id()),
2055 hir::Node::ImplItem(item) => tcx.hir_span(item.hir_id()),
2056_ => {
2057::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);
2058 }
2059 };
2060tcx.sess.source_map().end_point(owner_span)
2061}
20622063struct InferBorrowKind<'a, 'tcx> {
2064 fcx: &'a FnCtxt<'a, 'tcx>,
2065// The def-id of the closure whose kind and upvar accesses are being inferred.
2066closure_def_id: LocalDefId,
20672068/// For each Place that is captured by the closure, we track the minimal kind of
2069 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2070 ///
2071 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2072 /// s.str2 via a MutableBorrow
2073 ///
2074 /// ```rust,no_run
2075 /// struct SomeStruct { str1: String, str2: String };
2076 ///
2077 /// // Assume that the HirId for the variable definition is `V1`
2078 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2079 ///
2080 /// let fix_s = |new_s2| {
2081 /// // Assume that the HirId for the expression `s.str1` is `E1`
2082 /// println!("Updating SomeStruct with str1={0}", s.str1);
2083 /// // Assume that the HirId for the expression `*s.str2` is `E2`
2084 /// s.str2 = new_s2;
2085 /// };
2086 /// ```
2087 ///
2088 /// For closure `fix_s`, (at a high level) the map contains
2089 ///
2090 /// ```ignore (illustrative)
2091 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2092 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2093 /// ```
2094capture_information: InferredCaptureInformation<'tcx>,
2095 fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2096}
20972098impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
2099#[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(2099u32),
::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")]2100fn fake_read(
2101&mut self,
2102 place_with_id: &PlaceWithHirId<'tcx>,
2103 cause: FakeReadCause,
2104 diag_expr_id: HirId,
2105 ) {
2106let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
21072108// We need to restrict Fake Read precision to avoid fake reading unsafe code,
2109 // such as deref of a raw pointer.
2110let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
21112112let span = self.fcx.tcx.hir_span(diag_expr_id);
2113let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
21142115let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
21162117let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2118self.fake_reads.push((place, cause, diag_expr_id));
2119 }
21202121#[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(2121u32),
::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")]2122fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2123let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2124assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21252126let span = self.fcx.tcx.hir_span(diag_expr_id);
2127let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
21282129self.capture_information.push((
2130 place,
2131 ty::CaptureInfo {
2132 capture_kind_expr_id: Some(diag_expr_id),
2133 path_expr_id: Some(diag_expr_id),
2134 capture_kind: ty::UpvarCapture::ByValue,
2135 },
2136 ));
2137 }
21382139#[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(2139u32),
::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")]2140fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2141let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2142assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21432144let span = self.fcx.tcx.hir_span(diag_expr_id);
2145let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
21462147self.capture_information.push((
2148 place,
2149 ty::CaptureInfo {
2150 capture_kind_expr_id: Some(diag_expr_id),
2151 path_expr_id: Some(diag_expr_id),
2152 capture_kind: ty::UpvarCapture::ByUse,
2153 },
2154 ));
2155 }
21562157#[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(2157u32),
::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")]2158fn borrow(
2159&mut self,
2160 place_with_id: &PlaceWithHirId<'tcx>,
2161 diag_expr_id: HirId,
2162 bk: ty::BorrowKind,
2163 ) {
2164let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2165assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21662167// The region here will get discarded/ignored
2168let capture_kind = ty::UpvarCapture::ByRef(bk);
21692170let span = self.fcx.tcx.hir_span(diag_expr_id);
2171let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
21722173// We only want repr packed restriction to be applied to reading references into a packed
2174 // struct, and not when the data is being moved. Therefore we call this method here instead
2175 // of in `restrict_capture_precision`.
2176let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(place, capture_kind);
21772178// Raw pointers don't inherit mutability
2179if place.deref_tys().any(Ty::is_raw_ptr) {
2180 capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2181 }
21822183self.capture_information.push((
2184 place,
2185 ty::CaptureInfo {
2186 capture_kind_expr_id: Some(diag_expr_id),
2187 path_expr_id: Some(diag_expr_id),
2188 capture_kind,
2189 },
2190 ));
2191 }
21922193#[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(2193u32),
::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")]2194fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2195self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2196 }
2197}
21982199/// Rust doesn't permit moving fields out of a type that implements drop
2200x;#[instrument(skip(fcx), ret, level = "debug")]2201fn restrict_precision_for_drop_types<'a, 'tcx>(
2202 fcx: &'a FnCtxt<'a, 'tcx>,
2203mut place: Place<'tcx>,
2204mut curr_mode: ty::UpvarCapture,
2205) -> (Place<'tcx>, ty::UpvarCapture) {
2206let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
22072208if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2209for i in 0..place.projections.len() {
2210match place.ty_before_projection(i).kind() {
2211 ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2212 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2213break;
2214 }
2215_ => {}
2216 }
2217 }
2218 }
22192220 (place, curr_mode)
2221}
22222223/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2224/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2225/// them completely.
2226/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2227fn restrict_precision_for_unsafe(
2228mut place: Place<'_>,
2229mut curr_mode: ty::UpvarCapture,
2230) -> (Place<'_>, ty::UpvarCapture) {
2231if place.base_ty.is_raw_ptr() {
2232truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2233 }
22342235if place.base_ty.is_union() {
2236truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2237 }
22382239for (i, proj) in place.projections.iter().enumerate() {
2240if proj.ty.is_raw_ptr() {
2241// Don't apply any projections on top of a raw ptr.
2242truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2243break;
2244 }
22452246if proj.ty.is_union() {
2247// Don't capture precise fields of a union.
2248truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2249break;
2250 }
2251 }
22522253 (place, curr_mode)
2254}
22552256/// Truncate projections so that the following rules are obeyed by the captured `place`:
2257/// - No Index projections are captured, since arrays are captured completely.
2258/// - No unsafe block is required to capture `place`.
2259///
2260/// Returns the truncated place and updated capture mode.
2261x;#[instrument(ret, level = "debug")]2262fn restrict_capture_precision(
2263 place: Place<'_>,
2264 curr_mode: ty::UpvarCapture,
2265) -> (Place<'_>, ty::UpvarCapture) {
2266let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
22672268if place.projections.is_empty() {
2269// Nothing to do here
2270return (place, curr_mode);
2271 }
22722273for (i, proj) in place.projections.iter().enumerate() {
2274match proj.kind {
2275 ProjectionKind::Index | ProjectionKind::Subslice => {
2276// Arrays are completely captured, so we drop Index and Subslice projections
2277truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2278return (place, curr_mode);
2279 }
2280 ProjectionKind::Deref => {}
2281 ProjectionKind::OpaqueCast => {}
2282 ProjectionKind::Field(..) => {}
2283 ProjectionKind::UnwrapUnsafeBinder => {}
2284 }
2285 }
22862287 (place, curr_mode)
2288}
22892290/// Truncate deref of any reference.
2291x;#[instrument(ret, level = "debug")]2292fn adjust_for_move_closure(
2293mut place: Place<'_>,
2294mut kind: ty::UpvarCapture,
2295) -> (Place<'_>, ty::UpvarCapture) {
2296let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
22972298if let Some(idx) = first_deref {
2299 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2300 }
23012302 (place, ty::UpvarCapture::ByValue)
2303}
23042305/// Truncate deref of any reference.
2306x;#[instrument(ret, level = "debug")]2307fn adjust_for_use_closure(
2308mut place: Place<'_>,
2309mut kind: ty::UpvarCapture,
2310) -> (Place<'_>, ty::UpvarCapture) {
2311let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
23122313if let Some(idx) = first_deref {
2314 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2315 }
23162317 (place, ty::UpvarCapture::ByUse)
2318}
23192320/// Adjust closure capture just that if taking ownership of data, only move data
2321/// from enclosing stack frame.
2322x;#[instrument(ret, level = "debug")]2323fn adjust_for_non_move_closure(
2324mut place: Place<'_>,
2325mut kind: ty::UpvarCapture,
2326) -> (Place<'_>, ty::UpvarCapture) {
2327let contains_deref =
2328 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
23292330match kind {
2331 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2332if let Some(idx) = contains_deref {
2333 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2334 }
2335 }
23362337 ty::UpvarCapture::ByRef(..) => {}
2338 }
23392340 (place, kind)
2341}
23422343fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2344let variable_name = match place.base {
2345 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2346_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Capture_information should only contain upvars"))bug!("Capture_information should only contain upvars"),
2347 };
23482349let mut projections_str = String::new();
2350for (i, item) in place.projections.iter().enumerate() {
2351let proj = match item.kind {
2352 ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
})format!("({a:?}, {b:?})"),
2353 ProjectionKind::Deref => String::from("Deref"),
2354 ProjectionKind::Index => String::from("Index"),
2355 ProjectionKind::Subslice => String::from("Subslice"),
2356 ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2357 ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2358 };
2359if i != 0 {
2360 projections_str.push(',');
2361 }
2362 projections_str.push_str(proj.as_str());
2363 }
23642365::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
projections_str))
})format!("{variable_name}[{projections_str}]")2366}
23672368fn construct_capture_kind_reason_string<'tcx>(
2369 tcx: TyCtxt<'_>,
2370 place: &Place<'tcx>,
2371 capture_info: &ty::CaptureInfo,
2372) -> String {
2373let place_str = construct_place_string(tcx, place);
23742375let capture_kind_str = match capture_info.capture_kind {
2376 ty::UpvarCapture::ByValue => "ByValue".into(),
2377 ty::UpvarCapture::ByUse => "ByUse".into(),
2378 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2379 };
23802381::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")2382}
23832384fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2385let place_str = construct_place_string(tcx, place);
23862387::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} used here", place_str))
})format!("{place_str} used here")2388}
23892390fn construct_capture_info_string<'tcx>(
2391 tcx: TyCtxt<'_>,
2392 place: &Place<'tcx>,
2393 capture_info: &ty::CaptureInfo,
2394) -> String {
2395let place_str = construct_place_string(tcx, place);
23962397let capture_kind_str = match capture_info.capture_kind {
2398 ty::UpvarCapture::ByValue => "ByValue".into(),
2399 ty::UpvarCapture::ByUse => "ByUse".into(),
2400 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2401 };
2402::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
capture_kind_str))
})format!("{place_str} -> {capture_kind_str}")2403}
24042405fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2406tcx.hir_name(var_hir_id)
2407}
24082409#[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(2409u32),
::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))]2410fn should_do_rust_2021_incompatible_closure_captures_analysis(
2411 tcx: TyCtxt<'_>,
2412 closure_id: HirId,
2413) -> bool {
2414if tcx.sess.at_least_rust_2021() {
2415return false;
2416 }
24172418 !tcx.lint_level_spec_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2419 .is_allow()
2420}
24212422/// Return a two string tuple (s1, s2)
2423/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2424/// - s2: Comma separated names of the variables being migrated.
2425fn migration_suggestion_for_2229(
2426 tcx: TyCtxt<'_>,
2427 need_migrations: &[NeededMigration],
2428) -> (String, String) {
2429let need_migrations_variables = need_migrations2430 .iter()
2431 .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2432 .collect::<Vec<_>>();
24332434let migration_ref_concat =
2435need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
24362437let migration_string = if 1 == need_migrations.len() {
2438::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = {0}",
migration_ref_concat))
})format!("let _ = {migration_ref_concat}")2439 } else {
2440::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = ({0})",
migration_ref_concat))
})format!("let _ = ({migration_ref_concat})")2441 };
24422443let migrated_variables_concat =
2444need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", v))
})format!("`{v}`")).collect::<Vec<_>>().join(", ");
24452446 (migration_string, migrated_variables_concat)
2447}
24482449/// Helper function to determine if we need to escalate CaptureKind from
2450/// CaptureInfo A to B and returns the escalated CaptureInfo.
2451/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2452///
2453/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2454/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2455///
2456/// It is the caller's duty to figure out which path_expr_id to use.
2457///
2458/// If both the CaptureKind and Expression are considered to be equivalent,
2459/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2460/// expressions reported back to the user as part of diagnostics based on which appears earlier
2461/// in the closure. This can be achieved simply by calling
2462/// `determine_capture_info(existing_info, current_info)`. This works out because the
2463/// expressions that occur earlier in the closure body than the current expression are processed before.
2464/// Consider the following example
2465/// ```rust,no_run
2466/// struct Point { x: i32, y: i32 }
2467/// let mut p = Point { x: 10, y: 10 };
2468///
2469/// let c = || {
2470/// p.x += 10; // E1
2471/// // ...
2472/// // More code
2473/// // ...
2474/// p.x += 10; // E2
2475/// };
2476/// ```
2477/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2478/// and both have an expression associated, however for diagnostics we prefer reporting
2479/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2480/// would've already handled `E1`, and have an existing capture_information for it.
2481/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2482/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2483fn determine_capture_info(
2484 capture_info_a: ty::CaptureInfo,
2485 capture_info_b: ty::CaptureInfo,
2486) -> ty::CaptureInfo {
2487// If the capture kind is equivalent then, we don't need to escalate and can compare the
2488 // expressions.
2489let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2490 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2491 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2492 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2493 (ty::UpvarCapture::ByValue, _)
2494 | (ty::UpvarCapture::ByUse, _)
2495 | (ty::UpvarCapture::ByRef(_), _) => false,
2496 };
24972498if eq_capture_kind {
2499match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2500 (Some(_), _) | (None, None) => capture_info_a,
2501 (None, Some(_)) => capture_info_b,
2502 }
2503 } else {
2504// We select the CaptureKind which ranks higher based the following priority order:
2505 // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2506match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2507 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2508 | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2509::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")2510 }
2511 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2512 | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2513 | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2514capture_info_a2515 }
2516 (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2517capture_info_b2518 }
2519 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2520match (ref_a, ref_b) {
2521// Take LHS:
2522(BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2523 | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
25242525// Take RHS:
2526(BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2527 | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
25282529 (BorrowKind::Immutable, BorrowKind::Immutable)
2530 | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2531 | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2532::rustc_middle::util::bug::bug_fmt(format_args!("Expected unequal capture kinds"));bug!("Expected unequal capture kinds");
2533 }
2534 }
2535 }
2536 }
2537 }
2538}
25392540/// Truncates `place` to have up to `len` projections.
2541/// `curr_mode` is the current required capture kind for the place.
2542/// Returns the truncated `place` and the updated required capture kind.
2543///
2544/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2545/// contained `Deref` of `&mut`.
2546fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2547 place: &mut Place<'tcx>,
2548 curr_mode: &mut ty::UpvarCapture,
2549 len: usize,
2550) {
2551let 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));
25522553// If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2554 // UniqueImmBorrow
2555 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2556 // we don't need to worry about that case here.
2557match curr_mode {
2558 ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2559for i in len..place.projections.len() {
2560if place.projections[i].kind == ProjectionKind::Deref
2561 && is_mut_ref(place.ty_before_projection(i))
2562 {
2563*curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2564break;
2565 }
2566 }
2567 }
25682569 ty::UpvarCapture::ByRef(..) => {}
2570 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2571 }
25722573place.projections.truncate(len);
2574}
25752576/// Determines the Ancestry relationship of Place A relative to Place B
2577///
2578/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2579/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2580/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2581fn determine_place_ancestry_relation<'tcx>(
2582 place_a: &Place<'tcx>,
2583 place_b: &Place<'tcx>,
2584) -> PlaceAncestryRelation {
2585// If Place A and Place B don't start off from the same root variable, they are divergent.
2586if place_a.base != place_b.base {
2587return PlaceAncestryRelation::Divergent;
2588 }
25892590// Assume of length of projections_a = n
2591let projections_a = &place_a.projections;
25922593// Assume of length of projections_b = m
2594let projections_b = &place_b.projections;
25952596let same_initial_projections =
2597 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
25982599if same_initial_projections {
2600use std::cmp::Ordering;
26012602// First min(n, m) projections are the same
2603 // Select Ancestor/Descendant
2604match projections_b.len().cmp(&projections_a.len()) {
2605 Ordering::Greater => PlaceAncestryRelation::Ancestor,
2606 Ordering::Equal => PlaceAncestryRelation::SamePlace,
2607 Ordering::Less => PlaceAncestryRelation::Descendant,
2608 }
2609 } else {
2610 PlaceAncestryRelation::Divergent2611 }
2612}
26132614/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2615/// borrow checking perspective, allowing us to save us on the size of the capture.
2616///
2617///
2618/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2619/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2620/// rightmost deref of the capture if the deref is applied to a shared ref.
2621///
2622/// Reason we only drop the last deref is because of the following edge case:
2623///
2624/// ```
2625/// # struct A { field_of_a: Box<i32> }
2626/// # struct B {}
2627/// # struct C<'a>(&'a i32);
2628/// struct MyStruct<'a> {
2629/// a: &'static A,
2630/// b: B,
2631/// c: C<'a>,
2632/// }
2633///
2634/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2635/// || drop(&*m.a.field_of_a)
2636/// // Here we really do want to capture `*m.a` because that outlives `'static`
2637///
2638/// // If we capture `m`, then the closure no longer outlives `'static`
2639/// // it is constrained to `'a`
2640/// }
2641/// ```
2642x;#[instrument(ret, level = "debug")]2643fn truncate_capture_for_optimization(
2644mut place: Place<'_>,
2645mut curr_mode: ty::UpvarCapture,
2646) -> (Place<'_>, ty::UpvarCapture) {
2647let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
26482649// Find the rightmost deref (if any). All the projections that come after this
2650 // are fields or other "in-place pointer adjustments"; these refer therefore to
2651 // data owned by whatever pointer is being dereferenced here.
2652let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
26532654match idx {
2655// If that pointer is a shared reference, then we don't need those fields.
2656Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2657 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2658 }
2659None | Some(_) => {}
2660 }
26612662 (place, curr_mode)
2663}
26642665/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2666/// `span` is the span of the closure.
2667fn enable_precise_capture(span: Span) -> bool {
2668// We use span here to ensure that if the closure was generated by a macro with a different
2669 // edition.
2670span.at_least_rust_2021()
2671}