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::error_reporting::InferCtxtErrorExt as _;
53use rustc_trait_selection::infer::InferCtxtExt;
54use rustc_trait_selection::solve;
55use tracing::{debug, instrument};
5657use super::FnCtxt;
58use crate::expr_use_visitoras euv;
5960/// Describe the relationship between the paths of two places
61/// eg:
62/// - `foo` is ancestor of `foo.bar.baz`
63/// - `foo.bar.baz` is an descendant of `foo.bar`
64/// - `foo.bar` and `foo.baz` are divergent
65enum PlaceAncestryRelation {
66 Ancestor,
67 Descendant,
68 SamePlace,
69 Divergent,
70}
7172/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
73/// during capture analysis. Information in this map feeds into the minimum capture
74/// analysis pass.
75type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
7677impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
78pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
79InferBorrowKindVisitor { fcx: self }.visit_body(body);
8081// it's our job to process these.
82if !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());
83 }
84}
8586/// Intermediate format to store the hir_id pointing to the use that resulted in the
87/// corresponding place being captured and a String which contains the captured value's
88/// name (i.e: a.b.c)
89#[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)]
90enum UpvarMigrationInfo {
91/// We previously captured all of `x`, but now we capture some sub-path.
92CapturingPrecise { source_expr: Option<HirId>, var_name: String },
93 CapturingNothing {
94// where the variable appears in the closure (but is not captured)
95use_span: Span,
96 },
97}
9899/// Reasons that we might issue a migration warning.
100#[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> {
match ::core::cmp::PartialOrd::partial_cmp(&self.auto_traits,
&other.auto_traits) {
::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
::core::cmp::PartialOrd::partial_cmp(&self.drop_order,
&other.drop_order),
cmp => cmp,
}
}
}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)]
101struct MigrationWarningReason {
102/// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
103 /// in this vec, but now we don't.
104auto_traits: Vec<&'static str>,
105106/// When we used to capture `x` in its entirety, we would execute some destructors
107 /// at a different time.
108drop_order: bool,
109}
110111impl MigrationWarningReason {
112fn migration_message(&self) -> String {
113let base = "changes to closure capture in Rust 2021 will affect";
114if !self.auto_traits.is_empty() && self.drop_order {
115::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")116 } else if self.drop_order {
117::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} drop order", base))
})format!("{base} drop order")118 } else {
119::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} which traits the closure implements",
base))
})format!("{base} which traits the closure implements")120 }
121 }
122}
123124/// Intermediate format to store information needed to generate a note in the migration lint.
125struct MigrationLintNote {
126 captures_info: UpvarMigrationInfo,
127128/// reasons why migration is needed for this capture
129reason: MigrationWarningReason,
130}
131132/// Intermediate format to store the hir id of the root variable and a HashSet containing
133/// information on why the root variable should be fully captured
134struct NeededMigration {
135 var_hir_id: HirId,
136 diagnostics_info: Vec<MigrationLintNote>,
137}
138139struct InferBorrowKindVisitor<'a, 'tcx> {
140 fcx: &'a FnCtxt<'a, 'tcx>,
141}
142143impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
144fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
145match expr.kind {
146 hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
147let body = self.fcx.tcx.hir_body(body_id);
148self.visit_body(body);
149self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
150 }
151_ => {}
152 }
153154 intravisit::walk_expr(self, expr);
155 }
156157fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
158let body = self.fcx.tcx.hir_body(c.body);
159self.visit_body(body);
160 }
161}
162163impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
164/// Analysis starting point.
165#[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(165u32),
::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);
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:303",
"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(303u32),
::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:332",
"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(332u32),
::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:488",
"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(488u32),
::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")]166fn analyze_closure(
167&self,
168 closure_hir_id: HirId,
169 span: Span,
170 body_id: hir::BodyId,
171 body: &'tcx hir::Body<'tcx>,
172mut capture_clause: hir::CaptureBy,
173 ) {
174// Extract the type of the closure.
175let ty = self.node_ty(closure_hir_id);
176let (closure_def_id, args, infer_kind) = match *ty.kind() {
177 ty::Closure(def_id, args) => {
178 (def_id, UpvarArgs::Closure(args), self.closure_kind(ty).is_none())
179 }
180 ty::CoroutineClosure(def_id, args) => {
181 (def_id, UpvarArgs::CoroutineClosure(args), self.closure_kind(ty).is_none())
182 }
183 ty::Coroutine(def_id, args) => (def_id, UpvarArgs::Coroutine(args), false),
184 ty::Error(_) => {
185// #51714: skip analysis when we have already encountered type errors
186return;
187 }
188_ => {
189span_bug!(
190 span,
191"type of closure expr {:?} is not a closure {:?}",
192 closure_hir_id,
193 ty
194 );
195 }
196 };
197let args = self.resolve_vars_if_possible(args);
198let closure_def_id = closure_def_id.expect_local();
199200assert_eq!(self.tcx.hir_body_owner_def_id(body.id()), closure_def_id);
201202let closure_fcx = FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id);
203204let mut delegate = InferBorrowKind {
205 fcx: &closure_fcx,
206 closure_def_id,
207 capture_information: Default::default(),
208 fake_reads: Default::default(),
209 };
210211let _ = euv::ExprUseVisitor::new(&closure_fcx, &mut delegate).consume_body(body);
212213// There are several curious situations with coroutine-closures where
214 // analysis is too aggressive with borrows when the coroutine-closure is
215 // marked `move`. Specifically:
216 //
217 // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
218 // inference, then it's still possible that we try to borrow upvars from
219 // the coroutine-closure because they are not used by the coroutine body
220 // in a way that forces a move. See the test:
221 // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
222 //
223 // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
224 // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
225 // would force the closure to `FnOnce`.
226 // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
227 //
228 // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
229 // coroutine bodies can't borrow from their parent closure. To fix this,
230 // we force the inner coroutine to also be `move`. This only matters for
231 // coroutine-closures that are `move` since otherwise they themselves will
232 // be borrowing from the outer environment, so there's no self-borrows occurring.
233if let UpvarArgs::Coroutine(..) = args
234 && let hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) =
235self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
236 && let parent_hir_id =
237self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
238 && let parent_ty = self.node_ty(parent_hir_id)
239 && let hir::CaptureBy::Value { move_kw } =
240self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
241 {
242// (1.) Closure signature inference forced this closure to `FnOnce`.
243if let Some(ty::ClosureKind::FnOnce) = self.closure_kind(parent_ty) {
244 capture_clause = hir::CaptureBy::Value { move_kw };
245 }
246// (2.) The way that the closure uses its upvars means it's `FnOnce`.
247else if self.coroutine_body_consumes_upvars(closure_def_id, body) {
248 capture_clause = hir::CaptureBy::Value { move_kw };
249 }
250 }
251252// As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
253 // to `ByRef` for the `async {}` block internal to async fns/closure. This means
254 // that we would *not* be moving all of the parameters into the async block in all cases.
255 // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
256 // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
257 //
258 // We force all of these arguments to be captured by move before we do expr use analysis.
259 //
260 // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
261 // moving all of the `LocalSource::AsyncFn` locals here.
262if let Some(hir::CoroutineKind::Desugared(
263_,
264 hir::CoroutineSource::Fn | hir::CoroutineSource::Closure,
265 )) = self.tcx.coroutine_kind(closure_def_id)
266 {
267let hir::ExprKind::Block(block, _) = body.value.kind else {
268bug!();
269 };
270for stmt in block.stmts {
271let hir::StmtKind::Let(hir::LetStmt {
272 init: Some(init),
273 source: hir::LocalSource::AsyncFn,
274 pat,
275 ..
276 }) = stmt.kind
277else {
278bug!();
279 };
280let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), _, _, _) = pat.kind
281else {
282// Complex pattern, skip the non-upvar local.
283continue;
284 };
285let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = init.kind else {
286bug!();
287 };
288let hir::def::Res::Local(local_id) = path.res else {
289bug!();
290 };
291let place = closure_fcx.place_for_root_variable(closure_def_id, local_id);
292 delegate.capture_information.push((
293 place,
294 ty::CaptureInfo {
295 capture_kind_expr_id: Some(init.hir_id),
296 path_expr_id: Some(init.hir_id),
297 capture_kind: UpvarCapture::ByValue,
298 },
299 ));
300 }
301 }
302303debug!(
304"For closure={:?}, capture_information={:#?}",
305 closure_def_id, delegate.capture_information
306 );
307308self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
309310let (capture_information, closure_kind, origin) = self
311.process_collected_capture_information(capture_clause, &delegate.capture_information);
312313self.compute_min_captures(closure_def_id, capture_information, span);
314315let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
316317if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
318self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
319 }
320321let after_feature_tys = self.final_upvar_tys(closure_def_id);
322323// We now fake capture information for all variables that are mentioned within the closure
324 // We do this after handling migrations so that min_captures computes before
325if !enable_precise_capture(span) {
326let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
327328if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
329for var_hir_id in upvars.keys() {
330let place = closure_fcx.place_for_root_variable(closure_def_id, *var_hir_id);
331332debug!("seed place {:?}", place);
333334let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
335let fake_info = ty::CaptureInfo {
336 capture_kind_expr_id: None,
337 path_expr_id: None,
338 capture_kind,
339 };
340341 capture_information.push((place, fake_info));
342 }
343 }
344345// This will update the min captures based on this new fake information.
346self.compute_min_captures(closure_def_id, capture_information, span);
347 }
348349let before_feature_tys = self.final_upvar_tys(closure_def_id);
350351if infer_kind {
352// Unify the (as yet unbound) type variable in the closure
353 // args with the kind we inferred.
354let closure_kind_ty = match args {
355 UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
356 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
357 UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
358 };
359self.demand_eqtype(
360 span,
361 Ty::from_closure_kind(self.tcx, closure_kind),
362 closure_kind_ty,
363 );
364365// If we have an origin, store it.
366if let Some(mut origin) = origin {
367if !enable_precise_capture(span) {
368// Without precise captures, we just capture the base and ignore
369 // the projections.
370origin.1.projections.clear()
371 }
372373self.typeck_results
374 .borrow_mut()
375 .closure_kind_origins_mut()
376 .insert(closure_hir_id, origin);
377 }
378 }
379380// For coroutine-closures, we additionally must compute the
381 // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
382 // version of the coroutine-closure's output coroutine.
383if let UpvarArgs::CoroutineClosure(args) = args
384 && !args.references_error()
385 {
386let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
387self.tcx,
388 ty::INNERMOST,
389 ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::ClosureEnv },
390 );
391392let num_args = args
393 .as_coroutine_closure()
394 .coroutine_closure_sig()
395 .skip_binder()
396 .tupled_inputs_ty
397 .tuple_fields()
398 .len();
399let typeck_results = self.typeck_results.borrow();
400401let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
402self.tcx,
403 ty::analyze_coroutine_closure_captures(
404 typeck_results.closure_min_captures_flattened(closure_def_id),
405 typeck_results
406 .closure_min_captures_flattened(
407self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
408 )
409// Skip the captures that are just moving the closure's args
410 // into the coroutine. These are always by move, and we append
411 // those later in the `CoroutineClosureSignature` helper functions.
412.skip(num_args),
413 |(_, parent_capture), (_, child_capture)| {
414// This is subtle. See documentation on function.
415let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
416 parent_capture,
417 child_capture,
418 );
419420let upvar_ty = child_capture.place.ty();
421let capture = child_capture.info.capture_kind;
422// Not all upvars are captured by ref, so use
423 // `apply_capture_kind_on_capture_ty` to ensure that we
424 // compute the right captured type.
425apply_capture_kind_on_capture_ty(
426self.tcx,
427 upvar_ty,
428 capture,
429if needs_ref {
430 closure_env_region
431 } else {
432self.tcx.lifetimes.re_erased
433 },
434 )
435 },
436 ),
437 );
438let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
439self.tcx,
440 ty::Binder::bind_with_vars(
441self.tcx.mk_fn_sig_safe_rust_abi([], tupled_upvars_ty_for_borrow),
442self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
443 ty::BoundRegionKind::ClosureEnv,
444 )]),
445 ),
446 );
447self.demand_eqtype(
448 span,
449 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
450 coroutine_captures_by_ref_ty,
451 );
452453// Additionally, we can now constrain the coroutine's kind type.
454 //
455 // We only do this if `infer_kind`, because if we have constrained
456 // the kind from closure signature inference, the kind inferred
457 // for the inner coroutine may actually be more restrictive.
458if infer_kind {
459let ty::Coroutine(_, coroutine_args) =
460*self.typeck_results.borrow().expr_ty(body.value).kind()
461else {
462bug!();
463 };
464self.demand_eqtype(
465 span,
466 coroutine_args.as_coroutine().kind_ty(),
467 Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
468 );
469 }
470 }
471472self.log_closure_min_capture_info(closure_def_id, span);
473474// Now that we've analyzed the closure, we know how each
475 // variable is borrowed, and we know what traits the closure
476 // implements (Fn vs FnMut etc). We now have some updates to do
477 // with that information.
478 //
479 // Note that no closure type C may have an upvar of type C
480 // (though it may reference itself via a trait object). This
481 // results from the desugaring of closures to a struct like
482 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
483 // C, then the type would have infinite size (and the
484 // inference algorithm will reject it).
485486 // Equate the type variables for the upvars with the actual types.
487let final_upvar_tys = self.final_upvar_tys(closure_def_id);
488debug!(?closure_hir_id, ?args, ?final_upvar_tys);
489490if self.tcx.features().unsized_fn_params() {
491for capture in
492self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
493 {
494if let UpvarCapture::ByValue = capture.info.capture_kind {
495self.require_type_is_sized(
496 capture.place.ty(),
497 capture.get_path_span(self.tcx),
498 ObligationCauseCode::SizedClosureCapture(closure_def_id),
499 );
500 }
501 }
502 }
503504// Build a tuple (U0..Un) of the final upvar types U0..Un
505 // and unify the upvar tuple type in the closure with it:
506let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
507self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
508509let fake_reads = delegate.fake_reads;
510511self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
512513if self.tcx.sess.opts.unstable_opts.profile_closures {
514self.typeck_results.borrow_mut().closure_size_eval.insert(
515 closure_def_id,
516 ClosureSizeProfileData {
517 before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
518 after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
519 },
520 );
521 }
522523// If we are also inferred the closure kind here,
524 // process any deferred resolutions.
525let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
526for deferred_call_resolution in deferred_call_resolutions {
527 deferred_call_resolution.resolve(&FnCtxt::new(self, self.param_env, closure_def_id));
528 }
529 }
530531/// Determines whether the body of the coroutine uses its upvars in a way that
532 /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
533 /// In a more detailed comment above, we care whether this happens, since if
534 /// this happens, we want to force the coroutine to move all of the upvars it
535 /// would've borrowed from the parent coroutine-closure.
536 ///
537 /// This only really makes sense to be called on the child coroutine of a
538 /// coroutine-closure.
539fn coroutine_body_consumes_upvars(
540&self,
541 coroutine_def_id: LocalDefId,
542 body: &'tcx hir::Body<'tcx>,
543 ) -> bool {
544// This block contains argument capturing details. Since arguments
545 // aren't upvars, we do not care about them for determining if the
546 // coroutine body actually consumes its upvars.
547let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
548else {
549::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
550 };
551// Specifically, we only care about the *real* body of the coroutine.
552 // We skip out into the drop-temps within the block of the body in order
553 // to skip over the args of the desugaring.
554let hir::ExprKind::DropTemps(body) = body.kind else {
555::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
556 };
557558let coroutine_fcx =
559FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id);
560561let mut delegate = InferBorrowKind {
562 fcx: &coroutine_fcx,
563 closure_def_id: coroutine_def_id,
564 capture_information: Default::default(),
565 fake_reads: Default::default(),
566 };
567568let _ = euv::ExprUseVisitor::new(&coroutine_fcx, &mut delegate).consume_expr(body);
569570let (_, kind, _) = self.process_collected_capture_information(
571 hir::CaptureBy::Ref,
572&delegate.capture_information,
573 );
574575#[allow(non_exhaustive_omitted_patterns)] match kind {
ty::ClosureKind::FnOnce => true,
_ => false,
}matches!(kind, ty::ClosureKind::FnOnce)576 }
577578// Returns a list of `Ty`s for each upvar.
579fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
580self.typeck_results
581 .borrow()
582 .closure_min_captures_flattened(closure_id)
583 .map(|captured_place| {
584let upvar_ty = captured_place.place.ty();
585let capture = captured_place.info.capture_kind;
586587{
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:587",
"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(587u32),
::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);
588589apply_capture_kind_on_capture_ty(
590self.tcx,
591upvar_ty,
592capture,
593self.tcx.lifetimes.re_erased,
594 )
595 })
596 .collect()
597 }
598599/// Adjusts the closure capture information to ensure that the operations aren't unsafe,
600 /// and that the path can be captured with required capture kind (depending on use in closure,
601 /// move closure etc.)
602 ///
603 /// Returns the set of adjusted information along with the inferred closure kind and span
604 /// associated with the closure kind inference.
605 ///
606 /// Note that we *always* infer a minimal kind, even if
607 /// we don't always *use* that in the final result (i.e., sometimes
608 /// we've taken the closure kind from the expectations instead, and
609 /// for coroutines we don't even implement the closure traits
610 /// really).
611 ///
612 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
613 /// contains a `Some()` with the `Place` that caused us to do so.
614fn process_collected_capture_information(
615&self,
616 capture_clause: hir::CaptureBy,
617 capture_information: &InferredCaptureInformation<'tcx>,
618 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
619let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
620let mut origin: Option<(Span, Place<'tcx>)> = None;
621622let processed = capture_information623 .iter()
624 .cloned()
625 .map(|(place, mut capture_info)| {
626// Apply rules for safety before inferring closure kind
627let (place, capture_kind) =
628restrict_capture_precision(place, capture_info.capture_kind);
629630let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
631632let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
633self.tcx.hir_span(usage_expr)
634 } else {
635::core::panicking::panic("internal error: entered unreachable code")unreachable!()636 };
637638let updated = match capture_kind {
639 ty::UpvarCapture::ByValue => match closure_kind {
640 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
641 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
642 }
643// If closure is already FnOnce, don't update
644ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
645 },
646647 ty::UpvarCapture::ByRef(
648 ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
649 ) => {
650match closure_kind {
651 ty::ClosureKind::Fn => {
652 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
653 }
654// Don't update the origin
655ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
656 (closure_kind, origin.take())
657 }
658 }
659 }
660661_ => (closure_kind, origin.take()),
662 };
663664closure_kind = updated.0;
665origin = updated.1;
666667let (place, capture_kind) = match capture_clause {
668 hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
669 hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
670 hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
671 };
672673// This restriction needs to be applied after we have handled adjustments for `move`
674 // closures. We want to make sure any adjustment that might make us move the place into
675 // the closure gets handled.
676let (place, capture_kind) =
677restrict_precision_for_drop_types(self, place, capture_kind);
678679capture_info.capture_kind = capture_kind;
680 (place, capture_info)
681 })
682 .collect();
683684 (processed, closure_kind, origin)
685 }
686687/// Analyzes the information collected by `InferBorrowKind` to compute the min number of
688 /// Places (and corresponding capture kind) that we need to keep track of to support all
689 /// the required captured paths.
690 ///
691 ///
692 /// Note: If this function is called multiple times for the same closure, it will update
693 /// the existing min_capture map that is stored in TypeckResults.
694 ///
695 /// Eg:
696 /// ```
697 /// #[derive(Debug)]
698 /// struct Point { x: i32, y: i32 }
699 ///
700 /// let s = String::from("s"); // hir_id_s
701 /// let mut p = Point { x: 2, y: -2 }; // his_id_p
702 /// let c = || {
703 /// println!("{s:?}"); // L1
704 /// p.x += 10; // L2
705 /// println!("{}" , p.y); // L3
706 /// println!("{p:?}"); // L4
707 /// drop(s); // L5
708 /// };
709 /// ```
710 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
711 /// the lines L1..5 respectively.
712 ///
713 /// InferBorrowKind results in a structure like this:
714 ///
715 /// ```ignore (illustrative)
716 /// {
717 /// Place(base: hir_id_s, projections: [], ....) -> {
718 /// capture_kind_expr: hir_id_L5,
719 /// path_expr_id: hir_id_L5,
720 /// capture_kind: ByValue
721 /// },
722 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
723 /// capture_kind_expr: hir_id_L2,
724 /// path_expr_id: hir_id_L2,
725 /// capture_kind: ByValue
726 /// },
727 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
728 /// capture_kind_expr: hir_id_L3,
729 /// path_expr_id: hir_id_L3,
730 /// capture_kind: ByValue
731 /// },
732 /// Place(base: hir_id_p, projections: [], ...) -> {
733 /// capture_kind_expr: hir_id_L4,
734 /// path_expr_id: hir_id_L4,
735 /// capture_kind: ByValue
736 /// },
737 /// }
738 /// ```
739 ///
740 /// After the min capture analysis, we get:
741 /// ```ignore (illustrative)
742 /// {
743 /// hir_id_s -> [
744 /// Place(base: hir_id_s, projections: [], ....) -> {
745 /// capture_kind_expr: hir_id_L5,
746 /// path_expr_id: hir_id_L5,
747 /// capture_kind: ByValue
748 /// },
749 /// ],
750 /// hir_id_p -> [
751 /// Place(base: hir_id_p, projections: [], ...) -> {
752 /// capture_kind_expr: hir_id_L2,
753 /// path_expr_id: hir_id_L4,
754 /// capture_kind: ByValue
755 /// },
756 /// ],
757 /// }
758 /// ```
759#[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(759u32),
::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:884",
"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(884u32),
::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:945",
"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(945u32),
::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))]760fn compute_min_captures(
761&self,
762 closure_def_id: LocalDefId,
763 capture_information: InferredCaptureInformation<'tcx>,
764 closure_span: Span,
765 ) {
766if capture_information.is_empty() {
767return;
768 }
769770let mut typeck_results = self.typeck_results.borrow_mut();
771772let mut root_var_min_capture_list =
773 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
774775for (mut place, capture_info) in capture_information.into_iter() {
776let var_hir_id = match place.base {
777 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
778 base => bug!("Expected upvar, found={:?}", base),
779 };
780let var_ident = self.tcx.hir_ident(var_hir_id);
781782let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
783let mutability = self.determine_capture_mutability(&typeck_results, &place);
784let min_cap_list =
785vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
786 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
787continue;
788 };
789790// Go through each entry in the current list of min_captures
791 // - if ancestor is found, update its capture kind to account for current place's
792 // capture information.
793 //
794 // - if descendant is found, remove it from the list, and update the current place's
795 // capture information to account for the descendant's capture kind.
796 //
797 // We can never be in a case where the list contains both an ancestor and a descendant
798 // Also there can only be ancestor but in case of descendants there might be
799 // multiple.
800801let mut descendant_found = false;
802let mut updated_capture_info = capture_info;
803 min_cap_list.retain(|possible_descendant| {
804match determine_place_ancestry_relation(&place, &possible_descendant.place) {
805// current place is ancestor of possible_descendant
806PlaceAncestryRelation::Ancestor => {
807 descendant_found = true;
808809let mut possible_descendant = possible_descendant.clone();
810let backup_path_expr_id = updated_capture_info.path_expr_id;
811812// Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
813 // possible change in capture mode.
814truncate_place_to_len_and_update_capture_kind(
815&mut possible_descendant.place,
816&mut possible_descendant.info.capture_kind,
817 place.projections.len(),
818 );
819820 updated_capture_info =
821 determine_capture_info(updated_capture_info, possible_descendant.info);
822823// we need to keep the ancestor's `path_expr_id`
824updated_capture_info.path_expr_id = backup_path_expr_id;
825false
826}
827828_ => true,
829 }
830 });
831832let mut ancestor_found = false;
833if !descendant_found {
834for possible_ancestor in min_cap_list.iter_mut() {
835match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
836 PlaceAncestryRelation::SamePlace => {
837 ancestor_found = true;
838 possible_ancestor.info = determine_capture_info(
839 possible_ancestor.info,
840 updated_capture_info,
841 );
842843// Only one related place will be in the list.
844break;
845 }
846// current place is descendant of possible_ancestor
847PlaceAncestryRelation::Descendant => {
848 ancestor_found = true;
849let backup_path_expr_id = possible_ancestor.info.path_expr_id;
850851// Truncate the descendant (current place) to be same as the ancestor to handle any
852 // possible change in capture mode.
853truncate_place_to_len_and_update_capture_kind(
854&mut place,
855&mut updated_capture_info.capture_kind,
856 possible_ancestor.place.projections.len(),
857 );
858859 possible_ancestor.info = determine_capture_info(
860 possible_ancestor.info,
861 updated_capture_info,
862 );
863864// we need to keep the ancestor's `path_expr_id`
865possible_ancestor.info.path_expr_id = backup_path_expr_id;
866867// Only one related place will be in the list.
868break;
869 }
870_ => {}
871 }
872 }
873 }
874875// Only need to insert when we don't have an ancestor in the existing min capture list
876if !ancestor_found {
877let mutability = self.determine_capture_mutability(&typeck_results, &place);
878let captured_place =
879 ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
880 min_cap_list.push(captured_place);
881 }
882 }
883884debug!(
885"For closure={:?}, min_captures before sorting={:?}",
886 closure_def_id, root_var_min_capture_list
887 );
888889// Now that we have the minimized list of captures, sort the captures by field id.
890 // This causes the closure to capture the upvars in the same order as the fields are
891 // declared which is also the drop order. Thus, in situations where we capture all the
892 // fields of some type, the observable drop order will remain the same as it previously
893 // was even though we're dropping each capture individually.
894 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
895 // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
896for (_, captures) in &mut root_var_min_capture_list {
897 captures.sort_by(|capture1, capture2| {
898fn is_field<'a>(p: &&Projection<'a>) -> bool {
899match p.kind {
900 ProjectionKind::Field(_, _) => true,
901 ProjectionKind::Deref
902 | ProjectionKind::OpaqueCast
903 | ProjectionKind::UnwrapUnsafeBinder => false,
904 p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
905bug!("ProjectionKind {:?} was unexpected", p)
906 }
907 }
908 }
909910// Need to sort only by Field projections, so filter away others.
911 // A previous implementation considered other projection types too
912 // but that caused ICE #118144
913let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
914let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
915916for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
917// We do not need to look at the `Projection.ty` fields here because at each
918 // step of the iteration, the projections will either be the same and therefore
919 // the types must be as well or the current projection will be different and
920 // we will return the result of comparing the field indexes.
921match (p1.kind, p2.kind) {
922 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
923// Compare only if paths are different.
924 // Otherwise continue to the next iteration
925if i1 != i2 {
926return i1.cmp(&i2);
927 }
928 }
929// Given the filter above, this arm should never be hit
930(l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
931 }
932 }
933934self.dcx().span_delayed_bug(
935 closure_span,
936format!(
937"two identical projections: ({:?}, {:?})",
938 capture1.place.projections, capture2.place.projections
939 ),
940 );
941 std::cmp::Ordering::Equal
942 });
943 }
944945debug!(
946"For closure={:?}, min_captures after sorting={:#?}",
947 closure_def_id, root_var_min_capture_list
948 );
949 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
950 }
951952/// Perform the migration analysis for RFC 2229, and emit lint
953 /// `disjoint_capture_drop_reorder` if needed.
954fn perform_2229_migration_analysis(
955&self,
956 closure_def_id: LocalDefId,
957 body_id: hir::BodyId,
958 capture_clause: hir::CaptureBy,
959 span: Span,
960 ) {
961struct MigrationLint<'a, 'tcx> {
962 closure_def_id: LocalDefId,
963 this: &'a FnCtxt<'a, 'tcx>,
964 body_id: hir::BodyId,
965 need_migrations: Vec<NeededMigration>,
966 migration_message: String,
967 }
968969impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for MigrationLint<'b, 'tcx> {
970fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
971let Self { closure_def_id, this, body_id, need_migrations, migration_message } =
972self;
973let mut lint = Diag::new(dcx, level, migration_message);
974975let (migration_string, migrated_variables_concat) =
976migration_suggestion_for_2229(this.tcx, &need_migrations);
977978let closure_hir_id = this.tcx.local_def_id_to_hir_id(closure_def_id);
979let closure_head_span = this.tcx.def_span(closure_def_id);
980981for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
982// Labels all the usage of the captured variable and why they are responsible
983 // for migration being needed
984for lint_note in diagnostics_info.iter() {
985match &lint_note.captures_info {
986 UpvarMigrationInfo::CapturingPrecise {
987 source_expr: Some(capture_expr_id),
988 var_name: captured_name,
989 } => {
990let cause_span = this.tcx.hir_span(*capture_expr_id);
991 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 `{}`",
992 this.tcx.hir_name(*var_hir_id),
993 captured_name,
994 ));
995 }
996 UpvarMigrationInfo::CapturingNothing { use_span } => {
997 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",
998 this.tcx.hir_name(*var_hir_id),
999 ));
1000 }
10011002_ => {}
1003 }
10041005// Add a label pointing to where a captured variable affected by drop order
1006 // is dropped
1007if lint_note.reason.drop_order {
1008let drop_location_span = drop_location_span(this.tcx, closure_hir_id);
10091010match &lint_note.captures_info {
1011 UpvarMigrationInfo::CapturingPrecise {
1012 var_name: captured_name,
1013 ..
1014 } => {
1015 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",
1016 this.tcx.hir_name(*var_hir_id),
1017 captured_name,
1018 ));
1019 }
1020 UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1021 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",
1022 v = this.tcx.hir_name(*var_hir_id),
1023 ));
1024 }
1025 }
1026 }
10271028// Add a label explaining why a closure no longer implements a trait
1029for &missing_trait in &lint_note.reason.auto_traits {
1030// not capturing something anymore cannot cause a trait to fail to be implemented:
1031match &lint_note.captures_info {
1032 UpvarMigrationInfo::CapturingPrecise {
1033 var_name: captured_name,
1034 ..
1035 } => {
1036let var_name = this.tcx.hir_name(*var_hir_id);
1037 lint.span_label(
1038 closure_head_span,
1039::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!(
1040"\
1041 in Rust 2018, this closure implements {missing_trait} \
1042 as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1043 this closure will no longer implement {missing_trait} \
1044 because `{var_name}` is not fully captured \
1045 and `{captured_name}` does not implement {missing_trait}"
1046),
1047 );
1048 }
10491050// Cannot happen: if we don't capture a variable, we impl strictly more traits
1051 UpvarMigrationInfo::CapturingNothing { use_span } => ::rustc_middle::util::bug::span_bug_fmt(*use_span,
format_args!("missing trait from not capturing something"))span_bug!(
1052*use_span,
1053"missing trait from not capturing something"
1054),
1055 }
1056 }
1057 }
1058 }
10591060let 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!(
1061"add a dummy let to cause {migrated_variables_concat} to be fully captured"
1062);
10631064let closure_span = this.tcx.hir_span_with_body(closure_hir_id);
1065let mut closure_body_span = {
1066// If the body was entirely expanded from a macro
1067 // invocation, i.e. the body is not contained inside the
1068 // closure span, then we walk up the expansion until we
1069 // find the span before the expansion.
1070let s = this.tcx.hir_span_with_body(body_id.hir_id);
1071s.find_ancestor_inside(closure_span).unwrap_or(s)
1072 };
10731074if let Ok(mut s) = this.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1075if s.starts_with('$') {
1076// Looks like a macro fragment. Try to find the real block.
1077if let hir::Node::Expr(&hir::Expr {
1078 kind: hir::ExprKind::Block(block, ..),
1079 ..
1080 }) = this.tcx.hir_node(body_id.hir_id)
1081 {
1082// If the body is a block (with `{..}`), we use the span of that block.
1083 // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1084 // Since we know it's a block, we know we can insert the `let _ = ..` without
1085 // breaking the macro syntax.
1086if let Ok(snippet) =
1087this.tcx.sess.source_map().span_to_snippet(block.span)
1088 {
1089closure_body_span = block.span;
1090s = snippet;
1091 }
1092 }
1093 }
10941095let mut lines = s.lines();
1096let line1 = lines.next().unwrap_or_default();
10971098if line1.trim_end() == "{" {
1099// This is a multi-line closure with just a `{` on the first line,
1100 // so we put the `let` on its own line.
1101 // We take the indentation from the next non-empty line.
1102let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1103let indent =
1104line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1105lint.span_suggestion(
1106closure_body_span1107 .with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len()))
1108 .shrink_to_lo(),
1109diagnostic_msg,
1110::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}{1};", indent,
migration_string))
})format!("\n{indent}{migration_string};"),
1111 Applicability::MachineApplicable,
1112 );
1113 } else if line1.starts_with('{') {
1114// This is a closure with its body wrapped in
1115 // braces, but with more than just the opening
1116 // brace on the first line. We put the `let`
1117 // directly after the `{`.
1118lint.span_suggestion(
1119closure_body_span1120 .with_lo(closure_body_span.lo() + BytePos(1))
1121 .shrink_to_lo(),
1122diagnostic_msg,
1123::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0};", migration_string))
})format!(" {migration_string};"),
1124 Applicability::MachineApplicable,
1125 );
1126 } else {
1127// This is a closure without braces around the body.
1128 // We add braces to add the `let` before the body.
1129lint.multipart_suggestion(
1130diagnostic_msg,
1131::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![
1132 (
1133 closure_body_span.shrink_to_lo(),
1134format!("{{ {migration_string}; "),
1135 ),
1136 (closure_body_span.shrink_to_hi(), " }".to_string()),
1137 ],
1138 Applicability::MachineApplicable,
1139 );
1140 }
1141 } else {
1142lint.span_suggestion(
1143closure_span,
1144diagnostic_msg,
1145migration_string,
1146 Applicability::HasPlaceholders,
1147 );
1148 }
1149lint1150 }
1151 }
11521153let (need_migrations, reasons) = self.compute_2229_migrations(
1154closure_def_id,
1155span,
1156capture_clause,
1157self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
1158 );
11591160if !need_migrations.is_empty() {
1161self.tcx.emit_node_span_lint(
1162 lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
1163self.tcx.local_def_id_to_hir_id(closure_def_id),
1164self.tcx.def_span(closure_def_id),
1165MigrationLint {
1166 this: self,
1167 migration_message: reasons.migration_message(),
1168closure_def_id,
1169body_id,
1170need_migrations,
1171 },
1172 );
1173 }
1174 }
1175fn normalize_capture_place(&self, span: Span, place: Place<'tcx>) -> Place<'tcx> {
1176let mut place = self.resolve_vars_if_possible(place);
11771178// In the new solver, types in HIR `Place`s can contain unnormalized aliases,
1179 // which can ICE later (e.g. when projecting fields for diagnostics).
1180if self.next_trait_solver() {
1181let cause = self.misc(span);
1182let at = self.at(&cause, self.param_env);
1183match solve::deeply_normalize_with_skipped_universes_and_ambiguous_coroutine_goals(
1184at,
1185Unnormalized::new_wip(place.clone()),
1186::alloc::vec::Vec::new()vec![],
1187 ) {
1188Ok((normalized, goals)) => {
1189if !goals.is_empty() {
1190let mut typeck_results = self.typeck_results.borrow_mut();
1191typeck_results.coroutine_stalled_predicates.extend(
1192goals1193 .into_iter()
1194// FIXME: throwing away the param-env :(
1195.map(|goal| (goal.predicate, self.misc(span))),
1196 );
1197 }
1198normalized1199 }
1200Err(errors) => {
1201let guar = self.infcx.err_ctxt().report_fulfillment_errors(errors);
1202place.base_ty = Ty::new_error(self.tcx, guar);
1203for proj in &mut place.projections {
1204 proj.ty = Ty::new_error(self.tcx, guar);
1205 }
1206place1207 }
1208 }
1209 } else {
1210// For the old solver we can rely on `normalize` to eagerly normalize aliases.
1211self.normalize(span, Unnormalized::new_wip(place))
1212 }
1213 }
12141215/// Combines all the reasons for 2229 migrations
1216fn compute_2229_migrations_reasons(
1217&self,
1218 auto_trait_reasons: UnordSet<&'static str>,
1219 drop_order: bool,
1220 ) -> MigrationWarningReason {
1221MigrationWarningReason {
1222 auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1223drop_order,
1224 }
1225 }
12261227/// Figures out the list of root variables (and their types) that aren't completely
1228 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1229 /// differ between the root variable and the captured paths.
1230 ///
1231 /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1232 /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1233fn compute_2229_migrations_for_trait(
1234&self,
1235 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1236 var_hir_id: HirId,
1237 closure_clause: hir::CaptureBy,
1238 ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1239let auto_traits_def_id = [
1240self.tcx.lang_items().clone_trait(),
1241self.tcx.lang_items().sync_trait(),
1242self.tcx.get_diagnostic_item(sym::Send),
1243self.tcx.lang_items().unpin_trait(),
1244self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1245self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1246 ];
1247const AUTO_TRAITS: [&str; 6] =
1248 ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
12491250let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
12511252let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
12531254let ty = match closure_clause {
1255 hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1256hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1257// For non move closure the capture kind is the max capture kind of all captures
1258 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1259let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1260for capture in root_var_min_capture_list.iter() {
1261 max_capture_info = determine_capture_info(max_capture_info, capture.info);
1262 }
12631264apply_capture_kind_on_capture_ty(
1265self.tcx,
1266ty,
1267max_capture_info.capture_kind,
1268self.tcx.lifetimes.re_erased,
1269 )
1270 }
1271 };
12721273let mut obligations_should_hold = Vec::new();
1274// Checks if a root variable implements any of the auto traits
1275for check_trait in auto_traits_def_id.iter() {
1276 obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1277self.infcx
1278 .type_implements_trait(check_trait, [ty], self.param_env)
1279 .must_apply_modulo_regions()
1280 }));
1281 }
12821283let mut problematic_captures = FxIndexMap::default();
1284// Check whether captured fields also implement the trait
1285for capture in root_var_min_capture_list.iter() {
1286let ty = apply_capture_kind_on_capture_ty(
1287self.tcx,
1288 capture.place.ty(),
1289 capture.info.capture_kind,
1290self.tcx.lifetimes.re_erased,
1291 );
12921293// Checks if a capture implements any of the auto traits
1294let mut obligations_holds_for_capture = Vec::new();
1295for check_trait in auto_traits_def_id.iter() {
1296 obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1297self.infcx
1298 .type_implements_trait(check_trait, [ty], self.param_env)
1299 .must_apply_modulo_regions()
1300 }));
1301 }
13021303let mut capture_problems = UnordSet::default();
13041305// Checks if for any of the auto traits, one or more trait is implemented
1306 // by the root variable but not by the capture
1307for (idx, _) in obligations_should_hold.iter().enumerate() {
1308if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1309 capture_problems.insert(AUTO_TRAITS[idx]);
1310 }
1311 }
13121313if !capture_problems.is_empty() {
1314 problematic_captures.insert(
1315 UpvarMigrationInfo::CapturingPrecise {
1316 source_expr: capture.info.path_expr_id,
1317 var_name: capture.to_string(self.tcx),
1318 },
1319 capture_problems,
1320 );
1321 }
1322 }
1323if !problematic_captures.is_empty() {
1324return Some(problematic_captures);
1325 }
1326None1327 }
13281329/// Figures out the list of root variables (and their types) that aren't completely
1330 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1331 /// some path starting at that root variable **might** be affected.
1332 ///
1333 /// The output list would include a root variable if:
1334 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1335 /// enabled, **and**
1336 /// - It wasn't completely captured by the closure, **and**
1337 /// - One of the paths starting at this root variable, that is not captured needs Drop.
1338 ///
1339 /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1340 /// are no significant drops than None is returned
1341#[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(1341u32),
::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:1357",
"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(1357u32),
::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:1370",
"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(1370u32),
::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:1388",
"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(1388u32),
::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:1407",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1407u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["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:1408",
"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(1408u32),
::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:1411",
"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(1411u32),
::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:1415",
"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(1415u32),
::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))]1342fn compute_2229_migrations_for_drop(
1343&self,
1344 closure_def_id: LocalDefId,
1345 closure_span: Span,
1346 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1347 closure_clause: hir::CaptureBy,
1348 var_hir_id: HirId,
1349 ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1350let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
13511352// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1353if !ty.has_significant_drop(
1354self.tcx,
1355 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1356 ) {
1357debug!("does not have significant drop");
1358return None;
1359 }
13601361let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1362// The upvar is mentioned within the closure but no path starting from it is
1363 // used. This occurs when you have (e.g.)
1364 //
1365 // ```
1366 // let x = move || {
1367 // let _ = y;
1368 // });
1369 // ```
1370debug!("no path starting from it is used");
13711372match closure_clause {
1373// Only migrate if closure is a move closure
1374hir::CaptureBy::Value { .. } => {
1375let mut diagnostics_info = FxIndexSet::default();
1376let upvars =
1377self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1378let upvar = upvars[&var_hir_id];
1379 diagnostics_info
1380 .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1381return Some(diagnostics_info);
1382 }
1383 hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1384 }
13851386return None;
1387 };
1388debug!(?root_var_min_capture_list);
13891390let mut projections_list = Vec::new();
1391let mut diagnostics_info = FxIndexSet::default();
13921393for captured_place in root_var_min_capture_list.iter() {
1394match captured_place.info.capture_kind {
1395// Only care about captures that are moved into the closure
1396ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1397 projections_list.push(captured_place.place.projections.as_slice());
1398 diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1399 source_expr: captured_place.info.path_expr_id,
1400 var_name: captured_place.to_string(self.tcx),
1401 });
1402 }
1403 ty::UpvarCapture::ByRef(..) => {}
1404 }
1405 }
14061407debug!(?projections_list);
1408debug!(?diagnostics_info);
14091410let is_moved = !projections_list.is_empty();
1411debug!(?is_moved);
14121413let is_not_completely_captured =
1414 root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1415debug!(?is_not_completely_captured);
14161417if is_moved
1418 && is_not_completely_captured
1419 && self.has_significant_drop_outside_of_captures(
1420 closure_def_id,
1421 closure_span,
1422 ty,
1423 projections_list,
1424 )
1425 {
1426return Some(diagnostics_info);
1427 }
14281429None
1430}
14311432/// Figures out the list of root variables (and their types) that aren't completely
1433 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1434 /// order of some path starting at that root variable **might** be affected or auto-traits
1435 /// differ between the root variable and the captured paths.
1436 ///
1437 /// The output list would include a root variable if:
1438 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1439 /// enabled, **and**
1440 /// - It wasn't completely captured by the closure, **and**
1441 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1442 /// - One of the paths captured does not implement all the auto-traits its root variable
1443 /// implements.
1444 ///
1445 /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1446 /// containing the reason why root variables whose HirId is contained in the vector should
1447 /// be captured
1448#[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(1448u32),
::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))]1449fn compute_2229_migrations(
1450&self,
1451 closure_def_id: LocalDefId,
1452 closure_span: Span,
1453 closure_clause: hir::CaptureBy,
1454 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1455 ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1456let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1457return (Vec::new(), MigrationWarningReason::default());
1458 };
14591460let mut need_migrations = Vec::new();
1461let mut auto_trait_migration_reasons = UnordSet::default();
1462let mut drop_migration_needed = false;
14631464// Perform auto-trait analysis
1465for (&var_hir_id, _) in upvars.iter() {
1466let mut diagnostics_info = Vec::new();
14671468let auto_trait_diagnostic = self
1469.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1470 .unwrap_or_default();
14711472let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1473.compute_2229_migrations_for_drop(
1474 closure_def_id,
1475 closure_span,
1476 min_captures,
1477 closure_clause,
1478 var_hir_id,
1479 ) {
1480 drop_migration_needed = true;
1481 diagnostics_info
1482 } else {
1483 FxIndexSet::default()
1484 };
14851486// Combine all the captures responsible for needing migrations into one IndexSet
1487let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1488for key in auto_trait_diagnostic.keys() {
1489 capture_diagnostic.insert(key.clone());
1490 }
14911492let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1493 capture_diagnostic.sort_by_cached_key(|info| match info {
1494 UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1495 (0, Some(var_name.clone()))
1496 }
1497 UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1498 });
1499for captures_info in capture_diagnostic {
1500// Get the auto trait reasons of why migration is needed because of that capture, if there are any
1501let capture_trait_reasons =
1502if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1503 reasons.clone()
1504 } else {
1505 UnordSet::default()
1506 };
15071508// Check if migration is needed because of drop reorder as a result of that capture
1509let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
15101511// Combine all the reasons of why the root variable should be captured as a result of
1512 // auto trait implementation issues
1513auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
15141515 diagnostics_info.push(MigrationLintNote {
1516 captures_info,
1517 reason: self.compute_2229_migrations_reasons(
1518 capture_trait_reasons,
1519 capture_drop_reorder_reason,
1520 ),
1521 });
1522 }
15231524if !diagnostics_info.is_empty() {
1525 need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1526 }
1527 }
1528 (
1529 need_migrations,
1530self.compute_2229_migrations_reasons(
1531 auto_trait_migration_reasons,
1532 drop_migration_needed,
1533 ),
1534 )
1535 }
15361537/// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1538 /// of a root variable and a list of captured paths starting at this root variable (expressed
1539 /// using list of `Projection` slices), it returns true if there is a path that is not
1540 /// captured starting at this root variable that implements Drop.
1541 ///
1542 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1543 /// path say P and then list of projection slices which represent the different captures moved
1544 /// into the closure starting off of P.
1545 ///
1546 /// This will make more sense with an example:
1547 ///
1548 /// ```rust,edition2021
1549 ///
1550 /// struct FancyInteger(i32); // This implements Drop
1551 ///
1552 /// struct Point { x: FancyInteger, y: FancyInteger }
1553 /// struct Color;
1554 ///
1555 /// struct Wrapper { p: Point, c: Color }
1556 ///
1557 /// fn f(w: Wrapper) {
1558 /// let c = || {
1559 /// // Closure captures w.p.x and w.c by move.
1560 /// };
1561 ///
1562 /// c();
1563 /// }
1564 /// ```
1565 ///
1566 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1567 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1568 /// therefore Drop ordering would change and we want this function to return true.
1569 ///
1570 /// Call stack to figure out if we need to migrate for `w` would look as follows:
1571 ///
1572 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1573 /// `w[c]`.
1574 /// Notation:
1575 /// - Ty(place): Type of place
1576 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1577 /// respectively.
1578 /// ```ignore (illustrative)
1579 /// (Ty(w), [ &[p, x], &[c] ])
1580 /// // |
1581 /// // ----------------------------
1582 /// // | |
1583 /// // v v
1584 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
1585 /// // | |
1586 /// // v v
1587 /// (Ty(w.p), [ &[x] ]) false
1588 /// // |
1589 /// // |
1590 /// // -------------------------------
1591 /// // | |
1592 /// // v v
1593 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
1594 /// // | |
1595 /// // v v
1596 /// false NeedsSignificantDrop(Ty(w.p.y))
1597 /// // |
1598 /// // v
1599 /// true
1600 /// ```
1601 ///
1602 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1603 /// This implies that the `w.c` is completely captured by the closure.
1604 /// Since drop for this path will be called when the closure is
1605 /// dropped we don't need to migrate for it.
1606 ///
1607 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1608 /// path wasn't captured by the closure. Also note that even
1609 /// though we didn't capture this path, the function visits it,
1610 /// which is kind of the point of this function. We then return
1611 /// if the type of `w.p.y` implements Drop, which in this case is
1612 /// true.
1613 ///
1614 /// Consider another example:
1615 ///
1616 /// ```ignore (pseudo-rust)
1617 /// struct X;
1618 /// impl Drop for X {}
1619 ///
1620 /// struct Y(X);
1621 /// impl Drop for Y {}
1622 ///
1623 /// fn foo() {
1624 /// let y = Y(X);
1625 /// let c = || move(y.0);
1626 /// }
1627 /// ```
1628 ///
1629 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1630 /// return true, because even though all paths starting at `y` are captured, `y` itself
1631 /// implements Drop which will be affected since `y` isn't completely captured.
1632fn has_significant_drop_outside_of_captures(
1633&self,
1634 closure_def_id: LocalDefId,
1635 closure_span: Span,
1636 base_path_ty: Ty<'tcx>,
1637 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1638 ) -> bool {
1639// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1640let needs_drop = |ty: Ty<'tcx>| {
1641ty.has_significant_drop(
1642self.tcx,
1643 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1644 )
1645 };
16461647let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1648let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, closure_span);
1649self.infcx
1650 .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1651 .must_apply_modulo_regions()
1652 };
16531654let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
16551656// If there is a case where no projection is applied on top of current place
1657 // then there must be exactly one capture corresponding to such a case. Note that this
1658 // represents the case of the path being completely captured by the variable.
1659 //
1660 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1661 // capture `a.b.c`, because that violates min capture.
1662let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
16631664if !(!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));
16651666if is_completely_captured {
1667// The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1668 // when the closure is dropped.
1669return false;
1670 }
16711672if captured_by_move_projs.is_empty() {
1673return needs_drop(base_path_ty);
1674 }
16751676if is_drop_defined_for_ty {
1677// If drop is implemented for this type then we need it to be fully captured,
1678 // and we know it is not completely captured because of the previous checks.
16791680 // Note that this is a bug in the user code that will be reported by the
1681 // borrow checker, since we can't move out of drop types.
16821683 // The bug exists in the user's code pre-migration, and we don't migrate here.
1684return false;
1685 }
16861687match base_path_ty.kind() {
1688// Observations:
1689 // - `captured_by_move_projs` is not empty. Therefore we can call
1690 // `captured_by_move_projs.first().unwrap()` safely.
1691 // - All entries in `captured_by_move_projs` have at least one projection.
1692 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
16931694 // We don't capture derefs in case of move captures, which would have be applied to
1695 // access any further paths.
1696 ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1697 ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1698 ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
16991700 ty::Adt(def, args) => {
1701// Multi-variant enums are captured in entirety,
1702 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1703match (&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);
17041705// Only Field projections can be applied to a non-box Adt.
1706if !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!(
1707 captured_by_move_projs.iter().all(|projs| matches!(
1708 projs.first().unwrap().kind,
1709 ProjectionKind::Field(..)
1710 ))
1711 );
1712def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1713 |(i, field)| {
1714let paths_using_field = captured_by_move_projs1715 .iter()
1716 .filter_map(|projs| {
1717if let ProjectionKind::Field(field_idx, _) =
1718projs.first().unwrap().kind
1719 {
1720if field_idx == i { Some(&projs[1..]) } else { None }
1721 } else {
1722::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1723 }
1724 })
1725 .collect();
17261727let after_field_ty = field.ty(self.tcx, args);
1728self.has_significant_drop_outside_of_captures(
1729closure_def_id,
1730closure_span,
1731after_field_ty,
1732paths_using_field,
1733 )
1734 },
1735 )
1736 }
17371738 ty::Tuple(fields) => {
1739// Only Field projections can be applied to a tuple.
1740if !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!(
1741 captured_by_move_projs.iter().all(|projs| matches!(
1742 projs.first().unwrap().kind,
1743 ProjectionKind::Field(..)
1744 ))
1745 );
17461747fields.iter().enumerate().any(|(i, element_ty)| {
1748let paths_using_field = captured_by_move_projs1749 .iter()
1750 .filter_map(|projs| {
1751if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1752 {
1753if field_idx.index() == i { Some(&projs[1..]) } else { None }
1754 } else {
1755::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1756 }
1757 })
1758 .collect();
17591760self.has_significant_drop_outside_of_captures(
1761closure_def_id,
1762closure_span,
1763element_ty,
1764paths_using_field,
1765 )
1766 })
1767 }
17681769// Anything else would be completely captured and therefore handled already.
1770_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1771 }
1772 }
17731774fn init_capture_kind_for_place(
1775&self,
1776 place: &Place<'tcx>,
1777 capture_clause: hir::CaptureBy,
1778 ) -> ty::UpvarCapture {
1779match capture_clause {
1780// In case of a move closure if the data is accessed through a reference we
1781 // want to capture by ref to allow precise capture using reborrows.
1782 //
1783 // If the data will be moved out of this place, then the place will be truncated
1784 // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1785 //
1786 // For example:
1787 //
1788 // struct Buffer<'a> {
1789 // x: &'a String,
1790 // y: Vec<u8>,
1791 // }
1792 //
1793 // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1794 // let c = move || b.x;
1795 // drop(b);
1796 // c
1797 // }
1798 //
1799 // Even though the closure is declared as move, when we are capturing borrowed data (in
1800 // this case, *b.x) we prefer to capture by reference.
1801 // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1802 // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1803 // before, which is also an error.
1804hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1805 ty::UpvarCapture::ByValue1806 }
1807 hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1808 ty::UpvarCapture::ByUse1809 }
1810 hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1811 ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1812 }
1813 }
1814 }
18151816fn place_for_root_variable(
1817&self,
1818 closure_def_id: LocalDefId,
1819 var_hir_id: HirId,
1820 ) -> Place<'tcx> {
1821let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
18221823let place = Place {
1824 base_ty: self.node_ty(var_hir_id),
1825 base: PlaceBase::Upvar(upvar_id),
1826 projections: Default::default(),
1827 };
18281829// Normalize eagerly when inserting into `capture_information`, so all downstream
1830 // capture analysis can assume a normalized `Place`.
1831self.normalize_capture_place(self.tcx.hir_span(var_hir_id), place)
1832 }
18331834fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1835self.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)1836 }
18371838fn log_capture_analysis_first_pass(
1839&self,
1840 closure_def_id: LocalDefId,
1841 capture_information: &InferredCaptureInformation<'tcx>,
1842 closure_span: Span,
1843 ) {
1844if self.should_log_capture_analysis(closure_def_id) {
1845let mut diag =
1846self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1847for (place, capture_info) in capture_information {
1848let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1849let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
})format!("Capturing {capture_str}");
18501851let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1852 diag.span_note(span, output_str);
1853 }
1854diag.emit();
1855 }
1856 }
18571858fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1859if self.should_log_capture_analysis(closure_def_id) {
1860if let Some(min_captures) =
1861self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1862 {
1863let mut diag =
1864self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
18651866for (_, min_captures_for_var) in min_captures {
1867for capture in min_captures_for_var {
1868let place = &capture.place;
1869let capture_info = &capture.info;
18701871let capture_str =
1872 construct_capture_info_string(self.tcx, place, capture_info);
1873let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
})format!("Min Capture {capture_str}");
18741875if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1876let path_span = capture_info
1877 .path_expr_id
1878 .map_or(closure_span, |e| self.tcx.hir_span(e));
1879let capture_kind_span = capture_info
1880 .capture_kind_expr_id
1881 .map_or(closure_span, |e| self.tcx.hir_span(e));
18821883let mut multi_span: MultiSpan =
1884 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]);
18851886let capture_kind_label =
1887 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1888let path_label = construct_path_string(self.tcx, place);
18891890 multi_span.push_span_label(path_span, path_label);
1891 multi_span.push_span_label(capture_kind_span, capture_kind_label);
18921893 diag.span_note(multi_span, output_str);
1894 } else {
1895let span = capture_info
1896 .path_expr_id
1897 .map_or(closure_span, |e| self.tcx.hir_span(e));
18981899 diag.span_note(span, output_str);
1900 };
1901 }
1902 }
1903diag.emit();
1904 }
1905 }
1906 }
19071908/// A captured place is mutable if
1909 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1910 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1911fn determine_capture_mutability(
1912&self,
1913 typeck_results: &'a TypeckResults<'tcx>,
1914 place: &Place<'tcx>,
1915 ) -> hir::Mutability {
1916let var_hir_id = match place.base {
1917 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1918_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1919 };
19201921let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
19221923let mut is_mutbl = bm.1;
19241925for pointer_ty in place.deref_tys() {
1926match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
1927// We don't capture derefs of raw ptrs
1928 ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
19291930// Dereferencing a mut-ref allows us to mut the Place if we don't deref
1931 // an immut-ref after on top of this.
1932ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
19331934// The place isn't mutable once we dereference an immutable reference.
1935ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
19361937// Dereferencing a box doesn't change mutability
1938ty::Adt(def, ..) if def.is_box() => {}
19391940 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!(
1941self.tcx.hir_span(var_hir_id),
1942"deref of unexpected pointer type {:?}",
1943 unexpected_ty
1944 ),
1945 }
1946 }
19471948is_mutbl1949 }
1950}
19511952/// Determines whether a child capture that is derived from a parent capture
1953/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1954///
1955/// There are two cases when this needs to happen:
1956///
1957/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1958/// that is the case by checking if the parent capture is by move, EXCEPT if we
1959/// apply a deref projection of an immutable reference, reborrows of immutable
1960/// references which aren't restricted to the LUB of the lifetimes of the deref
1961/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1962///
1963/// ```rust
1964/// let x = &1i32; // Let's call this lifetime `'1`.
1965/// let c = async move || {
1966/// println!("{:?}", *x);
1967/// // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1968/// // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1969/// };
1970/// ```
1971///
1972/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1973/// mutable borrow cannot live for longer than either the parent *or* the borrow
1974/// that we have on the original upvar. Therefore we always need to borrow the
1975/// child capture with the lifetime of the parent coroutine-closure's env.
1976///
1977/// ```rust
1978/// let mut x = 1i32;
1979/// let c = async || {
1980/// x = 1;
1981/// // The parent borrows `x` for some `&'1 mut i32`.
1982/// // However, when we call `c()`, we implicitly autoref for the signature of
1983/// // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1984/// // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1985/// // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1986/// };
1987/// ```
1988///
1989/// If either of these cases apply, then we should capture the borrow with the
1990/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1991/// not correct, then the program is not unsound, since we still borrowck and validate
1992/// the choices made from this function -- the only side-effect is that the user
1993/// may receive unnecessary borrowck errors.
1994fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
1995 parent_capture: &ty::CapturedPlace<'tcx>,
1996 child_capture: &ty::CapturedPlace<'tcx>,
1997) -> bool {
1998// (1.)
1999(!parent_capture.is_by_ref()
2000// This is just inlined `place.deref_tys()` but truncated to just
2001 // the child projections. Namely, look for a `&T` deref, since we
2002 // can always extend `&'short mut &'long T` to `&'long T`.
2003&& !child_capture2004 .place
2005 .projections
2006 .iter()
2007 .enumerate()
2008 .skip(parent_capture.place.projections.len())
2009 .any(|(idx, proj)| {
2010#[allow(non_exhaustive_omitted_patterns)] match proj.kind {
ProjectionKind::Deref => true,
_ => false,
}matches!(proj.kind, ProjectionKind::Deref)2011 && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
{
ty::Ref(.., ty::Mutability::Not) => true,
_ => false,
}matches!(
2012 child_capture.place.ty_before_projection(idx).kind(),
2013 ty::Ref(.., ty::Mutability::Not)
2014 )2015 }))
2016// (2.)
2017 || #[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))2018}
20192020/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
2021/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
2022fn restrict_repr_packed_field_ref_capture<'tcx>(
2023mut place: Place<'tcx>,
2024mut curr_borrow_kind: ty::UpvarCapture,
2025) -> (Place<'tcx>, ty::UpvarCapture) {
2026let pos = place.projections.iter().enumerate().position(|(i, p)| {
2027let ty = place.ty_before_projection(i);
20282029// Return true for fields of packed structs.
2030match p.kind {
2031 ProjectionKind::Field(..) => match ty.kind() {
2032 ty::Adt(def, _) if def.repr().packed() => {
2033// We stop here regardless of field alignment. Field alignment can change as
2034 // types change, including the types of private fields in other crates, and that
2035 // shouldn't affect how we compute our captures.
2036true
2037}
20382039_ => false,
2040 },
2041_ => false,
2042 }
2043 });
20442045if let Some(pos) = pos {
2046truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
2047 }
20482049 (place, curr_borrow_kind)
2050}
20512052/// Returns a Ty that applies the specified capture kind on the provided capture Ty
2053fn apply_capture_kind_on_capture_ty<'tcx>(
2054 tcx: TyCtxt<'tcx>,
2055 ty: Ty<'tcx>,
2056 capture_kind: UpvarCapture,
2057 region: ty::Region<'tcx>,
2058) -> Ty<'tcx> {
2059match capture_kind {
2060 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
2061 ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
2062 }
2063}
20642065/// Returns the Span of where the value with the provided HirId would be dropped
2066fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
2067let owner_id = tcx.hir_get_enclosing_scope(hir_id).unwrap();
20682069let owner_node = tcx.hir_node(owner_id);
2070let owner_span = match owner_node {
2071 hir::Node::Item(item) => match item.kind {
2072 hir::ItemKind::Fn { body: owner_id, .. } => tcx.hir_span(owner_id.hir_id),
2073_ => {
2074::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);
2075 }
2076 },
2077 hir::Node::Block(block) => tcx.hir_span(block.hir_id),
2078 hir::Node::TraitItem(item) => tcx.hir_span(item.hir_id()),
2079 hir::Node::ImplItem(item) => tcx.hir_span(item.hir_id()),
2080_ => {
2081::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);
2082 }
2083 };
2084tcx.sess.source_map().end_point(owner_span)
2085}
20862087struct InferBorrowKind<'a, 'tcx> {
2088 fcx: &'a FnCtxt<'a, 'tcx>,
2089// The def-id of the closure whose kind and upvar accesses are being inferred.
2090closure_def_id: LocalDefId,
20912092/// For each Place that is captured by the closure, we track the minimal kind of
2093 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2094 ///
2095 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2096 /// s.str2 via a MutableBorrow
2097 ///
2098 /// ```rust,no_run
2099 /// struct SomeStruct { str1: String, str2: String };
2100 ///
2101 /// // Assume that the HirId for the variable definition is `V1`
2102 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2103 ///
2104 /// let fix_s = |new_s2| {
2105 /// // Assume that the HirId for the expression `s.str1` is `E1`
2106 /// println!("Updating SomeStruct with str1={0}", s.str1);
2107 /// // Assume that the HirId for the expression `*s.str2` is `E2`
2108 /// s.str2 = new_s2;
2109 /// };
2110 /// ```
2111 ///
2112 /// For closure `fix_s`, (at a high level) the map contains
2113 ///
2114 /// ```ignore (illustrative)
2115 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2116 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2117 /// ```
2118capture_information: InferredCaptureInformation<'tcx>,
2119 fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2120}
21212122impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
2123#[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(2123u32),
::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_capture_place(span,
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")]2124fn fake_read(
2125&mut self,
2126 place_with_id: &PlaceWithHirId<'tcx>,
2127 cause: FakeReadCause,
2128 diag_expr_id: HirId,
2129 ) {
2130let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
21312132// We need to restrict Fake Read precision to avoid fake reading unsafe code,
2133 // such as deref of a raw pointer.
2134let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
21352136let span = self.fcx.tcx.hir_span(diag_expr_id);
2137let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
21382139let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
21402141let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2142self.fake_reads.push((place, cause, diag_expr_id));
2143 }
21442145#[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(2145u32),
::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_capture_place(span,
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")]2146fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2147let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2148assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21492150let span = self.fcx.tcx.hir_span(diag_expr_id);
2151let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
21522153self.capture_information.push((
2154 place,
2155 ty::CaptureInfo {
2156 capture_kind_expr_id: Some(diag_expr_id),
2157 path_expr_id: Some(diag_expr_id),
2158 capture_kind: ty::UpvarCapture::ByValue,
2159 },
2160 ));
2161 }
21622163#[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(2163u32),
::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_capture_place(span,
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")]2164fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2165let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2166assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21672168let span = self.fcx.tcx.hir_span(diag_expr_id);
2169let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
21702171self.capture_information.push((
2172 place,
2173 ty::CaptureInfo {
2174 capture_kind_expr_id: Some(diag_expr_id),
2175 path_expr_id: Some(diag_expr_id),
2176 capture_kind: ty::UpvarCapture::ByUse,
2177 },
2178 ));
2179 }
21802181#[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(2181u32),
::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_capture_place(span,
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")]2182fn borrow(
2183&mut self,
2184 place_with_id: &PlaceWithHirId<'tcx>,
2185 diag_expr_id: HirId,
2186 bk: ty::BorrowKind,
2187 ) {
2188let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2189assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
21902191// The region here will get discarded/ignored
2192let capture_kind = ty::UpvarCapture::ByRef(bk);
21932194let span = self.fcx.tcx.hir_span(diag_expr_id);
2195let place = self.fcx.normalize_capture_place(span, place_with_id.place.clone());
21962197// We only want repr packed restriction to be applied to reading references into a packed
2198 // struct, and not when the data is being moved. Therefore we call this method here instead
2199 // of in `restrict_capture_precision`.
2200let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(place, capture_kind);
22012202// Raw pointers don't inherit mutability
2203if place.deref_tys().any(Ty::is_raw_ptr) {
2204 capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2205 }
22062207self.capture_information.push((
2208 place,
2209 ty::CaptureInfo {
2210 capture_kind_expr_id: Some(diag_expr_id),
2211 path_expr_id: Some(diag_expr_id),
2212 capture_kind,
2213 },
2214 ));
2215 }
22162217#[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(2217u32),
::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")]2218fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2219self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2220 }
2221}
22222223/// Rust doesn't permit moving fields out of a type that implements drop
2224x;#[instrument(skip(fcx), ret, level = "debug")]2225fn restrict_precision_for_drop_types<'a, 'tcx>(
2226 fcx: &'a FnCtxt<'a, 'tcx>,
2227mut place: Place<'tcx>,
2228mut curr_mode: ty::UpvarCapture,
2229) -> (Place<'tcx>, ty::UpvarCapture) {
2230let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
22312232if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2233for i in 0..place.projections.len() {
2234match place.ty_before_projection(i).kind() {
2235 ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2236 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2237break;
2238 }
2239_ => {}
2240 }
2241 }
2242 }
22432244 (place, curr_mode)
2245}
22462247/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2248/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2249/// them completely.
2250/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2251fn restrict_precision_for_unsafe(
2252mut place: Place<'_>,
2253mut curr_mode: ty::UpvarCapture,
2254) -> (Place<'_>, ty::UpvarCapture) {
2255if place.base_ty.is_raw_ptr() {
2256truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2257 }
22582259if place.base_ty.is_union() {
2260truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2261 }
22622263for (i, proj) in place.projections.iter().enumerate() {
2264if proj.ty.is_raw_ptr() {
2265// Don't apply any projections on top of a raw ptr.
2266truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2267break;
2268 }
22692270if proj.ty.is_union() {
2271// Don't capture precise fields of a union.
2272truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2273break;
2274 }
2275 }
22762277 (place, curr_mode)
2278}
22792280/// Truncate projections so that the following rules are obeyed by the captured `place`:
2281/// - No Index projections are captured, since arrays are captured completely.
2282/// - No unsafe block is required to capture `place`.
2283///
2284/// Returns the truncated place and updated capture mode.
2285x;#[instrument(ret, level = "debug")]2286fn restrict_capture_precision(
2287 place: Place<'_>,
2288 curr_mode: ty::UpvarCapture,
2289) -> (Place<'_>, ty::UpvarCapture) {
2290let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
22912292if place.projections.is_empty() {
2293// Nothing to do here
2294return (place, curr_mode);
2295 }
22962297for (i, proj) in place.projections.iter().enumerate() {
2298match proj.kind {
2299 ProjectionKind::Index | ProjectionKind::Subslice => {
2300// Arrays are completely captured, so we drop Index and Subslice projections
2301truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2302return (place, curr_mode);
2303 }
2304 ProjectionKind::Deref => {}
2305 ProjectionKind::OpaqueCast => {}
2306 ProjectionKind::Field(..) => {}
2307 ProjectionKind::UnwrapUnsafeBinder => {}
2308 }
2309 }
23102311 (place, curr_mode)
2312}
23132314/// Truncate deref of any reference.
2315x;#[instrument(ret, level = "debug")]2316fn adjust_for_move_closure(
2317mut place: Place<'_>,
2318mut kind: ty::UpvarCapture,
2319) -> (Place<'_>, ty::UpvarCapture) {
2320let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
23212322if let Some(idx) = first_deref {
2323 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2324 }
23252326 (place, ty::UpvarCapture::ByValue)
2327}
23282329/// Truncate deref of any reference.
2330x;#[instrument(ret, level = "debug")]2331fn adjust_for_use_closure(
2332mut place: Place<'_>,
2333mut kind: ty::UpvarCapture,
2334) -> (Place<'_>, ty::UpvarCapture) {
2335let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
23362337if let Some(idx) = first_deref {
2338 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2339 }
23402341 (place, ty::UpvarCapture::ByUse)
2342}
23432344/// Adjust closure capture just that if taking ownership of data, only move data
2345/// from enclosing stack frame.
2346x;#[instrument(ret, level = "debug")]2347fn adjust_for_non_move_closure(
2348mut place: Place<'_>,
2349mut kind: ty::UpvarCapture,
2350) -> (Place<'_>, ty::UpvarCapture) {
2351let contains_deref =
2352 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
23532354match kind {
2355 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2356if let Some(idx) = contains_deref {
2357 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2358 }
2359 }
23602361 ty::UpvarCapture::ByRef(..) => {}
2362 }
23632364 (place, kind)
2365}
23662367fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2368let variable_name = match place.base {
2369 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2370_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Capture_information should only contain upvars"))bug!("Capture_information should only contain upvars"),
2371 };
23722373let mut projections_str = String::new();
2374for (i, item) in place.projections.iter().enumerate() {
2375let proj = match item.kind {
2376 ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
})format!("({a:?}, {b:?})"),
2377 ProjectionKind::Deref => String::from("Deref"),
2378 ProjectionKind::Index => String::from("Index"),
2379 ProjectionKind::Subslice => String::from("Subslice"),
2380 ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2381 ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2382 };
2383if i != 0 {
2384 projections_str.push(',');
2385 }
2386 projections_str.push_str(proj.as_str());
2387 }
23882389::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
projections_str))
})format!("{variable_name}[{projections_str}]")2390}
23912392fn construct_capture_kind_reason_string<'tcx>(
2393 tcx: TyCtxt<'_>,
2394 place: &Place<'tcx>,
2395 capture_info: &ty::CaptureInfo,
2396) -> String {
2397let place_str = construct_place_string(tcx, place);
23982399let capture_kind_str = match capture_info.capture_kind {
2400 ty::UpvarCapture::ByValue => "ByValue".into(),
2401 ty::UpvarCapture::ByUse => "ByUse".into(),
2402 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2403 };
24042405::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")2406}
24072408fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2409let place_str = construct_place_string(tcx, place);
24102411::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} used here", place_str))
})format!("{place_str} used here")2412}
24132414fn construct_capture_info_string<'tcx>(
2415 tcx: TyCtxt<'_>,
2416 place: &Place<'tcx>,
2417 capture_info: &ty::CaptureInfo,
2418) -> String {
2419let place_str = construct_place_string(tcx, place);
24202421let capture_kind_str = match capture_info.capture_kind {
2422 ty::UpvarCapture::ByValue => "ByValue".into(),
2423 ty::UpvarCapture::ByUse => "ByUse".into(),
2424 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2425 };
2426::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
capture_kind_str))
})format!("{place_str} -> {capture_kind_str}")2427}
24282429fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2430tcx.hir_name(var_hir_id)
2431}
24322433#[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(2433u32),
::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; }
let level =
tcx.lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
closure_id).level;
!#[allow(non_exhaustive_omitted_patterns)] match level {
lint::Level::Allow => true,
_ => false,
}
}
}
}#[instrument(level = "debug", skip(tcx))]2434fn should_do_rust_2021_incompatible_closure_captures_analysis(
2435 tcx: TyCtxt<'_>,
2436 closure_id: HirId,
2437) -> bool {
2438if tcx.sess.at_least_rust_2021() {
2439return false;
2440 }
24412442let level = tcx
2443 .lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2444 .level;
24452446 !matches!(level, lint::Level::Allow)
2447}
24482449/// Return a two string tuple (s1, s2)
2450/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2451/// - s2: Comma separated names of the variables being migrated.
2452fn migration_suggestion_for_2229(
2453 tcx: TyCtxt<'_>,
2454 need_migrations: &[NeededMigration],
2455) -> (String, String) {
2456let need_migrations_variables = need_migrations2457 .iter()
2458 .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2459 .collect::<Vec<_>>();
24602461let migration_ref_concat =
2462need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
24632464let migration_string = if 1 == need_migrations.len() {
2465::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = {0}",
migration_ref_concat))
})format!("let _ = {migration_ref_concat}")2466 } else {
2467::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = ({0})",
migration_ref_concat))
})format!("let _ = ({migration_ref_concat})")2468 };
24692470let migrated_variables_concat =
2471need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", v))
})format!("`{v}`")).collect::<Vec<_>>().join(", ");
24722473 (migration_string, migrated_variables_concat)
2474}
24752476/// Helper function to determine if we need to escalate CaptureKind from
2477/// CaptureInfo A to B and returns the escalated CaptureInfo.
2478/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2479///
2480/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2481/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2482///
2483/// It is the caller's duty to figure out which path_expr_id to use.
2484///
2485/// If both the CaptureKind and Expression are considered to be equivalent,
2486/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2487/// expressions reported back to the user as part of diagnostics based on which appears earlier
2488/// in the closure. This can be achieved simply by calling
2489/// `determine_capture_info(existing_info, current_info)`. This works out because the
2490/// expressions that occur earlier in the closure body than the current expression are processed before.
2491/// Consider the following example
2492/// ```rust,no_run
2493/// struct Point { x: i32, y: i32 }
2494/// let mut p = Point { x: 10, y: 10 };
2495///
2496/// let c = || {
2497/// p.x += 10; // E1
2498/// // ...
2499/// // More code
2500/// // ...
2501/// p.x += 10; // E2
2502/// };
2503/// ```
2504/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2505/// and both have an expression associated, however for diagnostics we prefer reporting
2506/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2507/// would've already handled `E1`, and have an existing capture_information for it.
2508/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2509/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2510fn determine_capture_info(
2511 capture_info_a: ty::CaptureInfo,
2512 capture_info_b: ty::CaptureInfo,
2513) -> ty::CaptureInfo {
2514// If the capture kind is equivalent then, we don't need to escalate and can compare the
2515 // expressions.
2516let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2517 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2518 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2519 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2520 (ty::UpvarCapture::ByValue, _)
2521 | (ty::UpvarCapture::ByUse, _)
2522 | (ty::UpvarCapture::ByRef(_), _) => false,
2523 };
25242525if eq_capture_kind {
2526match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2527 (Some(_), _) | (None, None) => capture_info_a,
2528 (None, Some(_)) => capture_info_b,
2529 }
2530 } else {
2531// We select the CaptureKind which ranks higher based the following priority order:
2532 // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2533match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2534 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2535 | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2536::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")2537 }
2538 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2539 | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2540 | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2541capture_info_a2542 }
2543 (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2544capture_info_b2545 }
2546 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2547match (ref_a, ref_b) {
2548// Take LHS:
2549(BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2550 | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
25512552// Take RHS:
2553(BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2554 | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
25552556 (BorrowKind::Immutable, BorrowKind::Immutable)
2557 | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2558 | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2559::rustc_middle::util::bug::bug_fmt(format_args!("Expected unequal capture kinds"));bug!("Expected unequal capture kinds");
2560 }
2561 }
2562 }
2563 }
2564 }
2565}
25662567/// Truncates `place` to have up to `len` projections.
2568/// `curr_mode` is the current required capture kind for the place.
2569/// Returns the truncated `place` and the updated required capture kind.
2570///
2571/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2572/// contained `Deref` of `&mut`.
2573fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2574 place: &mut Place<'tcx>,
2575 curr_mode: &mut ty::UpvarCapture,
2576 len: usize,
2577) {
2578let 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));
25792580// If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2581 // UniqueImmBorrow
2582 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2583 // we don't need to worry about that case here.
2584match curr_mode {
2585 ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2586for i in len..place.projections.len() {
2587if place.projections[i].kind == ProjectionKind::Deref
2588 && is_mut_ref(place.ty_before_projection(i))
2589 {
2590*curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2591break;
2592 }
2593 }
2594 }
25952596 ty::UpvarCapture::ByRef(..) => {}
2597 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2598 }
25992600place.projections.truncate(len);
2601}
26022603/// Determines the Ancestry relationship of Place A relative to Place B
2604///
2605/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2606/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2607/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2608fn determine_place_ancestry_relation<'tcx>(
2609 place_a: &Place<'tcx>,
2610 place_b: &Place<'tcx>,
2611) -> PlaceAncestryRelation {
2612// If Place A and Place B don't start off from the same root variable, they are divergent.
2613if place_a.base != place_b.base {
2614return PlaceAncestryRelation::Divergent;
2615 }
26162617// Assume of length of projections_a = n
2618let projections_a = &place_a.projections;
26192620// Assume of length of projections_b = m
2621let projections_b = &place_b.projections;
26222623let same_initial_projections =
2624 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
26252626if same_initial_projections {
2627use std::cmp::Ordering;
26282629// First min(n, m) projections are the same
2630 // Select Ancestor/Descendant
2631match projections_b.len().cmp(&projections_a.len()) {
2632 Ordering::Greater => PlaceAncestryRelation::Ancestor,
2633 Ordering::Equal => PlaceAncestryRelation::SamePlace,
2634 Ordering::Less => PlaceAncestryRelation::Descendant,
2635 }
2636 } else {
2637 PlaceAncestryRelation::Divergent2638 }
2639}
26402641/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2642/// borrow checking perspective, allowing us to save us on the size of the capture.
2643///
2644///
2645/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2646/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2647/// rightmost deref of the capture if the deref is applied to a shared ref.
2648///
2649/// Reason we only drop the last deref is because of the following edge case:
2650///
2651/// ```
2652/// # struct A { field_of_a: Box<i32> }
2653/// # struct B {}
2654/// # struct C<'a>(&'a i32);
2655/// struct MyStruct<'a> {
2656/// a: &'static A,
2657/// b: B,
2658/// c: C<'a>,
2659/// }
2660///
2661/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2662/// || drop(&*m.a.field_of_a)
2663/// // Here we really do want to capture `*m.a` because that outlives `'static`
2664///
2665/// // If we capture `m`, then the closure no longer outlives `'static`
2666/// // it is constrained to `'a`
2667/// }
2668/// ```
2669x;#[instrument(ret, level = "debug")]2670fn truncate_capture_for_optimization(
2671mut place: Place<'_>,
2672mut curr_mode: ty::UpvarCapture,
2673) -> (Place<'_>, ty::UpvarCapture) {
2674let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
26752676// Find the rightmost deref (if any). All the projections that come after this
2677 // are fields or other "in-place pointer adjustments"; these refer therefore to
2678 // data owned by whatever pointer is being dereferenced here.
2679let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
26802681match idx {
2682// If that pointer is a shared reference, then we don't need those fields.
2683Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2684 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2685 }
2686None | Some(_) => {}
2687 }
26882689 (place, curr_mode)
2690}
26912692/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2693/// `span` is the span of the closure.
2694fn enable_precise_capture(span: Span) -> bool {
2695// We use span here to ensure that if the closure was generated by a macro with a different
2696 // edition.
2697span.at_least_rust_2021()
2698}