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, MultiSpan};
39use rustc_hiras hir;
40use rustc_hir::HirId;
41use rustc_hir::def_id::LocalDefId;
42use rustc_hir::intravisit::{self, Visitor};
43use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
44use rustc_middle::mir::FakeReadCause;
45use rustc_middle::traits::ObligationCauseCode;
46use rustc_middle::ty::{
47self, BorrowKind, ClosureSizeProfileData, Ty, TyCtxt, TypeVisitableExtas _, TypeckResults,
48UpvarArgs, UpvarCapture,
49};
50use rustc_middle::{bug, span_bug};
51use rustc_session::lint;
52use rustc_span::{BytePos, Pos, Span, Symbol, sym};
53use rustc_trait_selection::infer::InferCtxtExt;
54use tracing::{debug, instrument};
5556use super::FnCtxt;
57use crate::expr_use_visitoras euv;
5859/// Describe the relationship between the paths of two places
60/// eg:
61/// - `foo` is ancestor of `foo.bar.baz`
62/// - `foo.bar.baz` is an descendant of `foo.bar`
63/// - `foo.bar` and `foo.baz` are divergent
64enum PlaceAncestryRelation {
65 Ancestor,
66 Descendant,
67 SamePlace,
68 Divergent,
69}
7071/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
72/// during capture analysis. Information in this map feeds into the minimum capture
73/// analysis pass.
74type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
7576impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
77pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
78InferBorrowKindVisitor { fcx: self }.visit_body(body);
7980// it's our job to process these.
81if !self.deferred_call_resolutions.borrow().is_empty() {
::core::panicking::panic("assertion failed: self.deferred_call_resolutions.borrow().is_empty()")
};assert!(self.deferred_call_resolutions.borrow().is_empty());
82 }
83}
8485/// Intermediate format to store the hir_id pointing to the use that resulted in the
86/// corresponding place being captured and a String which contains the captured value's
87/// name (i.e: a.b.c)
88#[derive(#[automatically_derived]
impl ::core::clone::Clone for UpvarMigrationInfo {
#[inline]
fn clone(&self) -> UpvarMigrationInfo {
match self {
UpvarMigrationInfo::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 } =>
UpvarMigrationInfo::CapturingPrecise {
source_expr: ::core::clone::Clone::clone(__self_0),
var_name: ::core::clone::Clone::clone(__self_1),
},
UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
UpvarMigrationInfo::CapturingNothing {
use_span: ::core::clone::Clone::clone(__self_0),
},
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for UpvarMigrationInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
UpvarMigrationInfo::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"CapturingPrecise", "source_expr", __self_0, "var_name",
&__self_1),
UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"CapturingNothing", "use_span", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for UpvarMigrationInfo {
#[inline]
fn eq(&self, other: &UpvarMigrationInfo) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(UpvarMigrationInfo::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 },
UpvarMigrationInfo::CapturingPrecise {
source_expr: __arg1_0, var_name: __arg1_1 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(UpvarMigrationInfo::CapturingNothing { use_span: __self_0 },
UpvarMigrationInfo::CapturingNothing { use_span: __arg1_0 })
=> __self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for UpvarMigrationInfo {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<HirId>>;
let _: ::core::cmp::AssertParamIsEq<String>;
let _: ::core::cmp::AssertParamIsEq<Span>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for UpvarMigrationInfo {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
UpvarMigrationInfo::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 } => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
UpvarMigrationInfo::CapturingNothing { use_span: __self_0 } =>
::core::hash::Hash::hash(__self_0, state),
}
}
}Hash)]
89enum UpvarMigrationInfo {
90/// We previously captured all of `x`, but now we capture some sub-path.
91CapturingPrecise { source_expr: Option<HirId>, var_name: String },
92 CapturingNothing {
93// where the variable appears in the closure (but is not captured)
94use_span: Span,
95 },
96}
9798/// Reasons that we might issue a migration warning.
99#[derive(#[automatically_derived]
impl ::core::clone::Clone for MigrationWarningReason {
#[inline]
fn clone(&self) -> MigrationWarningReason {
MigrationWarningReason {
auto_traits: ::core::clone::Clone::clone(&self.auto_traits),
drop_order: ::core::clone::Clone::clone(&self.drop_order),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for MigrationWarningReason {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"MigrationWarningReason", "auto_traits", &self.auto_traits,
"drop_order", &&self.drop_order)
}
}Debug, #[automatically_derived]
impl ::core::default::Default for MigrationWarningReason {
#[inline]
fn default() -> MigrationWarningReason {
MigrationWarningReason {
auto_traits: ::core::default::Default::default(),
drop_order: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]
impl ::core::cmp::PartialEq for MigrationWarningReason {
#[inline]
fn eq(&self, other: &MigrationWarningReason) -> bool {
self.drop_order == other.drop_order &&
self.auto_traits == other.auto_traits
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MigrationWarningReason {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_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)]
100struct MigrationWarningReason {
101/// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
102 /// in this vec, but now we don't.
103auto_traits: Vec<&'static str>,
104105/// When we used to capture `x` in its entirety, we would execute some destructors
106 /// at a different time.
107drop_order: bool,
108}
109110impl MigrationWarningReason {
111fn migration_message(&self) -> String {
112let base = "changes to closure capture in Rust 2021 will affect";
113if !self.auto_traits.is_empty() && self.drop_order {
114::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} drop order and which traits the closure implements",
base))
})format!("{base} drop order and which traits the closure implements")115 } else if self.drop_order {
116::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} drop order", base))
})format!("{base} drop order")117 } else {
118::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} which traits the closure implements",
base))
})format!("{base} which traits the closure implements")119 }
120 }
121}
122123/// Intermediate format to store information needed to generate a note in the migration lint.
124struct MigrationLintNote {
125 captures_info: UpvarMigrationInfo,
126127/// reasons why migration is needed for this capture
128reason: MigrationWarningReason,
129}
130131/// Intermediate format to store the hir id of the root variable and a HashSet containing
132/// information on why the root variable should be fully captured
133struct NeededMigration {
134 var_hir_id: HirId,
135 diagnostics_info: Vec<MigrationLintNote>,
136}
137138struct InferBorrowKindVisitor<'a, 'tcx> {
139 fcx: &'a FnCtxt<'a, 'tcx>,
140}
141142impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
143fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
144match expr.kind {
145 hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
146let body = self.fcx.tcx.hir_body(body_id);
147self.visit_body(body);
148self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
149 }
150_ => {}
151 }
152153 intravisit::walk_expr(self, expr);
154 }
155156fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
157let body = self.fcx.tcx.hir_body(c.body);
158self.visit_body(body);
159 }
160}
161162impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
163/// Analysis starting point.
164#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("analyze_closure",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(164u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_hir_id",
"span", "body_id", "capture_clause"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_clause)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let ty = self.node_ty(closure_hir_id);
let (closure_def_id, args, infer_kind) =
match *ty.kind() {
ty::Closure(def_id, args) => {
(def_id, UpvarArgs::Closure(args),
self.closure_kind(ty).is_none())
}
ty::CoroutineClosure(def_id, args) => {
(def_id, UpvarArgs::CoroutineClosure(args),
self.closure_kind(ty).is_none())
}
ty::Coroutine(def_id, args) =>
(def_id, UpvarArgs::Coroutine(args), false),
ty::Error(_) => { return; }
_ => {
::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("type of closure expr {0:?} is not a closure {1:?}",
closure_hir_id, ty));
}
};
let args = self.resolve_vars_if_possible(args);
let closure_def_id = closure_def_id.expect_local();
match (&self.tcx.hir_body_owner_def_id(body.id()),
&closure_def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let mut delegate =
InferBorrowKind {
closure_def_id,
capture_information: Default::default(),
fake_reads: Default::default(),
};
let _ =
euv::ExprUseVisitor::new(&FnCtxt::new(self,
self.tcx.param_env(closure_def_id), closure_def_id),
&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 =
self.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:302",
"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(302u32),
::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 =
self.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:331",
"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(331u32),
::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([],
tupled_upvars_ty_for_borrow, false, hir::Safety::Safe,
rustc_abi::ExternAbi::Rust),
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:493",
"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(493u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_hir_id",
"args", "final_upvar_tys"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&closure_hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&args) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&final_upvar_tys)
as &dyn Value))])
});
} else { ; }
};
if self.tcx.features().unsized_fn_params() {
for capture in
self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
{
if let UpvarCapture::ByValue = capture.info.capture_kind {
self.require_type_is_sized(capture.place.ty(),
capture.get_path_span(self.tcx),
ObligationCauseCode::SizedClosureCapture(closure_def_id));
}
}
}
let final_tupled_upvars_type =
Ty::new_tup(self.tcx, &final_upvar_tys);
self.demand_suptype(span, args.tupled_upvars_ty(),
final_tupled_upvars_type);
let fake_reads = delegate.fake_reads;
self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id,
fake_reads);
if self.tcx.sess.opts.unstable_opts.profile_closures {
self.typeck_results.borrow_mut().closure_size_eval.insert(closure_def_id,
ClosureSizeProfileData {
before_feature_tys: Ty::new_tup(self.tcx,
&before_feature_tys),
after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
});
}
let deferred_call_resolutions =
self.remove_deferred_call_resolutions(closure_def_id);
for deferred_call_resolution in deferred_call_resolutions {
deferred_call_resolution.resolve(&FnCtxt::new(self,
self.param_env, closure_def_id));
}
}
}
}#[instrument(skip(self, body), level = "debug")]165fn analyze_closure(
166&self,
167 closure_hir_id: HirId,
168 span: Span,
169 body_id: hir::BodyId,
170 body: &'tcx hir::Body<'tcx>,
171mut capture_clause: hir::CaptureBy,
172 ) {
173// Extract the type of the closure.
174let ty = self.node_ty(closure_hir_id);
175let (closure_def_id, args, infer_kind) = match *ty.kind() {
176 ty::Closure(def_id, args) => {
177 (def_id, UpvarArgs::Closure(args), self.closure_kind(ty).is_none())
178 }
179 ty::CoroutineClosure(def_id, args) => {
180 (def_id, UpvarArgs::CoroutineClosure(args), self.closure_kind(ty).is_none())
181 }
182 ty::Coroutine(def_id, args) => (def_id, UpvarArgs::Coroutine(args), false),
183 ty::Error(_) => {
184// #51714: skip analysis when we have already encountered type errors
185return;
186 }
187_ => {
188span_bug!(
189 span,
190"type of closure expr {:?} is not a closure {:?}",
191 closure_hir_id,
192 ty
193 );
194 }
195 };
196let args = self.resolve_vars_if_possible(args);
197let closure_def_id = closure_def_id.expect_local();
198199assert_eq!(self.tcx.hir_body_owner_def_id(body.id()), closure_def_id);
200let mut delegate = InferBorrowKind {
201 closure_def_id,
202 capture_information: Default::default(),
203 fake_reads: Default::default(),
204 };
205206let _ = euv::ExprUseVisitor::new(
207&FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id),
208&mut delegate,
209 )
210 .consume_body(body);
211212// There are several curious situations with coroutine-closures where
213 // analysis is too aggressive with borrows when the coroutine-closure is
214 // marked `move`. Specifically:
215 //
216 // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
217 // inference, then it's still possible that we try to borrow upvars from
218 // the coroutine-closure because they are not used by the coroutine body
219 // in a way that forces a move. See the test:
220 // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
221 //
222 // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
223 // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
224 // would force the closure to `FnOnce`.
225 // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
226 //
227 // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
228 // coroutine bodies can't borrow from their parent closure. To fix this,
229 // we force the inner coroutine to also be `move`. This only matters for
230 // coroutine-closures that are `move` since otherwise they themselves will
231 // be borrowing from the outer environment, so there's no self-borrows occurring.
232if let UpvarArgs::Coroutine(..) = args
233 && let hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) =
234self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
235 && let parent_hir_id =
236self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
237 && let parent_ty = self.node_ty(parent_hir_id)
238 && let hir::CaptureBy::Value { move_kw } =
239self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
240 {
241// (1.) Closure signature inference forced this closure to `FnOnce`.
242if let Some(ty::ClosureKind::FnOnce) = self.closure_kind(parent_ty) {
243 capture_clause = hir::CaptureBy::Value { move_kw };
244 }
245// (2.) The way that the closure uses its upvars means it's `FnOnce`.
246else if self.coroutine_body_consumes_upvars(closure_def_id, body) {
247 capture_clause = hir::CaptureBy::Value { move_kw };
248 }
249 }
250251// As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
252 // to `ByRef` for the `async {}` block internal to async fns/closure. This means
253 // that we would *not* be moving all of the parameters into the async block in all cases.
254 // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
255 // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
256 //
257 // We force all of these arguments to be captured by move before we do expr use analysis.
258 //
259 // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
260 // moving all of the `LocalSource::AsyncFn` locals here.
261if let Some(hir::CoroutineKind::Desugared(
262_,
263 hir::CoroutineSource::Fn | hir::CoroutineSource::Closure,
264 )) = self.tcx.coroutine_kind(closure_def_id)
265 {
266let hir::ExprKind::Block(block, _) = body.value.kind else {
267bug!();
268 };
269for stmt in block.stmts {
270let hir::StmtKind::Let(hir::LetStmt {
271 init: Some(init),
272 source: hir::LocalSource::AsyncFn,
273 pat,
274 ..
275 }) = stmt.kind
276else {
277bug!();
278 };
279let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), _, _, _) = pat.kind
280else {
281// Complex pattern, skip the non-upvar local.
282continue;
283 };
284let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = init.kind else {
285bug!();
286 };
287let hir::def::Res::Local(local_id) = path.res else {
288bug!();
289 };
290let place = self.place_for_root_variable(closure_def_id, local_id);
291 delegate.capture_information.push((
292 place,
293 ty::CaptureInfo {
294 capture_kind_expr_id: Some(init.hir_id),
295 path_expr_id: Some(init.hir_id),
296 capture_kind: UpvarCapture::ByValue,
297 },
298 ));
299 }
300 }
301302debug!(
303"For closure={:?}, capture_information={:#?}",
304 closure_def_id, delegate.capture_information
305 );
306307self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
308309let (capture_information, closure_kind, origin) = self
310.process_collected_capture_information(capture_clause, &delegate.capture_information);
311312self.compute_min_captures(closure_def_id, capture_information, span);
313314let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
315316if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
317self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
318 }
319320let after_feature_tys = self.final_upvar_tys(closure_def_id);
321322// We now fake capture information for all variables that are mentioned within the closure
323 // We do this after handling migrations so that min_captures computes before
324if !enable_precise_capture(span) {
325let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
326327if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
328for var_hir_id in upvars.keys() {
329let place = self.place_for_root_variable(closure_def_id, *var_hir_id);
330331debug!("seed place {:?}", place);
332333let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
334let fake_info = ty::CaptureInfo {
335 capture_kind_expr_id: None,
336 path_expr_id: None,
337 capture_kind,
338 };
339340 capture_information.push((place, fake_info));
341 }
342 }
343344// This will update the min captures based on this new fake information.
345self.compute_min_captures(closure_def_id, capture_information, span);
346 }
347348let before_feature_tys = self.final_upvar_tys(closure_def_id);
349350if infer_kind {
351// Unify the (as yet unbound) type variable in the closure
352 // args with the kind we inferred.
353let closure_kind_ty = match args {
354 UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
355 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
356 UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
357 };
358self.demand_eqtype(
359 span,
360 Ty::from_closure_kind(self.tcx, closure_kind),
361 closure_kind_ty,
362 );
363364// If we have an origin, store it.
365if let Some(mut origin) = origin {
366if !enable_precise_capture(span) {
367// Without precise captures, we just capture the base and ignore
368 // the projections.
369origin.1.projections.clear()
370 }
371372self.typeck_results
373 .borrow_mut()
374 .closure_kind_origins_mut()
375 .insert(closure_hir_id, origin);
376 }
377 }
378379// For coroutine-closures, we additionally must compute the
380 // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
381 // version of the coroutine-closure's output coroutine.
382if let UpvarArgs::CoroutineClosure(args) = args
383 && !args.references_error()
384 {
385let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
386self.tcx,
387 ty::INNERMOST,
388 ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::ClosureEnv },
389 );
390391let num_args = args
392 .as_coroutine_closure()
393 .coroutine_closure_sig()
394 .skip_binder()
395 .tupled_inputs_ty
396 .tuple_fields()
397 .len();
398let typeck_results = self.typeck_results.borrow();
399400let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
401self.tcx,
402 ty::analyze_coroutine_closure_captures(
403 typeck_results.closure_min_captures_flattened(closure_def_id),
404 typeck_results
405 .closure_min_captures_flattened(
406self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
407 )
408// Skip the captures that are just moving the closure's args
409 // into the coroutine. These are always by move, and we append
410 // those later in the `CoroutineClosureSignature` helper functions.
411.skip(num_args),
412 |(_, parent_capture), (_, child_capture)| {
413// This is subtle. See documentation on function.
414let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
415 parent_capture,
416 child_capture,
417 );
418419let upvar_ty = child_capture.place.ty();
420let capture = child_capture.info.capture_kind;
421// Not all upvars are captured by ref, so use
422 // `apply_capture_kind_on_capture_ty` to ensure that we
423 // compute the right captured type.
424apply_capture_kind_on_capture_ty(
425self.tcx,
426 upvar_ty,
427 capture,
428if needs_ref {
429 closure_env_region
430 } else {
431self.tcx.lifetimes.re_erased
432 },
433 )
434 },
435 ),
436 );
437let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
438self.tcx,
439 ty::Binder::bind_with_vars(
440self.tcx.mk_fn_sig(
441 [],
442 tupled_upvars_ty_for_borrow,
443false,
444 hir::Safety::Safe,
445 rustc_abi::ExternAbi::Rust,
446 ),
447self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
448 ty::BoundRegionKind::ClosureEnv,
449 )]),
450 ),
451 );
452self.demand_eqtype(
453 span,
454 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
455 coroutine_captures_by_ref_ty,
456 );
457458// Additionally, we can now constrain the coroutine's kind type.
459 //
460 // We only do this if `infer_kind`, because if we have constrained
461 // the kind from closure signature inference, the kind inferred
462 // for the inner coroutine may actually be more restrictive.
463if infer_kind {
464let ty::Coroutine(_, coroutine_args) =
465*self.typeck_results.borrow().expr_ty(body.value).kind()
466else {
467bug!();
468 };
469self.demand_eqtype(
470 span,
471 coroutine_args.as_coroutine().kind_ty(),
472 Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
473 );
474 }
475 }
476477self.log_closure_min_capture_info(closure_def_id, span);
478479// Now that we've analyzed the closure, we know how each
480 // variable is borrowed, and we know what traits the closure
481 // implements (Fn vs FnMut etc). We now have some updates to do
482 // with that information.
483 //
484 // Note that no closure type C may have an upvar of type C
485 // (though it may reference itself via a trait object). This
486 // results from the desugaring of closures to a struct like
487 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
488 // C, then the type would have infinite size (and the
489 // inference algorithm will reject it).
490491 // Equate the type variables for the upvars with the actual types.
492let final_upvar_tys = self.final_upvar_tys(closure_def_id);
493debug!(?closure_hir_id, ?args, ?final_upvar_tys);
494495if self.tcx.features().unsized_fn_params() {
496for capture in
497self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
498 {
499if let UpvarCapture::ByValue = capture.info.capture_kind {
500self.require_type_is_sized(
501 capture.place.ty(),
502 capture.get_path_span(self.tcx),
503 ObligationCauseCode::SizedClosureCapture(closure_def_id),
504 );
505 }
506 }
507 }
508509// Build a tuple (U0..Un) of the final upvar types U0..Un
510 // and unify the upvar tuple type in the closure with it:
511let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
512self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
513514let fake_reads = delegate.fake_reads;
515516self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
517518if self.tcx.sess.opts.unstable_opts.profile_closures {
519self.typeck_results.borrow_mut().closure_size_eval.insert(
520 closure_def_id,
521 ClosureSizeProfileData {
522 before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
523 after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
524 },
525 );
526 }
527528// If we are also inferred the closure kind here,
529 // process any deferred resolutions.
530let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
531for deferred_call_resolution in deferred_call_resolutions {
532 deferred_call_resolution.resolve(&FnCtxt::new(self, self.param_env, closure_def_id));
533 }
534 }
535536/// Determines whether the body of the coroutine uses its upvars in a way that
537 /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
538 /// In a more detailed comment above, we care whether this happens, since if
539 /// this happens, we want to force the coroutine to move all of the upvars it
540 /// would've borrowed from the parent coroutine-closure.
541 ///
542 /// This only really makes sense to be called on the child coroutine of a
543 /// coroutine-closure.
544fn coroutine_body_consumes_upvars(
545&self,
546 coroutine_def_id: LocalDefId,
547 body: &'tcx hir::Body<'tcx>,
548 ) -> bool {
549// This block contains argument capturing details. Since arguments
550 // aren't upvars, we do not care about them for determining if the
551 // coroutine body actually consumes its upvars.
552let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
553else {
554::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
555 };
556// Specifically, we only care about the *real* body of the coroutine.
557 // We skip out into the drop-temps within the block of the body in order
558 // to skip over the args of the desugaring.
559let hir::ExprKind::DropTemps(body) = body.kind else {
560::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
561 };
562563let mut delegate = InferBorrowKind {
564 closure_def_id: coroutine_def_id,
565 capture_information: Default::default(),
566 fake_reads: Default::default(),
567 };
568569let _ = euv::ExprUseVisitor::new(
570&FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id),
571&mut delegate,
572 )
573 .consume_expr(body);
574575let (_, kind, _) = self.process_collected_capture_information(
576 hir::CaptureBy::Ref,
577&delegate.capture_information,
578 );
579580#[allow(non_exhaustive_omitted_patterns)] match kind {
ty::ClosureKind::FnOnce => true,
_ => false,
}matches!(kind, ty::ClosureKind::FnOnce)581 }
582583// Returns a list of `Ty`s for each upvar.
584fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
585self.typeck_results
586 .borrow()
587 .closure_min_captures_flattened(closure_id)
588 .map(|captured_place| {
589let upvar_ty = captured_place.place.ty();
590let capture = captured_place.info.capture_kind;
591592{
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:592",
"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(592u32),
::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);
593594apply_capture_kind_on_capture_ty(
595self.tcx,
596upvar_ty,
597capture,
598self.tcx.lifetimes.re_erased,
599 )
600 })
601 .collect()
602 }
603604/// Adjusts the closure capture information to ensure that the operations aren't unsafe,
605 /// and that the path can be captured with required capture kind (depending on use in closure,
606 /// move closure etc.)
607 ///
608 /// Returns the set of adjusted information along with the inferred closure kind and span
609 /// associated with the closure kind inference.
610 ///
611 /// Note that we *always* infer a minimal kind, even if
612 /// we don't always *use* that in the final result (i.e., sometimes
613 /// we've taken the closure kind from the expectations instead, and
614 /// for coroutines we don't even implement the closure traits
615 /// really).
616 ///
617 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
618 /// contains a `Some()` with the `Place` that caused us to do so.
619fn process_collected_capture_information(
620&self,
621 capture_clause: hir::CaptureBy,
622 capture_information: &InferredCaptureInformation<'tcx>,
623 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
624let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
625let mut origin: Option<(Span, Place<'tcx>)> = None;
626627let processed = capture_information628 .iter()
629 .cloned()
630 .map(|(place, mut capture_info)| {
631// Apply rules for safety before inferring closure kind
632let (place, capture_kind) =
633restrict_capture_precision(place, capture_info.capture_kind);
634635let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
636637let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
638self.tcx.hir_span(usage_expr)
639 } else {
640::core::panicking::panic("internal error: entered unreachable code")unreachable!()641 };
642643let updated = match capture_kind {
644 ty::UpvarCapture::ByValue => match closure_kind {
645 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
646 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
647 }
648// If closure is already FnOnce, don't update
649ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
650 },
651652 ty::UpvarCapture::ByRef(
653 ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
654 ) => {
655match closure_kind {
656 ty::ClosureKind::Fn => {
657 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
658 }
659// Don't update the origin
660ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
661 (closure_kind, origin.take())
662 }
663 }
664 }
665666_ => (closure_kind, origin.take()),
667 };
668669closure_kind = updated.0;
670origin = updated.1;
671672let (place, capture_kind) = match capture_clause {
673 hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
674 hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
675 hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
676 };
677678// This restriction needs to be applied after we have handled adjustments for `move`
679 // closures. We want to make sure any adjustment that might make us move the place into
680 // the closure gets handled.
681let (place, capture_kind) =
682restrict_precision_for_drop_types(self, place, capture_kind);
683684capture_info.capture_kind = capture_kind;
685 (place, capture_info)
686 })
687 .collect();
688689 (processed, closure_kind, origin)
690 }
691692/// Analyzes the information collected by `InferBorrowKind` to compute the min number of
693 /// Places (and corresponding capture kind) that we need to keep track of to support all
694 /// the required captured paths.
695 ///
696 ///
697 /// Note: If this function is called multiple times for the same closure, it will update
698 /// the existing min_capture map that is stored in TypeckResults.
699 ///
700 /// Eg:
701 /// ```
702 /// #[derive(Debug)]
703 /// struct Point { x: i32, y: i32 }
704 ///
705 /// let s = String::from("s"); // hir_id_s
706 /// let mut p = Point { x: 2, y: -2 }; // his_id_p
707 /// let c = || {
708 /// println!("{s:?}"); // L1
709 /// p.x += 10; // L2
710 /// println!("{}" , p.y); // L3
711 /// println!("{p:?}"); // L4
712 /// drop(s); // L5
713 /// };
714 /// ```
715 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
716 /// the lines L1..5 respectively.
717 ///
718 /// InferBorrowKind results in a structure like this:
719 ///
720 /// ```ignore (illustrative)
721 /// {
722 /// Place(base: hir_id_s, projections: [], ....) -> {
723 /// capture_kind_expr: hir_id_L5,
724 /// path_expr_id: hir_id_L5,
725 /// capture_kind: ByValue
726 /// },
727 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
728 /// capture_kind_expr: hir_id_L2,
729 /// path_expr_id: hir_id_L2,
730 /// capture_kind: ByValue
731 /// },
732 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
733 /// capture_kind_expr: hir_id_L3,
734 /// path_expr_id: hir_id_L3,
735 /// capture_kind: ByValue
736 /// },
737 /// Place(base: hir_id_p, projections: [], ...) -> {
738 /// capture_kind_expr: hir_id_L4,
739 /// path_expr_id: hir_id_L4,
740 /// capture_kind: ByValue
741 /// },
742 /// }
743 /// ```
744 ///
745 /// After the min capture analysis, we get:
746 /// ```ignore (illustrative)
747 /// {
748 /// hir_id_s -> [
749 /// Place(base: hir_id_s, projections: [], ....) -> {
750 /// capture_kind_expr: hir_id_L5,
751 /// path_expr_id: hir_id_L5,
752 /// capture_kind: ByValue
753 /// },
754 /// ],
755 /// hir_id_p -> [
756 /// Place(base: hir_id_p, projections: [], ...) -> {
757 /// capture_kind_expr: hir_id_L2,
758 /// path_expr_id: hir_id_L4,
759 /// capture_kind: ByValue
760 /// },
761 /// ],
762 /// }
763 /// ```
764#[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(764u32),
::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 =
<[_]>::into_vec(::alloc::boxed::box_new([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:889",
"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(889u32),
::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:950",
"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(950u32),
::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))]765fn compute_min_captures(
766&self,
767 closure_def_id: LocalDefId,
768 capture_information: InferredCaptureInformation<'tcx>,
769 closure_span: Span,
770 ) {
771if capture_information.is_empty() {
772return;
773 }
774775let mut typeck_results = self.typeck_results.borrow_mut();
776777let mut root_var_min_capture_list =
778 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
779780for (mut place, capture_info) in capture_information.into_iter() {
781let var_hir_id = match place.base {
782 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
783 base => bug!("Expected upvar, found={:?}", base),
784 };
785let var_ident = self.tcx.hir_ident(var_hir_id);
786787let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
788let mutability = self.determine_capture_mutability(&typeck_results, &place);
789let min_cap_list =
790vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
791 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
792continue;
793 };
794795// Go through each entry in the current list of min_captures
796 // - if ancestor is found, update its capture kind to account for current place's
797 // capture information.
798 //
799 // - if descendant is found, remove it from the list, and update the current place's
800 // capture information to account for the descendant's capture kind.
801 //
802 // We can never be in a case where the list contains both an ancestor and a descendant
803 // Also there can only be ancestor but in case of descendants there might be
804 // multiple.
805806let mut descendant_found = false;
807let mut updated_capture_info = capture_info;
808 min_cap_list.retain(|possible_descendant| {
809match determine_place_ancestry_relation(&place, &possible_descendant.place) {
810// current place is ancestor of possible_descendant
811PlaceAncestryRelation::Ancestor => {
812 descendant_found = true;
813814let mut possible_descendant = possible_descendant.clone();
815let backup_path_expr_id = updated_capture_info.path_expr_id;
816817// Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
818 // possible change in capture mode.
819truncate_place_to_len_and_update_capture_kind(
820&mut possible_descendant.place,
821&mut possible_descendant.info.capture_kind,
822 place.projections.len(),
823 );
824825 updated_capture_info =
826 determine_capture_info(updated_capture_info, possible_descendant.info);
827828// we need to keep the ancestor's `path_expr_id`
829updated_capture_info.path_expr_id = backup_path_expr_id;
830false
831}
832833_ => true,
834 }
835 });
836837let mut ancestor_found = false;
838if !descendant_found {
839for possible_ancestor in min_cap_list.iter_mut() {
840match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
841 PlaceAncestryRelation::SamePlace => {
842 ancestor_found = true;
843 possible_ancestor.info = determine_capture_info(
844 possible_ancestor.info,
845 updated_capture_info,
846 );
847848// Only one related place will be in the list.
849break;
850 }
851// current place is descendant of possible_ancestor
852PlaceAncestryRelation::Descendant => {
853 ancestor_found = true;
854let backup_path_expr_id = possible_ancestor.info.path_expr_id;
855856// Truncate the descendant (current place) to be same as the ancestor to handle any
857 // possible change in capture mode.
858truncate_place_to_len_and_update_capture_kind(
859&mut place,
860&mut updated_capture_info.capture_kind,
861 possible_ancestor.place.projections.len(),
862 );
863864 possible_ancestor.info = determine_capture_info(
865 possible_ancestor.info,
866 updated_capture_info,
867 );
868869// we need to keep the ancestor's `path_expr_id`
870possible_ancestor.info.path_expr_id = backup_path_expr_id;
871872// Only one related place will be in the list.
873break;
874 }
875_ => {}
876 }
877 }
878 }
879880// Only need to insert when we don't have an ancestor in the existing min capture list
881if !ancestor_found {
882let mutability = self.determine_capture_mutability(&typeck_results, &place);
883let captured_place =
884 ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
885 min_cap_list.push(captured_place);
886 }
887 }
888889debug!(
890"For closure={:?}, min_captures before sorting={:?}",
891 closure_def_id, root_var_min_capture_list
892 );
893894// Now that we have the minimized list of captures, sort the captures by field id.
895 // This causes the closure to capture the upvars in the same order as the fields are
896 // declared which is also the drop order. Thus, in situations where we capture all the
897 // fields of some type, the observable drop order will remain the same as it previously
898 // was even though we're dropping each capture individually.
899 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
900 // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
901for (_, captures) in &mut root_var_min_capture_list {
902 captures.sort_by(|capture1, capture2| {
903fn is_field<'a>(p: &&Projection<'a>) -> bool {
904match p.kind {
905 ProjectionKind::Field(_, _) => true,
906 ProjectionKind::Deref
907 | ProjectionKind::OpaqueCast
908 | ProjectionKind::UnwrapUnsafeBinder => false,
909 p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
910bug!("ProjectionKind {:?} was unexpected", p)
911 }
912 }
913 }
914915// Need to sort only by Field projections, so filter away others.
916 // A previous implementation considered other projection types too
917 // but that caused ICE #118144
918let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
919let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
920921for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
922// We do not need to look at the `Projection.ty` fields here because at each
923 // step of the iteration, the projections will either be the same and therefore
924 // the types must be as well or the current projection will be different and
925 // we will return the result of comparing the field indexes.
926match (p1.kind, p2.kind) {
927 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
928// Compare only if paths are different.
929 // Otherwise continue to the next iteration
930if i1 != i2 {
931return i1.cmp(&i2);
932 }
933 }
934// Given the filter above, this arm should never be hit
935(l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
936 }
937 }
938939self.dcx().span_delayed_bug(
940 closure_span,
941format!(
942"two identical projections: ({:?}, {:?})",
943 capture1.place.projections, capture2.place.projections
944 ),
945 );
946 std::cmp::Ordering::Equal
947 });
948 }
949950debug!(
951"For closure={:?}, min_captures after sorting={:#?}",
952 closure_def_id, root_var_min_capture_list
953 );
954 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
955 }
956957/// Perform the migration analysis for RFC 2229, and emit lint
958 /// `disjoint_capture_drop_reorder` if needed.
959fn perform_2229_migration_analysis(
960&self,
961 closure_def_id: LocalDefId,
962 body_id: hir::BodyId,
963 capture_clause: hir::CaptureBy,
964 span: Span,
965 ) {
966let (need_migrations, reasons) = self.compute_2229_migrations(
967closure_def_id,
968span,
969capture_clause,
970self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
971 );
972973if !need_migrations.is_empty() {
974let (migration_string, migrated_variables_concat) =
975migration_suggestion_for_2229(self.tcx, &need_migrations);
976977let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
978let closure_head_span = self.tcx.def_span(closure_def_id);
979self.tcx.node_span_lint(
980 lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
981closure_hir_id,
982closure_head_span,
983 |lint| {
984lint.primary_message(reasons.migration_message());
985986for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
987// Labels all the usage of the captured variable and why they are responsible
988 // for migration being needed
989for lint_note in diagnostics_info.iter() {
990match &lint_note.captures_info {
991 UpvarMigrationInfo::CapturingPrecise { source_expr: Some(capture_expr_id), var_name: captured_name } => {
992let cause_span = self.tcx.hir_span(*capture_expr_id);
993 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}`",
self.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 `{}`",
994self.tcx.hir_name(*var_hir_id),
995 captured_name,
996 ));
997 }
998 UpvarMigrationInfo::CapturingNothing { use_span } => {
999 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",
self.tcx.hir_name(*var_hir_id)))
})format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
1000self.tcx.hir_name(*var_hir_id),
1001 ));
1002 }
10031004_ => { }
1005 }
10061007// Add a label pointing to where a captured variable affected by drop order
1008 // is dropped
1009if lint_note.reason.drop_order {
1010let drop_location_span = drop_location_span(self.tcx, closure_hir_id);
10111012match &lint_note.captures_info {
1013 UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
1014 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",
self.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",
1015self.tcx.hir_name(*var_hir_id),
1016 captured_name,
1017 ));
1018 }
1019 UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1020 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",
self.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",
1021 v = self.tcx.hir_name(*var_hir_id),
1022 ));
1023 }
1024 }
1025 }
10261027// Add a label explaining why a closure no longer implements a trait
1028for &missing_trait in &lint_note.reason.auto_traits {
1029// not capturing something anymore cannot cause a trait to fail to be implemented:
1030match &lint_note.captures_info {
1031 UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
1032let var_name = self.tcx.hir_name(*var_hir_id);
1033 lint.span_label(closure_head_span, ::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!("\
1034 in Rust 2018, this closure implements {missing_trait} \
1035 as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1036 this closure will no longer implement {missing_trait} \
1037 because `{var_name}` is not fully captured \
1038 and `{captured_name}` does not implement {missing_trait}"));
1039 }
10401041// Cannot happen: if we don't capture a variable, we impl strictly more traits
1042 UpvarMigrationInfo::CapturingNothing { use_span } => ::rustc_middle::util::bug::span_bug_fmt(*use_span,
format_args!("missing trait from not capturing something"))span_bug!(*use_span, "missing trait from not capturing something"),
1043 }
1044 }
1045 }
1046 }
10471048let 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!(
1049"add a dummy let to cause {migrated_variables_concat} to be fully captured"
1050);
10511052let closure_span = self.tcx.hir_span_with_body(closure_hir_id);
1053let mut closure_body_span = {
1054// If the body was entirely expanded from a macro
1055 // invocation, i.e. the body is not contained inside the
1056 // closure span, then we walk up the expansion until we
1057 // find the span before the expansion.
1058let s = self.tcx.hir_span_with_body(body_id.hir_id);
1059s.find_ancestor_inside(closure_span).unwrap_or(s)
1060 };
10611062if let Ok(mut s) = self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1063if s.starts_with('$') {
1064// Looks like a macro fragment. Try to find the real block.
1065if let hir::Node::Expr(&hir::Expr {
1066 kind: hir::ExprKind::Block(block, ..), ..
1067 }) = self.tcx.hir_node(body_id.hir_id) {
1068// If the body is a block (with `{..}`), we use the span of that block.
1069 // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1070 // Since we know it's a block, we know we can insert the `let _ = ..` without
1071 // breaking the macro syntax.
1072if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(block.span) {
1073closure_body_span = block.span;
1074s = snippet;
1075 }
1076 }
1077 }
10781079let mut lines = s.lines();
1080let line1 = lines.next().unwrap_or_default();
10811082if line1.trim_end() == "{" {
1083// This is a multi-line closure with just a `{` on the first line,
1084 // so we put the `let` on its own line.
1085 // We take the indentation from the next non-empty line.
1086let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1087let indent = line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1088lint.span_suggestion(
1089closure_body_span.with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len())).shrink_to_lo(),
1090diagnostic_msg,
1091::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}{1};", indent,
migration_string))
})format!("\n{indent}{migration_string};"),
1092 Applicability::MachineApplicable,
1093 );
1094 } else if line1.starts_with('{') {
1095// This is a closure with its body wrapped in
1096 // braces, but with more than just the opening
1097 // brace on the first line. We put the `let`
1098 // directly after the `{`.
1099lint.span_suggestion(
1100closure_body_span.with_lo(closure_body_span.lo() + BytePos(1)).shrink_to_lo(),
1101diagnostic_msg,
1102::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0};", migration_string))
})format!(" {migration_string};"),
1103 Applicability::MachineApplicable,
1104 );
1105 } else {
1106// This is a closure without braces around the body.
1107 // We add braces to add the `let` before the body.
1108lint.multipart_suggestion(
1109diagnostic_msg,
1110<[_]>::into_vec(::alloc::boxed::box_new([(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![
1111 (closure_body_span.shrink_to_lo(), format!("{{ {migration_string}; ")),
1112 (closure_body_span.shrink_to_hi(), " }".to_string()),
1113 ],
1114 Applicability::MachineApplicable1115 );
1116 }
1117 } else {
1118lint.span_suggestion(
1119closure_span,
1120diagnostic_msg,
1121migration_string,
1122 Applicability::HasPlaceholders1123 );
1124 }
1125 },
1126 );
1127 }
1128 }
11291130/// Combines all the reasons for 2229 migrations
1131fn compute_2229_migrations_reasons(
1132&self,
1133 auto_trait_reasons: UnordSet<&'static str>,
1134 drop_order: bool,
1135 ) -> MigrationWarningReason {
1136MigrationWarningReason {
1137 auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1138drop_order,
1139 }
1140 }
11411142/// Figures out the list of root variables (and their types) that aren't completely
1143 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1144 /// differ between the root variable and the captured paths.
1145 ///
1146 /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1147 /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1148fn compute_2229_migrations_for_trait(
1149&self,
1150 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1151 var_hir_id: HirId,
1152 closure_clause: hir::CaptureBy,
1153 ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1154let auto_traits_def_id = [
1155self.tcx.lang_items().clone_trait(),
1156self.tcx.lang_items().sync_trait(),
1157self.tcx.get_diagnostic_item(sym::Send),
1158self.tcx.lang_items().unpin_trait(),
1159self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1160self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1161 ];
1162const AUTO_TRAITS: [&str; 6] =
1163 ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
11641165let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
11661167let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
11681169let ty = match closure_clause {
1170 hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1171hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1172// For non move closure the capture kind is the max capture kind of all captures
1173 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1174let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1175for capture in root_var_min_capture_list.iter() {
1176 max_capture_info = determine_capture_info(max_capture_info, capture.info);
1177 }
11781179apply_capture_kind_on_capture_ty(
1180self.tcx,
1181ty,
1182max_capture_info.capture_kind,
1183self.tcx.lifetimes.re_erased,
1184 )
1185 }
1186 };
11871188let mut obligations_should_hold = Vec::new();
1189// Checks if a root variable implements any of the auto traits
1190for check_trait in auto_traits_def_id.iter() {
1191 obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1192self.infcx
1193 .type_implements_trait(check_trait, [ty], self.param_env)
1194 .must_apply_modulo_regions()
1195 }));
1196 }
11971198let mut problematic_captures = FxIndexMap::default();
1199// Check whether captured fields also implement the trait
1200for capture in root_var_min_capture_list.iter() {
1201let ty = apply_capture_kind_on_capture_ty(
1202self.tcx,
1203 capture.place.ty(),
1204 capture.info.capture_kind,
1205self.tcx.lifetimes.re_erased,
1206 );
12071208// Checks if a capture implements any of the auto traits
1209let mut obligations_holds_for_capture = Vec::new();
1210for check_trait in auto_traits_def_id.iter() {
1211 obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1212self.infcx
1213 .type_implements_trait(check_trait, [ty], self.param_env)
1214 .must_apply_modulo_regions()
1215 }));
1216 }
12171218let mut capture_problems = UnordSet::default();
12191220// Checks if for any of the auto traits, one or more trait is implemented
1221 // by the root variable but not by the capture
1222for (idx, _) in obligations_should_hold.iter().enumerate() {
1223if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1224 capture_problems.insert(AUTO_TRAITS[idx]);
1225 }
1226 }
12271228if !capture_problems.is_empty() {
1229 problematic_captures.insert(
1230 UpvarMigrationInfo::CapturingPrecise {
1231 source_expr: capture.info.path_expr_id,
1232 var_name: capture.to_string(self.tcx),
1233 },
1234 capture_problems,
1235 );
1236 }
1237 }
1238if !problematic_captures.is_empty() {
1239return Some(problematic_captures);
1240 }
1241None1242 }
12431244/// Figures out the list of root variables (and their types) that aren't completely
1245 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1246 /// some path starting at that root variable **might** be affected.
1247 ///
1248 /// The output list would include a root variable if:
1249 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1250 /// enabled, **and**
1251 /// - It wasn't completely captured by the closure, **and**
1252 /// - One of the paths starting at this root variable, that is not captured needs Drop.
1253 ///
1254 /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1255 /// are no significant drops than None is returned
1256#[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(1256u32),
::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:1272",
"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(1272u32),
::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:1285",
"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(1285u32),
::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:1303",
"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(1303u32),
::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:1322",
"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(1322u32),
::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:1323",
"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(1323u32),
::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:1326",
"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(1326u32),
::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:1330",
"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(1330u32),
::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))]1257fn compute_2229_migrations_for_drop(
1258&self,
1259 closure_def_id: LocalDefId,
1260 closure_span: Span,
1261 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1262 closure_clause: hir::CaptureBy,
1263 var_hir_id: HirId,
1264 ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1265let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
12661267// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1268if !ty.has_significant_drop(
1269self.tcx,
1270 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1271 ) {
1272debug!("does not have significant drop");
1273return None;
1274 }
12751276let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1277// The upvar is mentioned within the closure but no path starting from it is
1278 // used. This occurs when you have (e.g.)
1279 //
1280 // ```
1281 // let x = move || {
1282 // let _ = y;
1283 // });
1284 // ```
1285debug!("no path starting from it is used");
12861287match closure_clause {
1288// Only migrate if closure is a move closure
1289hir::CaptureBy::Value { .. } => {
1290let mut diagnostics_info = FxIndexSet::default();
1291let upvars =
1292self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1293let upvar = upvars[&var_hir_id];
1294 diagnostics_info
1295 .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1296return Some(diagnostics_info);
1297 }
1298 hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1299 }
13001301return None;
1302 };
1303debug!(?root_var_min_capture_list);
13041305let mut projections_list = Vec::new();
1306let mut diagnostics_info = FxIndexSet::default();
13071308for captured_place in root_var_min_capture_list.iter() {
1309match captured_place.info.capture_kind {
1310// Only care about captures that are moved into the closure
1311ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1312 projections_list.push(captured_place.place.projections.as_slice());
1313 diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1314 source_expr: captured_place.info.path_expr_id,
1315 var_name: captured_place.to_string(self.tcx),
1316 });
1317 }
1318 ty::UpvarCapture::ByRef(..) => {}
1319 }
1320 }
13211322debug!(?projections_list);
1323debug!(?diagnostics_info);
13241325let is_moved = !projections_list.is_empty();
1326debug!(?is_moved);
13271328let is_not_completely_captured =
1329 root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1330debug!(?is_not_completely_captured);
13311332if is_moved
1333 && is_not_completely_captured
1334 && self.has_significant_drop_outside_of_captures(
1335 closure_def_id,
1336 closure_span,
1337 ty,
1338 projections_list,
1339 )
1340 {
1341return Some(diagnostics_info);
1342 }
13431344None
1345}
13461347/// Figures out the list of root variables (and their types) that aren't completely
1348 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1349 /// order of some path starting at that root variable **might** be affected or auto-traits
1350 /// differ between the root variable and the captured paths.
1351 ///
1352 /// The output list would include a root variable if:
1353 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1354 /// enabled, **and**
1355 /// - It wasn't completely captured by the closure, **and**
1356 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1357 /// - One of the paths captured does not implement all the auto-traits its root variable
1358 /// implements.
1359 ///
1360 /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1361 /// containing the reason why root variables whose HirId is contained in the vector should
1362 /// be captured
1363#[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(1363u32),
::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))]1364fn compute_2229_migrations(
1365&self,
1366 closure_def_id: LocalDefId,
1367 closure_span: Span,
1368 closure_clause: hir::CaptureBy,
1369 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1370 ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1371let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1372return (Vec::new(), MigrationWarningReason::default());
1373 };
13741375let mut need_migrations = Vec::new();
1376let mut auto_trait_migration_reasons = UnordSet::default();
1377let mut drop_migration_needed = false;
13781379// Perform auto-trait analysis
1380for (&var_hir_id, _) in upvars.iter() {
1381let mut diagnostics_info = Vec::new();
13821383let auto_trait_diagnostic = self
1384.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1385 .unwrap_or_default();
13861387let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1388.compute_2229_migrations_for_drop(
1389 closure_def_id,
1390 closure_span,
1391 min_captures,
1392 closure_clause,
1393 var_hir_id,
1394 ) {
1395 drop_migration_needed = true;
1396 diagnostics_info
1397 } else {
1398 FxIndexSet::default()
1399 };
14001401// Combine all the captures responsible for needing migrations into one IndexSet
1402let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1403for key in auto_trait_diagnostic.keys() {
1404 capture_diagnostic.insert(key.clone());
1405 }
14061407let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1408 capture_diagnostic.sort_by_cached_key(|info| match info {
1409 UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1410 (0, Some(var_name.clone()))
1411 }
1412 UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1413 });
1414for captures_info in capture_diagnostic {
1415// Get the auto trait reasons of why migration is needed because of that capture, if there are any
1416let capture_trait_reasons =
1417if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1418 reasons.clone()
1419 } else {
1420 UnordSet::default()
1421 };
14221423// Check if migration is needed because of drop reorder as a result of that capture
1424let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
14251426// Combine all the reasons of why the root variable should be captured as a result of
1427 // auto trait implementation issues
1428auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
14291430 diagnostics_info.push(MigrationLintNote {
1431 captures_info,
1432 reason: self.compute_2229_migrations_reasons(
1433 capture_trait_reasons,
1434 capture_drop_reorder_reason,
1435 ),
1436 });
1437 }
14381439if !diagnostics_info.is_empty() {
1440 need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1441 }
1442 }
1443 (
1444 need_migrations,
1445self.compute_2229_migrations_reasons(
1446 auto_trait_migration_reasons,
1447 drop_migration_needed,
1448 ),
1449 )
1450 }
14511452/// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1453 /// of a root variable and a list of captured paths starting at this root variable (expressed
1454 /// using list of `Projection` slices), it returns true if there is a path that is not
1455 /// captured starting at this root variable that implements Drop.
1456 ///
1457 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1458 /// path say P and then list of projection slices which represent the different captures moved
1459 /// into the closure starting off of P.
1460 ///
1461 /// This will make more sense with an example:
1462 ///
1463 /// ```rust,edition2021
1464 ///
1465 /// struct FancyInteger(i32); // This implements Drop
1466 ///
1467 /// struct Point { x: FancyInteger, y: FancyInteger }
1468 /// struct Color;
1469 ///
1470 /// struct Wrapper { p: Point, c: Color }
1471 ///
1472 /// fn f(w: Wrapper) {
1473 /// let c = || {
1474 /// // Closure captures w.p.x and w.c by move.
1475 /// };
1476 ///
1477 /// c();
1478 /// }
1479 /// ```
1480 ///
1481 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1482 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1483 /// therefore Drop ordering would change and we want this function to return true.
1484 ///
1485 /// Call stack to figure out if we need to migrate for `w` would look as follows:
1486 ///
1487 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1488 /// `w[c]`.
1489 /// Notation:
1490 /// - Ty(place): Type of place
1491 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1492 /// respectively.
1493 /// ```ignore (illustrative)
1494 /// (Ty(w), [ &[p, x], &[c] ])
1495 /// // |
1496 /// // ----------------------------
1497 /// // | |
1498 /// // v v
1499 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
1500 /// // | |
1501 /// // v v
1502 /// (Ty(w.p), [ &[x] ]) false
1503 /// // |
1504 /// // |
1505 /// // -------------------------------
1506 /// // | |
1507 /// // v v
1508 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
1509 /// // | |
1510 /// // v v
1511 /// false NeedsSignificantDrop(Ty(w.p.y))
1512 /// // |
1513 /// // v
1514 /// true
1515 /// ```
1516 ///
1517 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1518 /// This implies that the `w.c` is completely captured by the closure.
1519 /// Since drop for this path will be called when the closure is
1520 /// dropped we don't need to migrate for it.
1521 ///
1522 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1523 /// path wasn't captured by the closure. Also note that even
1524 /// though we didn't capture this path, the function visits it,
1525 /// which is kind of the point of this function. We then return
1526 /// if the type of `w.p.y` implements Drop, which in this case is
1527 /// true.
1528 ///
1529 /// Consider another example:
1530 ///
1531 /// ```ignore (pseudo-rust)
1532 /// struct X;
1533 /// impl Drop for X {}
1534 ///
1535 /// struct Y(X);
1536 /// impl Drop for Y {}
1537 ///
1538 /// fn foo() {
1539 /// let y = Y(X);
1540 /// let c = || move(y.0);
1541 /// }
1542 /// ```
1543 ///
1544 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1545 /// return true, because even though all paths starting at `y` are captured, `y` itself
1546 /// implements Drop which will be affected since `y` isn't completely captured.
1547fn has_significant_drop_outside_of_captures(
1548&self,
1549 closure_def_id: LocalDefId,
1550 closure_span: Span,
1551 base_path_ty: Ty<'tcx>,
1552 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1553 ) -> bool {
1554// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1555let needs_drop = |ty: Ty<'tcx>| {
1556ty.has_significant_drop(
1557self.tcx,
1558 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1559 )
1560 };
15611562let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1563let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, closure_span);
1564self.infcx
1565 .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1566 .must_apply_modulo_regions()
1567 };
15681569let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
15701571// If there is a case where no projection is applied on top of current place
1572 // then there must be exactly one capture corresponding to such a case. Note that this
1573 // represents the case of the path being completely captured by the variable.
1574 //
1575 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1576 // capture `a.b.c`, because that violates min capture.
1577let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
15781579if !(!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));
15801581if is_completely_captured {
1582// The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1583 // when the closure is dropped.
1584return false;
1585 }
15861587if captured_by_move_projs.is_empty() {
1588return needs_drop(base_path_ty);
1589 }
15901591if is_drop_defined_for_ty {
1592// If drop is implemented for this type then we need it to be fully captured,
1593 // and we know it is not completely captured because of the previous checks.
15941595 // Note that this is a bug in the user code that will be reported by the
1596 // borrow checker, since we can't move out of drop types.
15971598 // The bug exists in the user's code pre-migration, and we don't migrate here.
1599return false;
1600 }
16011602match base_path_ty.kind() {
1603// Observations:
1604 // - `captured_by_move_projs` is not empty. Therefore we can call
1605 // `captured_by_move_projs.first().unwrap()` safely.
1606 // - All entries in `captured_by_move_projs` have at least one projection.
1607 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
16081609 // We don't capture derefs in case of move captures, which would have be applied to
1610 // access any further paths.
1611 ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1612 ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1613 ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
16141615 ty::Adt(def, args) => {
1616// Multi-variant enums are captured in entirety,
1617 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1618match (&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);
16191620// Only Field projections can be applied to a non-box Adt.
1621if !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!(
1622 captured_by_move_projs.iter().all(|projs| matches!(
1623 projs.first().unwrap().kind,
1624 ProjectionKind::Field(..)
1625 ))
1626 );
1627def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1628 |(i, field)| {
1629let paths_using_field = captured_by_move_projs1630 .iter()
1631 .filter_map(|projs| {
1632if let ProjectionKind::Field(field_idx, _) =
1633projs.first().unwrap().kind
1634 {
1635if field_idx == i { Some(&projs[1..]) } else { None }
1636 } else {
1637::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1638 }
1639 })
1640 .collect();
16411642let after_field_ty = field.ty(self.tcx, args);
1643self.has_significant_drop_outside_of_captures(
1644closure_def_id,
1645closure_span,
1646after_field_ty,
1647paths_using_field,
1648 )
1649 },
1650 )
1651 }
16521653 ty::Tuple(fields) => {
1654// Only Field projections can be applied to a tuple.
1655if !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!(
1656 captured_by_move_projs.iter().all(|projs| matches!(
1657 projs.first().unwrap().kind,
1658 ProjectionKind::Field(..)
1659 ))
1660 );
16611662fields.iter().enumerate().any(|(i, element_ty)| {
1663let paths_using_field = captured_by_move_projs1664 .iter()
1665 .filter_map(|projs| {
1666if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1667 {
1668if field_idx.index() == i { Some(&projs[1..]) } else { None }
1669 } else {
1670::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1671 }
1672 })
1673 .collect();
16741675self.has_significant_drop_outside_of_captures(
1676closure_def_id,
1677closure_span,
1678element_ty,
1679paths_using_field,
1680 )
1681 })
1682 }
16831684// Anything else would be completely captured and therefore handled already.
1685_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1686 }
1687 }
16881689fn init_capture_kind_for_place(
1690&self,
1691 place: &Place<'tcx>,
1692 capture_clause: hir::CaptureBy,
1693 ) -> ty::UpvarCapture {
1694match capture_clause {
1695// In case of a move closure if the data is accessed through a reference we
1696 // want to capture by ref to allow precise capture using reborrows.
1697 //
1698 // If the data will be moved out of this place, then the place will be truncated
1699 // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1700 //
1701 // For example:
1702 //
1703 // struct Buffer<'a> {
1704 // x: &'a String,
1705 // y: Vec<u8>,
1706 // }
1707 //
1708 // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1709 // let c = move || b.x;
1710 // drop(b);
1711 // c
1712 // }
1713 //
1714 // Even though the closure is declared as move, when we are capturing borrowed data (in
1715 // this case, *b.x) we prefer to capture by reference.
1716 // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1717 // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1718 // before, which is also an error.
1719hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1720 ty::UpvarCapture::ByValue1721 }
1722 hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1723 ty::UpvarCapture::ByUse1724 }
1725 hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1726 ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1727 }
1728 }
1729 }
17301731fn place_for_root_variable(
1732&self,
1733 closure_def_id: LocalDefId,
1734 var_hir_id: HirId,
1735 ) -> Place<'tcx> {
1736let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
17371738Place {
1739 base_ty: self.node_ty(var_hir_id),
1740 base: PlaceBase::Upvar(upvar_id),
1741 projections: Default::default(),
1742 }
1743 }
17441745fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1746self.has_rustc_attrs && self.tcx.has_attr(closure_def_id, sym::rustc_capture_analysis)
1747 }
17481749fn log_capture_analysis_first_pass(
1750&self,
1751 closure_def_id: LocalDefId,
1752 capture_information: &InferredCaptureInformation<'tcx>,
1753 closure_span: Span,
1754 ) {
1755if self.should_log_capture_analysis(closure_def_id) {
1756let mut diag =
1757self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1758for (place, capture_info) in capture_information {
1759let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1760let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
})format!("Capturing {capture_str}");
17611762let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1763 diag.span_note(span, output_str);
1764 }
1765diag.emit();
1766 }
1767 }
17681769fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1770if self.should_log_capture_analysis(closure_def_id) {
1771if let Some(min_captures) =
1772self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1773 {
1774let mut diag =
1775self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
17761777for (_, min_captures_for_var) in min_captures {
1778for capture in min_captures_for_var {
1779let place = &capture.place;
1780let capture_info = &capture.info;
17811782let capture_str =
1783 construct_capture_info_string(self.tcx, place, capture_info);
1784let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
})format!("Min Capture {capture_str}");
17851786if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1787let path_span = capture_info
1788 .path_expr_id
1789 .map_or(closure_span, |e| self.tcx.hir_span(e));
1790let capture_kind_span = capture_info
1791 .capture_kind_expr_id
1792 .map_or(closure_span, |e| self.tcx.hir_span(e));
17931794let mut multi_span: MultiSpan =
1795 MultiSpan::from_spans(<[_]>::into_vec(::alloc::boxed::box_new([path_span, capture_kind_span]))vec![path_span, capture_kind_span]);
17961797let capture_kind_label =
1798 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1799let path_label = construct_path_string(self.tcx, place);
18001801 multi_span.push_span_label(path_span, path_label);
1802 multi_span.push_span_label(capture_kind_span, capture_kind_label);
18031804 diag.span_note(multi_span, output_str);
1805 } else {
1806let span = capture_info
1807 .path_expr_id
1808 .map_or(closure_span, |e| self.tcx.hir_span(e));
18091810 diag.span_note(span, output_str);
1811 };
1812 }
1813 }
1814diag.emit();
1815 }
1816 }
1817 }
18181819/// A captured place is mutable if
1820 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1821 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1822fn determine_capture_mutability(
1823&self,
1824 typeck_results: &'a TypeckResults<'tcx>,
1825 place: &Place<'tcx>,
1826 ) -> hir::Mutability {
1827let var_hir_id = match place.base {
1828 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1829_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1830 };
18311832let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
18331834let mut is_mutbl = bm.1;
18351836for pointer_ty in place.deref_tys() {
1837match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
1838// We don't capture derefs of raw ptrs
1839 ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
18401841// Dereferencing a mut-ref allows us to mut the Place if we don't deref
1842 // an immut-ref after on top of this.
1843ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
18441845// The place isn't mutable once we dereference an immutable reference.
1846ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
18471848// Dereferencing a box doesn't change mutability
1849ty::Adt(def, ..) if def.is_box() => {}
18501851 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!(
1852self.tcx.hir_span(var_hir_id),
1853"deref of unexpected pointer type {:?}",
1854 unexpected_ty
1855 ),
1856 }
1857 }
18581859is_mutbl1860 }
1861}
18621863/// Determines whether a child capture that is derived from a parent capture
1864/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1865///
1866/// There are two cases when this needs to happen:
1867///
1868/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1869/// that is the case by checking if the parent capture is by move, EXCEPT if we
1870/// apply a deref projection of an immutable reference, reborrows of immutable
1871/// references which aren't restricted to the LUB of the lifetimes of the deref
1872/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1873///
1874/// ```rust
1875/// let x = &1i32; // Let's call this lifetime `'1`.
1876/// let c = async move || {
1877/// println!("{:?}", *x);
1878/// // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1879/// // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1880/// };
1881/// ```
1882///
1883/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1884/// mutable borrow cannot live for longer than either the parent *or* the borrow
1885/// that we have on the original upvar. Therefore we always need to borrow the
1886/// child capture with the lifetime of the parent coroutine-closure's env.
1887///
1888/// ```rust
1889/// let mut x = 1i32;
1890/// let c = async || {
1891/// x = 1;
1892/// // The parent borrows `x` for some `&'1 mut i32`.
1893/// // However, when we call `c()`, we implicitly autoref for the signature of
1894/// // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1895/// // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1896/// // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1897/// };
1898/// ```
1899///
1900/// If either of these cases apply, then we should capture the borrow with the
1901/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1902/// not correct, then the program is not unsound, since we still borrowck and validate
1903/// the choices made from this function -- the only side-effect is that the user
1904/// may receive unnecessary borrowck errors.
1905fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
1906 parent_capture: &ty::CapturedPlace<'tcx>,
1907 child_capture: &ty::CapturedPlace<'tcx>,
1908) -> bool {
1909// (1.)
1910(!parent_capture.is_by_ref()
1911// This is just inlined `place.deref_tys()` but truncated to just
1912 // the child projections. Namely, look for a `&T` deref, since we
1913 // can always extend `&'short mut &'long T` to `&'long T`.
1914&& !child_capture1915 .place
1916 .projections
1917 .iter()
1918 .enumerate()
1919 .skip(parent_capture.place.projections.len())
1920 .any(|(idx, proj)| {
1921#[allow(non_exhaustive_omitted_patterns)] match proj.kind {
ProjectionKind::Deref => true,
_ => false,
}matches!(proj.kind, ProjectionKind::Deref)1922 && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
{
ty::Ref(.., ty::Mutability::Not) => true,
_ => false,
}matches!(
1923 child_capture.place.ty_before_projection(idx).kind(),
1924 ty::Ref(.., ty::Mutability::Not)
1925 )1926 }))
1927// (2.)
1928 || #[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))1929}
19301931/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1932/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1933fn restrict_repr_packed_field_ref_capture<'tcx>(
1934mut place: Place<'tcx>,
1935mut curr_borrow_kind: ty::UpvarCapture,
1936) -> (Place<'tcx>, ty::UpvarCapture) {
1937let pos = place.projections.iter().enumerate().position(|(i, p)| {
1938let ty = place.ty_before_projection(i);
19391940// Return true for fields of packed structs.
1941match p.kind {
1942 ProjectionKind::Field(..) => match ty.kind() {
1943 ty::Adt(def, _) if def.repr().packed() => {
1944// We stop here regardless of field alignment. Field alignment can change as
1945 // types change, including the types of private fields in other crates, and that
1946 // shouldn't affect how we compute our captures.
1947true
1948}
19491950_ => false,
1951 },
1952_ => false,
1953 }
1954 });
19551956if let Some(pos) = pos {
1957truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
1958 }
19591960 (place, curr_borrow_kind)
1961}
19621963/// Returns a Ty that applies the specified capture kind on the provided capture Ty
1964fn apply_capture_kind_on_capture_ty<'tcx>(
1965 tcx: TyCtxt<'tcx>,
1966 ty: Ty<'tcx>,
1967 capture_kind: UpvarCapture,
1968 region: ty::Region<'tcx>,
1969) -> Ty<'tcx> {
1970match capture_kind {
1971 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
1972 ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
1973 }
1974}
19751976/// Returns the Span of where the value with the provided HirId would be dropped
1977fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
1978let owner_id = tcx.hir_get_enclosing_scope(hir_id).unwrap();
19791980let owner_node = tcx.hir_node(owner_id);
1981let owner_span = match owner_node {
1982 hir::Node::Item(item) => match item.kind {
1983 hir::ItemKind::Fn { body: owner_id, .. } => tcx.hir_span(owner_id.hir_id),
1984_ => {
1985::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);
1986 }
1987 },
1988 hir::Node::Block(block) => tcx.hir_span(block.hir_id),
1989 hir::Node::TraitItem(item) => tcx.hir_span(item.hir_id()),
1990 hir::Node::ImplItem(item) => tcx.hir_span(item.hir_id()),
1991_ => {
1992::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);
1993 }
1994 };
1995tcx.sess.source_map().end_point(owner_span)
1996}
19971998struct InferBorrowKind<'tcx> {
1999// The def-id of the closure whose kind and upvar accesses are being inferred.
2000closure_def_id: LocalDefId,
20012002/// For each Place that is captured by the closure, we track the minimal kind of
2003 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2004 ///
2005 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2006 /// s.str2 via a MutableBorrow
2007 ///
2008 /// ```rust,no_run
2009 /// struct SomeStruct { str1: String, str2: String };
2010 ///
2011 /// // Assume that the HirId for the variable definition is `V1`
2012 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2013 ///
2014 /// let fix_s = |new_s2| {
2015 /// // Assume that the HirId for the expression `s.str1` is `E1`
2016 /// println!("Updating SomeStruct with str1={0}", s.str1);
2017 /// // Assume that the HirId for the expression `*s.str2` is `E2`
2018 /// s.str2 = new_s2;
2019 /// };
2020 /// ```
2021 ///
2022 /// For closure `fix_s`, (at a high level) the map contains
2023 ///
2024 /// ```ignore (illustrative)
2025 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2026 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2027 /// ```
2028capture_information: InferredCaptureInformation<'tcx>,
2029 fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2030}
20312032impl<'tcx> euv::Delegate<'tcx> for InferBorrowKind<'tcx> {
2033#[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(2033u32),
::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 (place, _) =
restrict_capture_precision(place_with_id.place.clone(),
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")]2034fn fake_read(
2035&mut self,
2036 place_with_id: &PlaceWithHirId<'tcx>,
2037 cause: FakeReadCause,
2038 diag_expr_id: HirId,
2039 ) {
2040let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
20412042// We need to restrict Fake Read precision to avoid fake reading unsafe code,
2043 // such as deref of a raw pointer.
2044let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
20452046let (place, _) =
2047 restrict_capture_precision(place_with_id.place.clone(), dummy_capture_kind);
20482049let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2050self.fake_reads.push((place, cause, diag_expr_id));
2051 }
20522053#[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(2053u32),
::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);
}
}
};
self.capture_information.push((place_with_id.place.clone(),
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")]2054fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2055let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2056assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
20572058self.capture_information.push((
2059 place_with_id.place.clone(),
2060 ty::CaptureInfo {
2061 capture_kind_expr_id: Some(diag_expr_id),
2062 path_expr_id: Some(diag_expr_id),
2063 capture_kind: ty::UpvarCapture::ByValue,
2064 },
2065 ));
2066 }
20672068#[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(2068u32),
::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);
}
}
};
self.capture_information.push((place_with_id.place.clone(),
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")]2069fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2070let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2071assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
20722073self.capture_information.push((
2074 place_with_id.place.clone(),
2075 ty::CaptureInfo {
2076 capture_kind_expr_id: Some(diag_expr_id),
2077 path_expr_id: Some(diag_expr_id),
2078 capture_kind: ty::UpvarCapture::ByUse,
2079 },
2080 ));
2081 }
20822083#[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(2083u32),
::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 (place, mut capture_kind) =
restrict_repr_packed_field_ref_capture(place_with_id.place.clone(),
capture_kind);
if place_with_id.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")]2084fn borrow(
2085&mut self,
2086 place_with_id: &PlaceWithHirId<'tcx>,
2087 diag_expr_id: HirId,
2088 bk: ty::BorrowKind,
2089 ) {
2090let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2091assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
20922093// The region here will get discarded/ignored
2094let capture_kind = ty::UpvarCapture::ByRef(bk);
20952096// We only want repr packed restriction to be applied to reading references into a packed
2097 // struct, and not when the data is being moved. Therefore we call this method here instead
2098 // of in `restrict_capture_precision`.
2099let (place, mut capture_kind) =
2100 restrict_repr_packed_field_ref_capture(place_with_id.place.clone(), capture_kind);
21012102// Raw pointers don't inherit mutability
2103if place_with_id.place.deref_tys().any(Ty::is_raw_ptr) {
2104 capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2105 }
21062107self.capture_information.push((
2108 place,
2109 ty::CaptureInfo {
2110 capture_kind_expr_id: Some(diag_expr_id),
2111 path_expr_id: Some(diag_expr_id),
2112 capture_kind,
2113 },
2114 ));
2115 }
21162117#[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(2117u32),
::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")]2118fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2119self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2120 }
2121}
21222123/// Rust doesn't permit moving fields out of a type that implements drop
2124x;#[instrument(skip(fcx), ret, level = "debug")]2125fn restrict_precision_for_drop_types<'a, 'tcx>(
2126 fcx: &'a FnCtxt<'a, 'tcx>,
2127mut place: Place<'tcx>,
2128mut curr_mode: ty::UpvarCapture,
2129) -> (Place<'tcx>, ty::UpvarCapture) {
2130let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
21312132if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2133for i in 0..place.projections.len() {
2134match place.ty_before_projection(i).kind() {
2135 ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2136 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2137break;
2138 }
2139_ => {}
2140 }
2141 }
2142 }
21432144 (place, curr_mode)
2145}
21462147/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2148/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2149/// them completely.
2150/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2151fn restrict_precision_for_unsafe(
2152mut place: Place<'_>,
2153mut curr_mode: ty::UpvarCapture,
2154) -> (Place<'_>, ty::UpvarCapture) {
2155if place.base_ty.is_raw_ptr() {
2156truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2157 }
21582159if place.base_ty.is_union() {
2160truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2161 }
21622163for (i, proj) in place.projections.iter().enumerate() {
2164if proj.ty.is_raw_ptr() {
2165// Don't apply any projections on top of a raw ptr.
2166truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2167break;
2168 }
21692170if proj.ty.is_union() {
2171// Don't capture precise fields of a union.
2172truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2173break;
2174 }
2175 }
21762177 (place, curr_mode)
2178}
21792180/// Truncate projections so that the following rules are obeyed by the captured `place`:
2181/// - No Index projections are captured, since arrays are captured completely.
2182/// - No unsafe block is required to capture `place`.
2183///
2184/// Returns the truncated place and updated capture mode.
2185x;#[instrument(ret, level = "debug")]2186fn restrict_capture_precision(
2187 place: Place<'_>,
2188 curr_mode: ty::UpvarCapture,
2189) -> (Place<'_>, ty::UpvarCapture) {
2190let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
21912192if place.projections.is_empty() {
2193// Nothing to do here
2194return (place, curr_mode);
2195 }
21962197for (i, proj) in place.projections.iter().enumerate() {
2198match proj.kind {
2199 ProjectionKind::Index | ProjectionKind::Subslice => {
2200// Arrays are completely captured, so we drop Index and Subslice projections
2201truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2202return (place, curr_mode);
2203 }
2204 ProjectionKind::Deref => {}
2205 ProjectionKind::OpaqueCast => {}
2206 ProjectionKind::Field(..) => {}
2207 ProjectionKind::UnwrapUnsafeBinder => {}
2208 }
2209 }
22102211 (place, curr_mode)
2212}
22132214/// Truncate deref of any reference.
2215x;#[instrument(ret, level = "debug")]2216fn adjust_for_move_closure(
2217mut place: Place<'_>,
2218mut kind: ty::UpvarCapture,
2219) -> (Place<'_>, ty::UpvarCapture) {
2220let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
22212222if let Some(idx) = first_deref {
2223 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2224 }
22252226 (place, ty::UpvarCapture::ByValue)
2227}
22282229/// Truncate deref of any reference.
2230x;#[instrument(ret, level = "debug")]2231fn adjust_for_use_closure(
2232mut place: Place<'_>,
2233mut kind: ty::UpvarCapture,
2234) -> (Place<'_>, ty::UpvarCapture) {
2235let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
22362237if let Some(idx) = first_deref {
2238 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2239 }
22402241 (place, ty::UpvarCapture::ByUse)
2242}
22432244/// Adjust closure capture just that if taking ownership of data, only move data
2245/// from enclosing stack frame.
2246x;#[instrument(ret, level = "debug")]2247fn adjust_for_non_move_closure(
2248mut place: Place<'_>,
2249mut kind: ty::UpvarCapture,
2250) -> (Place<'_>, ty::UpvarCapture) {
2251let contains_deref =
2252 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
22532254match kind {
2255 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2256if let Some(idx) = contains_deref {
2257 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2258 }
2259 }
22602261 ty::UpvarCapture::ByRef(..) => {}
2262 }
22632264 (place, kind)
2265}
22662267fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2268let variable_name = match place.base {
2269 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2270_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Capture_information should only contain upvars"))bug!("Capture_information should only contain upvars"),
2271 };
22722273let mut projections_str = String::new();
2274for (i, item) in place.projections.iter().enumerate() {
2275let proj = match item.kind {
2276 ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
})format!("({a:?}, {b:?})"),
2277 ProjectionKind::Deref => String::from("Deref"),
2278 ProjectionKind::Index => String::from("Index"),
2279 ProjectionKind::Subslice => String::from("Subslice"),
2280 ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2281 ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2282 };
2283if i != 0 {
2284 projections_str.push(',');
2285 }
2286 projections_str.push_str(proj.as_str());
2287 }
22882289::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
projections_str))
})format!("{variable_name}[{projections_str}]")2290}
22912292fn construct_capture_kind_reason_string<'tcx>(
2293 tcx: TyCtxt<'_>,
2294 place: &Place<'tcx>,
2295 capture_info: &ty::CaptureInfo,
2296) -> String {
2297let place_str = construct_place_string(tcx, place);
22982299let capture_kind_str = match capture_info.capture_kind {
2300 ty::UpvarCapture::ByValue => "ByValue".into(),
2301 ty::UpvarCapture::ByUse => "ByUse".into(),
2302 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2303 };
23042305::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")2306}
23072308fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2309let place_str = construct_place_string(tcx, place);
23102311::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} used here", place_str))
})format!("{place_str} used here")2312}
23132314fn construct_capture_info_string<'tcx>(
2315 tcx: TyCtxt<'_>,
2316 place: &Place<'tcx>,
2317 capture_info: &ty::CaptureInfo,
2318) -> String {
2319let place_str = construct_place_string(tcx, place);
23202321let capture_kind_str = match capture_info.capture_kind {
2322 ty::UpvarCapture::ByValue => "ByValue".into(),
2323 ty::UpvarCapture::ByUse => "ByUse".into(),
2324 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2325 };
2326::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
capture_kind_str))
})format!("{place_str} -> {capture_kind_str}")2327}
23282329fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2330tcx.hir_name(var_hir_id)
2331}
23322333#[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(2333u32),
::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))]2334fn should_do_rust_2021_incompatible_closure_captures_analysis(
2335 tcx: TyCtxt<'_>,
2336 closure_id: HirId,
2337) -> bool {
2338if tcx.sess.at_least_rust_2021() {
2339return false;
2340 }
23412342let level = tcx
2343 .lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2344 .level;
23452346 !matches!(level, lint::Level::Allow)
2347}
23482349/// Return a two string tuple (s1, s2)
2350/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2351/// - s2: Comma separated names of the variables being migrated.
2352fn migration_suggestion_for_2229(
2353 tcx: TyCtxt<'_>,
2354 need_migrations: &[NeededMigration],
2355) -> (String, String) {
2356let need_migrations_variables = need_migrations2357 .iter()
2358 .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2359 .collect::<Vec<_>>();
23602361let migration_ref_concat =
2362need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
23632364let migration_string = if 1 == need_migrations.len() {
2365::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = {0}",
migration_ref_concat))
})format!("let _ = {migration_ref_concat}")2366 } else {
2367::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = ({0})",
migration_ref_concat))
})format!("let _ = ({migration_ref_concat})")2368 };
23692370let migrated_variables_concat =
2371need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", v))
})format!("`{v}`")).collect::<Vec<_>>().join(", ");
23722373 (migration_string, migrated_variables_concat)
2374}
23752376/// Helper function to determine if we need to escalate CaptureKind from
2377/// CaptureInfo A to B and returns the escalated CaptureInfo.
2378/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2379///
2380/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2381/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2382///
2383/// It is the caller's duty to figure out which path_expr_id to use.
2384///
2385/// If both the CaptureKind and Expression are considered to be equivalent,
2386/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2387/// expressions reported back to the user as part of diagnostics based on which appears earlier
2388/// in the closure. This can be achieved simply by calling
2389/// `determine_capture_info(existing_info, current_info)`. This works out because the
2390/// expressions that occur earlier in the closure body than the current expression are processed before.
2391/// Consider the following example
2392/// ```rust,no_run
2393/// struct Point { x: i32, y: i32 }
2394/// let mut p = Point { x: 10, y: 10 };
2395///
2396/// let c = || {
2397/// p.x += 10; // E1
2398/// // ...
2399/// // More code
2400/// // ...
2401/// p.x += 10; // E2
2402/// };
2403/// ```
2404/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2405/// and both have an expression associated, however for diagnostics we prefer reporting
2406/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2407/// would've already handled `E1`, and have an existing capture_information for it.
2408/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2409/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2410fn determine_capture_info(
2411 capture_info_a: ty::CaptureInfo,
2412 capture_info_b: ty::CaptureInfo,
2413) -> ty::CaptureInfo {
2414// If the capture kind is equivalent then, we don't need to escalate and can compare the
2415 // expressions.
2416let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2417 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2418 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2419 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2420 (ty::UpvarCapture::ByValue, _)
2421 | (ty::UpvarCapture::ByUse, _)
2422 | (ty::UpvarCapture::ByRef(_), _) => false,
2423 };
24242425if eq_capture_kind {
2426match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2427 (Some(_), _) | (None, None) => capture_info_a,
2428 (None, Some(_)) => capture_info_b,
2429 }
2430 } else {
2431// We select the CaptureKind which ranks higher based the following priority order:
2432 // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2433match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2434 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2435 | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2436::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")2437 }
2438 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2439 | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2440 | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2441capture_info_a2442 }
2443 (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2444capture_info_b2445 }
2446 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2447match (ref_a, ref_b) {
2448// Take LHS:
2449(BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2450 | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
24512452// Take RHS:
2453(BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2454 | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
24552456 (BorrowKind::Immutable, BorrowKind::Immutable)
2457 | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2458 | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2459::rustc_middle::util::bug::bug_fmt(format_args!("Expected unequal capture kinds"));bug!("Expected unequal capture kinds");
2460 }
2461 }
2462 }
2463 }
2464 }
2465}
24662467/// Truncates `place` to have up to `len` projections.
2468/// `curr_mode` is the current required capture kind for the place.
2469/// Returns the truncated `place` and the updated required capture kind.
2470///
2471/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2472/// contained `Deref` of `&mut`.
2473fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2474 place: &mut Place<'tcx>,
2475 curr_mode: &mut ty::UpvarCapture,
2476 len: usize,
2477) {
2478let 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));
24792480// If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2481 // UniqueImmBorrow
2482 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2483 // we don't need to worry about that case here.
2484match curr_mode {
2485 ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2486for i in len..place.projections.len() {
2487if place.projections[i].kind == ProjectionKind::Deref
2488 && is_mut_ref(place.ty_before_projection(i))
2489 {
2490*curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2491break;
2492 }
2493 }
2494 }
24952496 ty::UpvarCapture::ByRef(..) => {}
2497 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2498 }
24992500place.projections.truncate(len);
2501}
25022503/// Determines the Ancestry relationship of Place A relative to Place B
2504///
2505/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2506/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2507/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2508fn determine_place_ancestry_relation<'tcx>(
2509 place_a: &Place<'tcx>,
2510 place_b: &Place<'tcx>,
2511) -> PlaceAncestryRelation {
2512// If Place A and Place B don't start off from the same root variable, they are divergent.
2513if place_a.base != place_b.base {
2514return PlaceAncestryRelation::Divergent;
2515 }
25162517// Assume of length of projections_a = n
2518let projections_a = &place_a.projections;
25192520// Assume of length of projections_b = m
2521let projections_b = &place_b.projections;
25222523let same_initial_projections =
2524 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
25252526if same_initial_projections {
2527use std::cmp::Ordering;
25282529// First min(n, m) projections are the same
2530 // Select Ancestor/Descendant
2531match projections_b.len().cmp(&projections_a.len()) {
2532 Ordering::Greater => PlaceAncestryRelation::Ancestor,
2533 Ordering::Equal => PlaceAncestryRelation::SamePlace,
2534 Ordering::Less => PlaceAncestryRelation::Descendant,
2535 }
2536 } else {
2537 PlaceAncestryRelation::Divergent2538 }
2539}
25402541/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2542/// borrow checking perspective, allowing us to save us on the size of the capture.
2543///
2544///
2545/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2546/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2547/// rightmost deref of the capture if the deref is applied to a shared ref.
2548///
2549/// Reason we only drop the last deref is because of the following edge case:
2550///
2551/// ```
2552/// # struct A { field_of_a: Box<i32> }
2553/// # struct B {}
2554/// # struct C<'a>(&'a i32);
2555/// struct MyStruct<'a> {
2556/// a: &'static A,
2557/// b: B,
2558/// c: C<'a>,
2559/// }
2560///
2561/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2562/// || drop(&*m.a.field_of_a)
2563/// // Here we really do want to capture `*m.a` because that outlives `'static`
2564///
2565/// // If we capture `m`, then the closure no longer outlives `'static`
2566/// // it is constrained to `'a`
2567/// }
2568/// ```
2569x;#[instrument(ret, level = "debug")]2570fn truncate_capture_for_optimization(
2571mut place: Place<'_>,
2572mut curr_mode: ty::UpvarCapture,
2573) -> (Place<'_>, ty::UpvarCapture) {
2574let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
25752576// Find the rightmost deref (if any). All the projections that come after this
2577 // are fields or other "in-place pointer adjustments"; these refer therefore to
2578 // data owned by whatever pointer is being dereferenced here.
2579let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
25802581match idx {
2582// If that pointer is a shared reference, then we don't need those fields.
2583Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2584 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2585 }
2586None | Some(_) => {}
2587 }
25882589 (place, curr_mode)
2590}
25912592/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2593/// `span` is the span of the closure.
2594fn enable_precise_capture(span: Span) -> bool {
2595// We use span here to ensure that if the closure was generated by a macro with a different
2596 // edition.
2597span.at_least_rust_2021()
2598}