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_hir::def_id::LocalDefId;
40use rustc_hir::intravisit::{self, Visitor};
41use rustc_hir::{selfas hir, HirId, find_attr};
42use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
43use rustc_middle::mir::FakeReadCause;
44use rustc_middle::traits::ObligationCauseCode;
45use rustc_middle::ty::{
46self, BorrowKind, ClosureSizeProfileData, Ty, TyCtxt, TypeVisitableExtas _, TypeckResults,
47UpvarArgs, UpvarCapture,
48};
49use rustc_middle::{bug, span_bug};
50use rustc_session::lint;
51use rustc_span::{BytePos, Pos, Span, Symbol, sym};
52use rustc_trait_selection::infer::InferCtxtExt;
53use tracing::{debug, instrument};
5455use super::FnCtxt;
56use crate::expr_use_visitoras euv;
5758/// Describe the relationship between the paths of two places
59/// eg:
60/// - `foo` is ancestor of `foo.bar.baz`
61/// - `foo.bar.baz` is an descendant of `foo.bar`
62/// - `foo.bar` and `foo.baz` are divergent
63enum PlaceAncestryRelation {
64 Ancestor,
65 Descendant,
66 SamePlace,
67 Divergent,
68}
6970/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
71/// during capture analysis. Information in this map feeds into the minimum capture
72/// analysis pass.
73type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
7475impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
76pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
77InferBorrowKindVisitor { fcx: self }.visit_body(body);
7879// it's our job to process these.
80if !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());
81 }
82}
8384/// Intermediate format to store the hir_id pointing to the use that resulted in the
85/// corresponding place being captured and a String which contains the captured value's
86/// name (i.e: a.b.c)
87#[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)]
88enum UpvarMigrationInfo {
89/// We previously captured all of `x`, but now we capture some sub-path.
90CapturingPrecise { source_expr: Option<HirId>, var_name: String },
91 CapturingNothing {
92// where the variable appears in the closure (but is not captured)
93use_span: Span,
94 },
95}
9697/// Reasons that we might issue a migration warning.
98#[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)]
99struct MigrationWarningReason {
100/// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
101 /// in this vec, but now we don't.
102auto_traits: Vec<&'static str>,
103104/// When we used to capture `x` in its entirety, we would execute some destructors
105 /// at a different time.
106drop_order: bool,
107}
108109impl MigrationWarningReason {
110fn migration_message(&self) -> String {
111let base = "changes to closure capture in Rust 2021 will affect";
112if !self.auto_traits.is_empty() && self.drop_order {
113::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")114 } else if self.drop_order {
115::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} drop order", base))
})format!("{base} drop order")116 } else {
117::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} which traits the closure implements",
base))
})format!("{base} which traits the closure implements")118 }
119 }
120}
121122/// Intermediate format to store information needed to generate a note in the migration lint.
123struct MigrationLintNote {
124 captures_info: UpvarMigrationInfo,
125126/// reasons why migration is needed for this capture
127reason: MigrationWarningReason,
128}
129130/// Intermediate format to store the hir id of the root variable and a HashSet containing
131/// information on why the root variable should be fully captured
132struct NeededMigration {
133 var_hir_id: HirId,
134 diagnostics_info: Vec<MigrationLintNote>,
135}
136137struct InferBorrowKindVisitor<'a, 'tcx> {
138 fcx: &'a FnCtxt<'a, 'tcx>,
139}
140141impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
142fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
143match expr.kind {
144 hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
145let body = self.fcx.tcx.hir_body(body_id);
146self.visit_body(body);
147self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
148 }
149_ => {}
150 }
151152 intravisit::walk_expr(self, expr);
153 }
154155fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
156let body = self.fcx.tcx.hir_body(c.body);
157self.visit_body(body);
158 }
159}
160161impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
162/// Analysis starting point.
163#[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(163u32),
::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:301",
"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(301u32),
::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:330",
"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(330u32),
::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:492",
"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(492u32),
::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")]164fn analyze_closure(
165&self,
166 closure_hir_id: HirId,
167 span: Span,
168 body_id: hir::BodyId,
169 body: &'tcx hir::Body<'tcx>,
170mut capture_clause: hir::CaptureBy,
171 ) {
172// Extract the type of the closure.
173let ty = self.node_ty(closure_hir_id);
174let (closure_def_id, args, infer_kind) = match *ty.kind() {
175 ty::Closure(def_id, args) => {
176 (def_id, UpvarArgs::Closure(args), self.closure_kind(ty).is_none())
177 }
178 ty::CoroutineClosure(def_id, args) => {
179 (def_id, UpvarArgs::CoroutineClosure(args), self.closure_kind(ty).is_none())
180 }
181 ty::Coroutine(def_id, args) => (def_id, UpvarArgs::Coroutine(args), false),
182 ty::Error(_) => {
183// #51714: skip analysis when we have already encountered type errors
184return;
185 }
186_ => {
187span_bug!(
188 span,
189"type of closure expr {:?} is not a closure {:?}",
190 closure_hir_id,
191 ty
192 );
193 }
194 };
195let args = self.resolve_vars_if_possible(args);
196let closure_def_id = closure_def_id.expect_local();
197198assert_eq!(self.tcx.hir_body_owner_def_id(body.id()), closure_def_id);
199let mut delegate = InferBorrowKind {
200 closure_def_id,
201 capture_information: Default::default(),
202 fake_reads: Default::default(),
203 };
204205let _ = euv::ExprUseVisitor::new(
206&FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id),
207&mut delegate,
208 )
209 .consume_body(body);
210211// There are several curious situations with coroutine-closures where
212 // analysis is too aggressive with borrows when the coroutine-closure is
213 // marked `move`. Specifically:
214 //
215 // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
216 // inference, then it's still possible that we try to borrow upvars from
217 // the coroutine-closure because they are not used by the coroutine body
218 // in a way that forces a move. See the test:
219 // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
220 //
221 // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
222 // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
223 // would force the closure to `FnOnce`.
224 // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
225 //
226 // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
227 // coroutine bodies can't borrow from their parent closure. To fix this,
228 // we force the inner coroutine to also be `move`. This only matters for
229 // coroutine-closures that are `move` since otherwise they themselves will
230 // be borrowing from the outer environment, so there's no self-borrows occurring.
231if let UpvarArgs::Coroutine(..) = args
232 && let hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) =
233self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
234 && let parent_hir_id =
235self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
236 && let parent_ty = self.node_ty(parent_hir_id)
237 && let hir::CaptureBy::Value { move_kw } =
238self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
239 {
240// (1.) Closure signature inference forced this closure to `FnOnce`.
241if let Some(ty::ClosureKind::FnOnce) = self.closure_kind(parent_ty) {
242 capture_clause = hir::CaptureBy::Value { move_kw };
243 }
244// (2.) The way that the closure uses its upvars means it's `FnOnce`.
245else if self.coroutine_body_consumes_upvars(closure_def_id, body) {
246 capture_clause = hir::CaptureBy::Value { move_kw };
247 }
248 }
249250// As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
251 // to `ByRef` for the `async {}` block internal to async fns/closure. This means
252 // that we would *not* be moving all of the parameters into the async block in all cases.
253 // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
254 // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
255 //
256 // We force all of these arguments to be captured by move before we do expr use analysis.
257 //
258 // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
259 // moving all of the `LocalSource::AsyncFn` locals here.
260if let Some(hir::CoroutineKind::Desugared(
261_,
262 hir::CoroutineSource::Fn | hir::CoroutineSource::Closure,
263 )) = self.tcx.coroutine_kind(closure_def_id)
264 {
265let hir::ExprKind::Block(block, _) = body.value.kind else {
266bug!();
267 };
268for stmt in block.stmts {
269let hir::StmtKind::Let(hir::LetStmt {
270 init: Some(init),
271 source: hir::LocalSource::AsyncFn,
272 pat,
273 ..
274 }) = stmt.kind
275else {
276bug!();
277 };
278let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), _, _, _) = pat.kind
279else {
280// Complex pattern, skip the non-upvar local.
281continue;
282 };
283let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = init.kind else {
284bug!();
285 };
286let hir::def::Res::Local(local_id) = path.res else {
287bug!();
288 };
289let place = self.place_for_root_variable(closure_def_id, local_id);
290 delegate.capture_information.push((
291 place,
292 ty::CaptureInfo {
293 capture_kind_expr_id: Some(init.hir_id),
294 path_expr_id: Some(init.hir_id),
295 capture_kind: UpvarCapture::ByValue,
296 },
297 ));
298 }
299 }
300301debug!(
302"For closure={:?}, capture_information={:#?}",
303 closure_def_id, delegate.capture_information
304 );
305306self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
307308let (capture_information, closure_kind, origin) = self
309.process_collected_capture_information(capture_clause, &delegate.capture_information);
310311self.compute_min_captures(closure_def_id, capture_information, span);
312313let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
314315if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
316self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
317 }
318319let after_feature_tys = self.final_upvar_tys(closure_def_id);
320321// We now fake capture information for all variables that are mentioned within the closure
322 // We do this after handling migrations so that min_captures computes before
323if !enable_precise_capture(span) {
324let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
325326if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
327for var_hir_id in upvars.keys() {
328let place = self.place_for_root_variable(closure_def_id, *var_hir_id);
329330debug!("seed place {:?}", place);
331332let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
333let fake_info = ty::CaptureInfo {
334 capture_kind_expr_id: None,
335 path_expr_id: None,
336 capture_kind,
337 };
338339 capture_information.push((place, fake_info));
340 }
341 }
342343// This will update the min captures based on this new fake information.
344self.compute_min_captures(closure_def_id, capture_information, span);
345 }
346347let before_feature_tys = self.final_upvar_tys(closure_def_id);
348349if infer_kind {
350// Unify the (as yet unbound) type variable in the closure
351 // args with the kind we inferred.
352let closure_kind_ty = match args {
353 UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
354 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
355 UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
356 };
357self.demand_eqtype(
358 span,
359 Ty::from_closure_kind(self.tcx, closure_kind),
360 closure_kind_ty,
361 );
362363// If we have an origin, store it.
364if let Some(mut origin) = origin {
365if !enable_precise_capture(span) {
366// Without precise captures, we just capture the base and ignore
367 // the projections.
368origin.1.projections.clear()
369 }
370371self.typeck_results
372 .borrow_mut()
373 .closure_kind_origins_mut()
374 .insert(closure_hir_id, origin);
375 }
376 }
377378// For coroutine-closures, we additionally must compute the
379 // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
380 // version of the coroutine-closure's output coroutine.
381if let UpvarArgs::CoroutineClosure(args) = args
382 && !args.references_error()
383 {
384let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
385self.tcx,
386 ty::INNERMOST,
387 ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::ClosureEnv },
388 );
389390let num_args = args
391 .as_coroutine_closure()
392 .coroutine_closure_sig()
393 .skip_binder()
394 .tupled_inputs_ty
395 .tuple_fields()
396 .len();
397let typeck_results = self.typeck_results.borrow();
398399let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
400self.tcx,
401 ty::analyze_coroutine_closure_captures(
402 typeck_results.closure_min_captures_flattened(closure_def_id),
403 typeck_results
404 .closure_min_captures_flattened(
405self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
406 )
407// Skip the captures that are just moving the closure's args
408 // into the coroutine. These are always by move, and we append
409 // those later in the `CoroutineClosureSignature` helper functions.
410.skip(num_args),
411 |(_, parent_capture), (_, child_capture)| {
412// This is subtle. See documentation on function.
413let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
414 parent_capture,
415 child_capture,
416 );
417418let upvar_ty = child_capture.place.ty();
419let capture = child_capture.info.capture_kind;
420// Not all upvars are captured by ref, so use
421 // `apply_capture_kind_on_capture_ty` to ensure that we
422 // compute the right captured type.
423apply_capture_kind_on_capture_ty(
424self.tcx,
425 upvar_ty,
426 capture,
427if needs_ref {
428 closure_env_region
429 } else {
430self.tcx.lifetimes.re_erased
431 },
432 )
433 },
434 ),
435 );
436let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
437self.tcx,
438 ty::Binder::bind_with_vars(
439self.tcx.mk_fn_sig(
440 [],
441 tupled_upvars_ty_for_borrow,
442false,
443 hir::Safety::Safe,
444 rustc_abi::ExternAbi::Rust,
445 ),
446self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
447 ty::BoundRegionKind::ClosureEnv,
448 )]),
449 ),
450 );
451self.demand_eqtype(
452 span,
453 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
454 coroutine_captures_by_ref_ty,
455 );
456457// Additionally, we can now constrain the coroutine's kind type.
458 //
459 // We only do this if `infer_kind`, because if we have constrained
460 // the kind from closure signature inference, the kind inferred
461 // for the inner coroutine may actually be more restrictive.
462if infer_kind {
463let ty::Coroutine(_, coroutine_args) =
464*self.typeck_results.borrow().expr_ty(body.value).kind()
465else {
466bug!();
467 };
468self.demand_eqtype(
469 span,
470 coroutine_args.as_coroutine().kind_ty(),
471 Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
472 );
473 }
474 }
475476self.log_closure_min_capture_info(closure_def_id, span);
477478// Now that we've analyzed the closure, we know how each
479 // variable is borrowed, and we know what traits the closure
480 // implements (Fn vs FnMut etc). We now have some updates to do
481 // with that information.
482 //
483 // Note that no closure type C may have an upvar of type C
484 // (though it may reference itself via a trait object). This
485 // results from the desugaring of closures to a struct like
486 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
487 // C, then the type would have infinite size (and the
488 // inference algorithm will reject it).
489490 // Equate the type variables for the upvars with the actual types.
491let final_upvar_tys = self.final_upvar_tys(closure_def_id);
492debug!(?closure_hir_id, ?args, ?final_upvar_tys);
493494if self.tcx.features().unsized_fn_params() {
495for capture in
496self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
497 {
498if let UpvarCapture::ByValue = capture.info.capture_kind {
499self.require_type_is_sized(
500 capture.place.ty(),
501 capture.get_path_span(self.tcx),
502 ObligationCauseCode::SizedClosureCapture(closure_def_id),
503 );
504 }
505 }
506 }
507508// Build a tuple (U0..Un) of the final upvar types U0..Un
509 // and unify the upvar tuple type in the closure with it:
510let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
511self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
512513let fake_reads = delegate.fake_reads;
514515self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
516517if self.tcx.sess.opts.unstable_opts.profile_closures {
518self.typeck_results.borrow_mut().closure_size_eval.insert(
519 closure_def_id,
520 ClosureSizeProfileData {
521 before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
522 after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
523 },
524 );
525 }
526527// If we are also inferred the closure kind here,
528 // process any deferred resolutions.
529let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
530for deferred_call_resolution in deferred_call_resolutions {
531 deferred_call_resolution.resolve(&FnCtxt::new(self, self.param_env, closure_def_id));
532 }
533 }
534535/// Determines whether the body of the coroutine uses its upvars in a way that
536 /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
537 /// In a more detailed comment above, we care whether this happens, since if
538 /// this happens, we want to force the coroutine to move all of the upvars it
539 /// would've borrowed from the parent coroutine-closure.
540 ///
541 /// This only really makes sense to be called on the child coroutine of a
542 /// coroutine-closure.
543fn coroutine_body_consumes_upvars(
544&self,
545 coroutine_def_id: LocalDefId,
546 body: &'tcx hir::Body<'tcx>,
547 ) -> bool {
548// This block contains argument capturing details. Since arguments
549 // aren't upvars, we do not care about them for determining if the
550 // coroutine body actually consumes its upvars.
551let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
552else {
553::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
554 };
555// Specifically, we only care about the *real* body of the coroutine.
556 // We skip out into the drop-temps within the block of the body in order
557 // to skip over the args of the desugaring.
558let hir::ExprKind::DropTemps(body) = body.kind else {
559::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"));bug!();
560 };
561562let mut delegate = InferBorrowKind {
563 closure_def_id: coroutine_def_id,
564 capture_information: Default::default(),
565 fake_reads: Default::default(),
566 };
567568let _ = euv::ExprUseVisitor::new(
569&FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id),
570&mut delegate,
571 )
572 .consume_expr(body);
573574let (_, kind, _) = self.process_collected_capture_information(
575 hir::CaptureBy::Ref,
576&delegate.capture_information,
577 );
578579#[allow(non_exhaustive_omitted_patterns)] match kind {
ty::ClosureKind::FnOnce => true,
_ => false,
}matches!(kind, ty::ClosureKind::FnOnce)580 }
581582// Returns a list of `Ty`s for each upvar.
583fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
584self.typeck_results
585 .borrow()
586 .closure_min_captures_flattened(closure_id)
587 .map(|captured_place| {
588let upvar_ty = captured_place.place.ty();
589let capture = captured_place.info.capture_kind;
590591{
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:591",
"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(591u32),
::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);
592593apply_capture_kind_on_capture_ty(
594self.tcx,
595upvar_ty,
596capture,
597self.tcx.lifetimes.re_erased,
598 )
599 })
600 .collect()
601 }
602603/// Adjusts the closure capture information to ensure that the operations aren't unsafe,
604 /// and that the path can be captured with required capture kind (depending on use in closure,
605 /// move closure etc.)
606 ///
607 /// Returns the set of adjusted information along with the inferred closure kind and span
608 /// associated with the closure kind inference.
609 ///
610 /// Note that we *always* infer a minimal kind, even if
611 /// we don't always *use* that in the final result (i.e., sometimes
612 /// we've taken the closure kind from the expectations instead, and
613 /// for coroutines we don't even implement the closure traits
614 /// really).
615 ///
616 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
617 /// contains a `Some()` with the `Place` that caused us to do so.
618fn process_collected_capture_information(
619&self,
620 capture_clause: hir::CaptureBy,
621 capture_information: &InferredCaptureInformation<'tcx>,
622 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
623let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
624let mut origin: Option<(Span, Place<'tcx>)> = None;
625626let processed = capture_information627 .iter()
628 .cloned()
629 .map(|(place, mut capture_info)| {
630// Apply rules for safety before inferring closure kind
631let (place, capture_kind) =
632restrict_capture_precision(place, capture_info.capture_kind);
633634let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
635636let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
637self.tcx.hir_span(usage_expr)
638 } else {
639::core::panicking::panic("internal error: entered unreachable code")unreachable!()640 };
641642let updated = match capture_kind {
643 ty::UpvarCapture::ByValue => match closure_kind {
644 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
645 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
646 }
647// If closure is already FnOnce, don't update
648ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
649 },
650651 ty::UpvarCapture::ByRef(
652 ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
653 ) => {
654match closure_kind {
655 ty::ClosureKind::Fn => {
656 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
657 }
658// Don't update the origin
659ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
660 (closure_kind, origin.take())
661 }
662 }
663 }
664665_ => (closure_kind, origin.take()),
666 };
667668closure_kind = updated.0;
669origin = updated.1;
670671let (place, capture_kind) = match capture_clause {
672 hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
673 hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
674 hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
675 };
676677// This restriction needs to be applied after we have handled adjustments for `move`
678 // closures. We want to make sure any adjustment that might make us move the place into
679 // the closure gets handled.
680let (place, capture_kind) =
681restrict_precision_for_drop_types(self, place, capture_kind);
682683capture_info.capture_kind = capture_kind;
684 (place, capture_info)
685 })
686 .collect();
687688 (processed, closure_kind, origin)
689 }
690691/// Analyzes the information collected by `InferBorrowKind` to compute the min number of
692 /// Places (and corresponding capture kind) that we need to keep track of to support all
693 /// the required captured paths.
694 ///
695 ///
696 /// Note: If this function is called multiple times for the same closure, it will update
697 /// the existing min_capture map that is stored in TypeckResults.
698 ///
699 /// Eg:
700 /// ```
701 /// #[derive(Debug)]
702 /// struct Point { x: i32, y: i32 }
703 ///
704 /// let s = String::from("s"); // hir_id_s
705 /// let mut p = Point { x: 2, y: -2 }; // his_id_p
706 /// let c = || {
707 /// println!("{s:?}"); // L1
708 /// p.x += 10; // L2
709 /// println!("{}" , p.y); // L3
710 /// println!("{p:?}"); // L4
711 /// drop(s); // L5
712 /// };
713 /// ```
714 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
715 /// the lines L1..5 respectively.
716 ///
717 /// InferBorrowKind results in a structure like this:
718 ///
719 /// ```ignore (illustrative)
720 /// {
721 /// Place(base: hir_id_s, projections: [], ....) -> {
722 /// capture_kind_expr: hir_id_L5,
723 /// path_expr_id: hir_id_L5,
724 /// capture_kind: ByValue
725 /// },
726 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
727 /// capture_kind_expr: hir_id_L2,
728 /// path_expr_id: hir_id_L2,
729 /// capture_kind: ByValue
730 /// },
731 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
732 /// capture_kind_expr: hir_id_L3,
733 /// path_expr_id: hir_id_L3,
734 /// capture_kind: ByValue
735 /// },
736 /// Place(base: hir_id_p, projections: [], ...) -> {
737 /// capture_kind_expr: hir_id_L4,
738 /// path_expr_id: hir_id_L4,
739 /// capture_kind: ByValue
740 /// },
741 /// }
742 /// ```
743 ///
744 /// After the min capture analysis, we get:
745 /// ```ignore (illustrative)
746 /// {
747 /// hir_id_s -> [
748 /// Place(base: hir_id_s, projections: [], ....) -> {
749 /// capture_kind_expr: hir_id_L5,
750 /// path_expr_id: hir_id_L5,
751 /// capture_kind: ByValue
752 /// },
753 /// ],
754 /// hir_id_p -> [
755 /// Place(base: hir_id_p, projections: [], ...) -> {
756 /// capture_kind_expr: hir_id_L2,
757 /// path_expr_id: hir_id_L4,
758 /// capture_kind: ByValue
759 /// },
760 /// ],
761 /// }
762 /// ```
763#[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(763u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&["closure_def_id",
"capture_information", "closure_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_information)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if capture_information.is_empty() { return; }
let mut typeck_results = self.typeck_results.borrow_mut();
let mut root_var_min_capture_list =
typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
for (mut place, capture_info) in capture_information.into_iter() {
let var_hir_id =
match place.base {
PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
base =>
::rustc_middle::util::bug::bug_fmt(format_args!("Expected upvar, found={0:?}",
base)),
};
let var_ident = self.tcx.hir_ident(var_hir_id);
let Some(min_cap_list) =
root_var_min_capture_list.get_mut(&var_hir_id) else {
let mutability =
self.determine_capture_mutability(&typeck_results, &place);
let min_cap_list =
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ty::CapturedPlace {
var_ident,
place,
info: capture_info,
mutability,
}]));
root_var_min_capture_list.insert(var_hir_id, min_cap_list);
continue;
};
let mut descendant_found = false;
let mut updated_capture_info = capture_info;
min_cap_list.retain(|possible_descendant|
{
match determine_place_ancestry_relation(&place,
&possible_descendant.place) {
PlaceAncestryRelation::Ancestor => {
descendant_found = true;
let mut possible_descendant = possible_descendant.clone();
let backup_path_expr_id = updated_capture_info.path_expr_id;
truncate_place_to_len_and_update_capture_kind(&mut possible_descendant.place,
&mut possible_descendant.info.capture_kind,
place.projections.len());
updated_capture_info =
determine_capture_info(updated_capture_info,
possible_descendant.info);
updated_capture_info.path_expr_id = backup_path_expr_id;
false
}
_ => true,
}
});
let mut ancestor_found = false;
if !descendant_found {
for possible_ancestor in min_cap_list.iter_mut() {
match determine_place_ancestry_relation(&place,
&possible_ancestor.place) {
PlaceAncestryRelation::SamePlace => {
ancestor_found = true;
possible_ancestor.info =
determine_capture_info(possible_ancestor.info,
updated_capture_info);
break;
}
PlaceAncestryRelation::Descendant => {
ancestor_found = true;
let backup_path_expr_id =
possible_ancestor.info.path_expr_id;
truncate_place_to_len_and_update_capture_kind(&mut place,
&mut updated_capture_info.capture_kind,
possible_ancestor.place.projections.len());
possible_ancestor.info =
determine_capture_info(possible_ancestor.info,
updated_capture_info);
possible_ancestor.info.path_expr_id = backup_path_expr_id;
break;
}
_ => {}
}
}
}
if !ancestor_found {
let mutability =
self.determine_capture_mutability(&typeck_results, &place);
let captured_place =
ty::CapturedPlace {
var_ident,
place,
info: updated_capture_info,
mutability,
};
min_cap_list.push(captured_place);
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/upvar.rs:888",
"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(888u32),
::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:949",
"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(949u32),
::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))]764fn compute_min_captures(
765&self,
766 closure_def_id: LocalDefId,
767 capture_information: InferredCaptureInformation<'tcx>,
768 closure_span: Span,
769 ) {
770if capture_information.is_empty() {
771return;
772 }
773774let mut typeck_results = self.typeck_results.borrow_mut();
775776let mut root_var_min_capture_list =
777 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
778779for (mut place, capture_info) in capture_information.into_iter() {
780let var_hir_id = match place.base {
781 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
782 base => bug!("Expected upvar, found={:?}", base),
783 };
784let var_ident = self.tcx.hir_ident(var_hir_id);
785786let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
787let mutability = self.determine_capture_mutability(&typeck_results, &place);
788let min_cap_list =
789vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
790 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
791continue;
792 };
793794// Go through each entry in the current list of min_captures
795 // - if ancestor is found, update its capture kind to account for current place's
796 // capture information.
797 //
798 // - if descendant is found, remove it from the list, and update the current place's
799 // capture information to account for the descendant's capture kind.
800 //
801 // We can never be in a case where the list contains both an ancestor and a descendant
802 // Also there can only be ancestor but in case of descendants there might be
803 // multiple.
804805let mut descendant_found = false;
806let mut updated_capture_info = capture_info;
807 min_cap_list.retain(|possible_descendant| {
808match determine_place_ancestry_relation(&place, &possible_descendant.place) {
809// current place is ancestor of possible_descendant
810PlaceAncestryRelation::Ancestor => {
811 descendant_found = true;
812813let mut possible_descendant = possible_descendant.clone();
814let backup_path_expr_id = updated_capture_info.path_expr_id;
815816// Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
817 // possible change in capture mode.
818truncate_place_to_len_and_update_capture_kind(
819&mut possible_descendant.place,
820&mut possible_descendant.info.capture_kind,
821 place.projections.len(),
822 );
823824 updated_capture_info =
825 determine_capture_info(updated_capture_info, possible_descendant.info);
826827// we need to keep the ancestor's `path_expr_id`
828updated_capture_info.path_expr_id = backup_path_expr_id;
829false
830}
831832_ => true,
833 }
834 });
835836let mut ancestor_found = false;
837if !descendant_found {
838for possible_ancestor in min_cap_list.iter_mut() {
839match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
840 PlaceAncestryRelation::SamePlace => {
841 ancestor_found = true;
842 possible_ancestor.info = determine_capture_info(
843 possible_ancestor.info,
844 updated_capture_info,
845 );
846847// Only one related place will be in the list.
848break;
849 }
850// current place is descendant of possible_ancestor
851PlaceAncestryRelation::Descendant => {
852 ancestor_found = true;
853let backup_path_expr_id = possible_ancestor.info.path_expr_id;
854855// Truncate the descendant (current place) to be same as the ancestor to handle any
856 // possible change in capture mode.
857truncate_place_to_len_and_update_capture_kind(
858&mut place,
859&mut updated_capture_info.capture_kind,
860 possible_ancestor.place.projections.len(),
861 );
862863 possible_ancestor.info = determine_capture_info(
864 possible_ancestor.info,
865 updated_capture_info,
866 );
867868// we need to keep the ancestor's `path_expr_id`
869possible_ancestor.info.path_expr_id = backup_path_expr_id;
870871// Only one related place will be in the list.
872break;
873 }
874_ => {}
875 }
876 }
877 }
878879// Only need to insert when we don't have an ancestor in the existing min capture list
880if !ancestor_found {
881let mutability = self.determine_capture_mutability(&typeck_results, &place);
882let captured_place =
883 ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
884 min_cap_list.push(captured_place);
885 }
886 }
887888debug!(
889"For closure={:?}, min_captures before sorting={:?}",
890 closure_def_id, root_var_min_capture_list
891 );
892893// Now that we have the minimized list of captures, sort the captures by field id.
894 // This causes the closure to capture the upvars in the same order as the fields are
895 // declared which is also the drop order. Thus, in situations where we capture all the
896 // fields of some type, the observable drop order will remain the same as it previously
897 // was even though we're dropping each capture individually.
898 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
899 // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
900for (_, captures) in &mut root_var_min_capture_list {
901 captures.sort_by(|capture1, capture2| {
902fn is_field<'a>(p: &&Projection<'a>) -> bool {
903match p.kind {
904 ProjectionKind::Field(_, _) => true,
905 ProjectionKind::Deref
906 | ProjectionKind::OpaqueCast
907 | ProjectionKind::UnwrapUnsafeBinder => false,
908 p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
909bug!("ProjectionKind {:?} was unexpected", p)
910 }
911 }
912 }
913914// Need to sort only by Field projections, so filter away others.
915 // A previous implementation considered other projection types too
916 // but that caused ICE #118144
917let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
918let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
919920for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
921// We do not need to look at the `Projection.ty` fields here because at each
922 // step of the iteration, the projections will either be the same and therefore
923 // the types must be as well or the current projection will be different and
924 // we will return the result of comparing the field indexes.
925match (p1.kind, p2.kind) {
926 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
927// Compare only if paths are different.
928 // Otherwise continue to the next iteration
929if i1 != i2 {
930return i1.cmp(&i2);
931 }
932 }
933// Given the filter above, this arm should never be hit
934(l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
935 }
936 }
937938self.dcx().span_delayed_bug(
939 closure_span,
940format!(
941"two identical projections: ({:?}, {:?})",
942 capture1.place.projections, capture2.place.projections
943 ),
944 );
945 std::cmp::Ordering::Equal
946 });
947 }
948949debug!(
950"For closure={:?}, min_captures after sorting={:#?}",
951 closure_def_id, root_var_min_capture_list
952 );
953 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
954 }
955956/// Perform the migration analysis for RFC 2229, and emit lint
957 /// `disjoint_capture_drop_reorder` if needed.
958fn perform_2229_migration_analysis(
959&self,
960 closure_def_id: LocalDefId,
961 body_id: hir::BodyId,
962 capture_clause: hir::CaptureBy,
963 span: Span,
964 ) {
965let (need_migrations, reasons) = self.compute_2229_migrations(
966closure_def_id,
967span,
968capture_clause,
969self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
970 );
971972if !need_migrations.is_empty() {
973let (migration_string, migrated_variables_concat) =
974migration_suggestion_for_2229(self.tcx, &need_migrations);
975976let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
977let closure_head_span = self.tcx.def_span(closure_def_id);
978self.tcx.node_span_lint(
979 lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
980closure_hir_id,
981closure_head_span,
982 |lint| {
983lint.primary_message(reasons.migration_message());
984985for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
986// Labels all the usage of the captured variable and why they are responsible
987 // for migration being needed
988for lint_note in diagnostics_info.iter() {
989match &lint_note.captures_info {
990 UpvarMigrationInfo::CapturingPrecise { source_expr: Some(capture_expr_id), var_name: captured_name } => {
991let cause_span = self.tcx.hir_span(*capture_expr_id);
992 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 `{}`",
993self.tcx.hir_name(*var_hir_id),
994 captured_name,
995 ));
996 }
997 UpvarMigrationInfo::CapturingNothing { use_span } => {
998 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",
999self.tcx.hir_name(*var_hir_id),
1000 ));
1001 }
10021003_ => { }
1004 }
10051006// Add a label pointing to where a captured variable affected by drop order
1007 // is dropped
1008if lint_note.reason.drop_order {
1009let drop_location_span = drop_location_span(self.tcx, closure_hir_id);
10101011match &lint_note.captures_info {
1012 UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
1013 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",
1014self.tcx.hir_name(*var_hir_id),
1015 captured_name,
1016 ));
1017 }
1018 UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1019 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",
1020 v = self.tcx.hir_name(*var_hir_id),
1021 ));
1022 }
1023 }
1024 }
10251026// Add a label explaining why a closure no longer implements a trait
1027for &missing_trait in &lint_note.reason.auto_traits {
1028// not capturing something anymore cannot cause a trait to fail to be implemented:
1029match &lint_note.captures_info {
1030 UpvarMigrationInfo::CapturingPrecise { var_name: captured_name, .. } => {
1031let var_name = self.tcx.hir_name(*var_hir_id);
1032 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!("\
1033 in Rust 2018, this closure implements {missing_trait} \
1034 as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1035 this closure will no longer implement {missing_trait} \
1036 because `{var_name}` is not fully captured \
1037 and `{captured_name}` does not implement {missing_trait}"));
1038 }
10391040// Cannot happen: if we don't capture a variable, we impl strictly more traits
1041 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"),
1042 }
1043 }
1044 }
1045 }
10461047let 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!(
1048"add a dummy let to cause {migrated_variables_concat} to be fully captured"
1049);
10501051let closure_span = self.tcx.hir_span_with_body(closure_hir_id);
1052let mut closure_body_span = {
1053// If the body was entirely expanded from a macro
1054 // invocation, i.e. the body is not contained inside the
1055 // closure span, then we walk up the expansion until we
1056 // find the span before the expansion.
1057let s = self.tcx.hir_span_with_body(body_id.hir_id);
1058s.find_ancestor_inside(closure_span).unwrap_or(s)
1059 };
10601061if let Ok(mut s) = self.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1062if s.starts_with('$') {
1063// Looks like a macro fragment. Try to find the real block.
1064if let hir::Node::Expr(&hir::Expr {
1065 kind: hir::ExprKind::Block(block, ..), ..
1066 }) = self.tcx.hir_node(body_id.hir_id) {
1067// If the body is a block (with `{..}`), we use the span of that block.
1068 // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1069 // Since we know it's a block, we know we can insert the `let _ = ..` without
1070 // breaking the macro syntax.
1071if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(block.span) {
1072closure_body_span = block.span;
1073s = snippet;
1074 }
1075 }
1076 }
10771078let mut lines = s.lines();
1079let line1 = lines.next().unwrap_or_default();
10801081if line1.trim_end() == "{" {
1082// This is a multi-line closure with just a `{` on the first line,
1083 // so we put the `let` on its own line.
1084 // We take the indentation from the next non-empty line.
1085let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1086let indent = line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1087lint.span_suggestion(
1088closure_body_span.with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len())).shrink_to_lo(),
1089diagnostic_msg,
1090::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}{1};", indent,
migration_string))
})format!("\n{indent}{migration_string};"),
1091 Applicability::MachineApplicable,
1092 );
1093 } else if line1.starts_with('{') {
1094// This is a closure with its body wrapped in
1095 // braces, but with more than just the opening
1096 // brace on the first line. We put the `let`
1097 // directly after the `{`.
1098lint.span_suggestion(
1099closure_body_span.with_lo(closure_body_span.lo() + BytePos(1)).shrink_to_lo(),
1100diagnostic_msg,
1101::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0};", migration_string))
})format!(" {migration_string};"),
1102 Applicability::MachineApplicable,
1103 );
1104 } else {
1105// This is a closure without braces around the body.
1106 // We add braces to add the `let` before the body.
1107lint.multipart_suggestion(
1108diagnostic_msg,
1109::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(closure_body_span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{ {0}; ",
migration_string))
})), (closure_body_span.shrink_to_hi(), " }".to_string())]))vec![
1110 (closure_body_span.shrink_to_lo(), format!("{{ {migration_string}; ")),
1111 (closure_body_span.shrink_to_hi(), " }".to_string()),
1112 ],
1113 Applicability::MachineApplicable1114 );
1115 }
1116 } else {
1117lint.span_suggestion(
1118closure_span,
1119diagnostic_msg,
1120migration_string,
1121 Applicability::HasPlaceholders1122 );
1123 }
1124 },
1125 );
1126 }
1127 }
11281129/// Combines all the reasons for 2229 migrations
1130fn compute_2229_migrations_reasons(
1131&self,
1132 auto_trait_reasons: UnordSet<&'static str>,
1133 drop_order: bool,
1134 ) -> MigrationWarningReason {
1135MigrationWarningReason {
1136 auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1137drop_order,
1138 }
1139 }
11401141/// Figures out the list of root variables (and their types) that aren't completely
1142 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1143 /// differ between the root variable and the captured paths.
1144 ///
1145 /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1146 /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1147fn compute_2229_migrations_for_trait(
1148&self,
1149 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1150 var_hir_id: HirId,
1151 closure_clause: hir::CaptureBy,
1152 ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1153let auto_traits_def_id = [
1154self.tcx.lang_items().clone_trait(),
1155self.tcx.lang_items().sync_trait(),
1156self.tcx.get_diagnostic_item(sym::Send),
1157self.tcx.lang_items().unpin_trait(),
1158self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1159self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1160 ];
1161const AUTO_TRAITS: [&str; 6] =
1162 ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
11631164let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
11651166let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
11671168let ty = match closure_clause {
1169 hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1170hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1171// For non move closure the capture kind is the max capture kind of all captures
1172 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1173let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1174for capture in root_var_min_capture_list.iter() {
1175 max_capture_info = determine_capture_info(max_capture_info, capture.info);
1176 }
11771178apply_capture_kind_on_capture_ty(
1179self.tcx,
1180ty,
1181max_capture_info.capture_kind,
1182self.tcx.lifetimes.re_erased,
1183 )
1184 }
1185 };
11861187let mut obligations_should_hold = Vec::new();
1188// Checks if a root variable implements any of the auto traits
1189for check_trait in auto_traits_def_id.iter() {
1190 obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1191self.infcx
1192 .type_implements_trait(check_trait, [ty], self.param_env)
1193 .must_apply_modulo_regions()
1194 }));
1195 }
11961197let mut problematic_captures = FxIndexMap::default();
1198// Check whether captured fields also implement the trait
1199for capture in root_var_min_capture_list.iter() {
1200let ty = apply_capture_kind_on_capture_ty(
1201self.tcx,
1202 capture.place.ty(),
1203 capture.info.capture_kind,
1204self.tcx.lifetimes.re_erased,
1205 );
12061207// Checks if a capture implements any of the auto traits
1208let mut obligations_holds_for_capture = Vec::new();
1209for check_trait in auto_traits_def_id.iter() {
1210 obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1211self.infcx
1212 .type_implements_trait(check_trait, [ty], self.param_env)
1213 .must_apply_modulo_regions()
1214 }));
1215 }
12161217let mut capture_problems = UnordSet::default();
12181219// Checks if for any of the auto traits, one or more trait is implemented
1220 // by the root variable but not by the capture
1221for (idx, _) in obligations_should_hold.iter().enumerate() {
1222if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1223 capture_problems.insert(AUTO_TRAITS[idx]);
1224 }
1225 }
12261227if !capture_problems.is_empty() {
1228 problematic_captures.insert(
1229 UpvarMigrationInfo::CapturingPrecise {
1230 source_expr: capture.info.path_expr_id,
1231 var_name: capture.to_string(self.tcx),
1232 },
1233 capture_problems,
1234 );
1235 }
1236 }
1237if !problematic_captures.is_empty() {
1238return Some(problematic_captures);
1239 }
1240None1241 }
12421243/// Figures out the list of root variables (and their types) that aren't completely
1244 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1245 /// some path starting at that root variable **might** be affected.
1246 ///
1247 /// The output list would include a root variable if:
1248 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1249 /// enabled, **and**
1250 /// - It wasn't completely captured by the closure, **and**
1251 /// - One of the paths starting at this root variable, that is not captured needs Drop.
1252 ///
1253 /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1254 /// are no significant drops than None is returned
1255#[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(1255u32),
::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:1271",
"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(1271u32),
::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:1284",
"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(1284u32),
::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:1302",
"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(1302u32),
::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:1321",
"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(1321u32),
::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: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(&["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:1325",
"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(1325u32),
::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:1329",
"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(1329u32),
::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))]1256fn compute_2229_migrations_for_drop(
1257&self,
1258 closure_def_id: LocalDefId,
1259 closure_span: Span,
1260 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1261 closure_clause: hir::CaptureBy,
1262 var_hir_id: HirId,
1263 ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1264let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id));
12651266// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1267if !ty.has_significant_drop(
1268self.tcx,
1269 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1270 ) {
1271debug!("does not have significant drop");
1272return None;
1273 }
12741275let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1276// The upvar is mentioned within the closure but no path starting from it is
1277 // used. This occurs when you have (e.g.)
1278 //
1279 // ```
1280 // let x = move || {
1281 // let _ = y;
1282 // });
1283 // ```
1284debug!("no path starting from it is used");
12851286match closure_clause {
1287// Only migrate if closure is a move closure
1288hir::CaptureBy::Value { .. } => {
1289let mut diagnostics_info = FxIndexSet::default();
1290let upvars =
1291self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1292let upvar = upvars[&var_hir_id];
1293 diagnostics_info
1294 .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1295return Some(diagnostics_info);
1296 }
1297 hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1298 }
12991300return None;
1301 };
1302debug!(?root_var_min_capture_list);
13031304let mut projections_list = Vec::new();
1305let mut diagnostics_info = FxIndexSet::default();
13061307for captured_place in root_var_min_capture_list.iter() {
1308match captured_place.info.capture_kind {
1309// Only care about captures that are moved into the closure
1310ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1311 projections_list.push(captured_place.place.projections.as_slice());
1312 diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1313 source_expr: captured_place.info.path_expr_id,
1314 var_name: captured_place.to_string(self.tcx),
1315 });
1316 }
1317 ty::UpvarCapture::ByRef(..) => {}
1318 }
1319 }
13201321debug!(?projections_list);
1322debug!(?diagnostics_info);
13231324let is_moved = !projections_list.is_empty();
1325debug!(?is_moved);
13261327let is_not_completely_captured =
1328 root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1329debug!(?is_not_completely_captured);
13301331if is_moved
1332 && is_not_completely_captured
1333 && self.has_significant_drop_outside_of_captures(
1334 closure_def_id,
1335 closure_span,
1336 ty,
1337 projections_list,
1338 )
1339 {
1340return Some(diagnostics_info);
1341 }
13421343None
1344}
13451346/// Figures out the list of root variables (and their types) that aren't completely
1347 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1348 /// order of some path starting at that root variable **might** be affected or auto-traits
1349 /// differ between the root variable and the captured paths.
1350 ///
1351 /// The output list would include a root variable if:
1352 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1353 /// enabled, **and**
1354 /// - It wasn't completely captured by the closure, **and**
1355 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1356 /// - One of the paths captured does not implement all the auto-traits its root variable
1357 /// implements.
1358 ///
1359 /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1360 /// containing the reason why root variables whose HirId is contained in the vector should
1361 /// be captured
1362#[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(1362u32),
::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))]1363fn compute_2229_migrations(
1364&self,
1365 closure_def_id: LocalDefId,
1366 closure_span: Span,
1367 closure_clause: hir::CaptureBy,
1368 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1369 ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1370let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1371return (Vec::new(), MigrationWarningReason::default());
1372 };
13731374let mut need_migrations = Vec::new();
1375let mut auto_trait_migration_reasons = UnordSet::default();
1376let mut drop_migration_needed = false;
13771378// Perform auto-trait analysis
1379for (&var_hir_id, _) in upvars.iter() {
1380let mut diagnostics_info = Vec::new();
13811382let auto_trait_diagnostic = self
1383.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1384 .unwrap_or_default();
13851386let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1387.compute_2229_migrations_for_drop(
1388 closure_def_id,
1389 closure_span,
1390 min_captures,
1391 closure_clause,
1392 var_hir_id,
1393 ) {
1394 drop_migration_needed = true;
1395 diagnostics_info
1396 } else {
1397 FxIndexSet::default()
1398 };
13991400// Combine all the captures responsible for needing migrations into one IndexSet
1401let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1402for key in auto_trait_diagnostic.keys() {
1403 capture_diagnostic.insert(key.clone());
1404 }
14051406let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1407 capture_diagnostic.sort_by_cached_key(|info| match info {
1408 UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1409 (0, Some(var_name.clone()))
1410 }
1411 UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1412 });
1413for captures_info in capture_diagnostic {
1414// Get the auto trait reasons of why migration is needed because of that capture, if there are any
1415let capture_trait_reasons =
1416if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1417 reasons.clone()
1418 } else {
1419 UnordSet::default()
1420 };
14211422// Check if migration is needed because of drop reorder as a result of that capture
1423let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
14241425// Combine all the reasons of why the root variable should be captured as a result of
1426 // auto trait implementation issues
1427auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
14281429 diagnostics_info.push(MigrationLintNote {
1430 captures_info,
1431 reason: self.compute_2229_migrations_reasons(
1432 capture_trait_reasons,
1433 capture_drop_reorder_reason,
1434 ),
1435 });
1436 }
14371438if !diagnostics_info.is_empty() {
1439 need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1440 }
1441 }
1442 (
1443 need_migrations,
1444self.compute_2229_migrations_reasons(
1445 auto_trait_migration_reasons,
1446 drop_migration_needed,
1447 ),
1448 )
1449 }
14501451/// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1452 /// of a root variable and a list of captured paths starting at this root variable (expressed
1453 /// using list of `Projection` slices), it returns true if there is a path that is not
1454 /// captured starting at this root variable that implements Drop.
1455 ///
1456 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1457 /// path say P and then list of projection slices which represent the different captures moved
1458 /// into the closure starting off of P.
1459 ///
1460 /// This will make more sense with an example:
1461 ///
1462 /// ```rust,edition2021
1463 ///
1464 /// struct FancyInteger(i32); // This implements Drop
1465 ///
1466 /// struct Point { x: FancyInteger, y: FancyInteger }
1467 /// struct Color;
1468 ///
1469 /// struct Wrapper { p: Point, c: Color }
1470 ///
1471 /// fn f(w: Wrapper) {
1472 /// let c = || {
1473 /// // Closure captures w.p.x and w.c by move.
1474 /// };
1475 ///
1476 /// c();
1477 /// }
1478 /// ```
1479 ///
1480 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1481 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1482 /// therefore Drop ordering would change and we want this function to return true.
1483 ///
1484 /// Call stack to figure out if we need to migrate for `w` would look as follows:
1485 ///
1486 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1487 /// `w[c]`.
1488 /// Notation:
1489 /// - Ty(place): Type of place
1490 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1491 /// respectively.
1492 /// ```ignore (illustrative)
1493 /// (Ty(w), [ &[p, x], &[c] ])
1494 /// // |
1495 /// // ----------------------------
1496 /// // | |
1497 /// // v v
1498 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
1499 /// // | |
1500 /// // v v
1501 /// (Ty(w.p), [ &[x] ]) false
1502 /// // |
1503 /// // |
1504 /// // -------------------------------
1505 /// // | |
1506 /// // v v
1507 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
1508 /// // | |
1509 /// // v v
1510 /// false NeedsSignificantDrop(Ty(w.p.y))
1511 /// // |
1512 /// // v
1513 /// true
1514 /// ```
1515 ///
1516 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1517 /// This implies that the `w.c` is completely captured by the closure.
1518 /// Since drop for this path will be called when the closure is
1519 /// dropped we don't need to migrate for it.
1520 ///
1521 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1522 /// path wasn't captured by the closure. Also note that even
1523 /// though we didn't capture this path, the function visits it,
1524 /// which is kind of the point of this function. We then return
1525 /// if the type of `w.p.y` implements Drop, which in this case is
1526 /// true.
1527 ///
1528 /// Consider another example:
1529 ///
1530 /// ```ignore (pseudo-rust)
1531 /// struct X;
1532 /// impl Drop for X {}
1533 ///
1534 /// struct Y(X);
1535 /// impl Drop for Y {}
1536 ///
1537 /// fn foo() {
1538 /// let y = Y(X);
1539 /// let c = || move(y.0);
1540 /// }
1541 /// ```
1542 ///
1543 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1544 /// return true, because even though all paths starting at `y` are captured, `y` itself
1545 /// implements Drop which will be affected since `y` isn't completely captured.
1546fn has_significant_drop_outside_of_captures(
1547&self,
1548 closure_def_id: LocalDefId,
1549 closure_span: Span,
1550 base_path_ty: Ty<'tcx>,
1551 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1552 ) -> bool {
1553// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1554let needs_drop = |ty: Ty<'tcx>| {
1555ty.has_significant_drop(
1556self.tcx,
1557 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1558 )
1559 };
15601561let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1562let drop_trait = self.tcx.require_lang_item(hir::LangItem::Drop, closure_span);
1563self.infcx
1564 .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1565 .must_apply_modulo_regions()
1566 };
15671568let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
15691570// If there is a case where no projection is applied on top of current place
1571 // then there must be exactly one capture corresponding to such a case. Note that this
1572 // represents the case of the path being completely captured by the variable.
1573 //
1574 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1575 // capture `a.b.c`, because that violates min capture.
1576let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
15771578if !(!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));
15791580if is_completely_captured {
1581// The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1582 // when the closure is dropped.
1583return false;
1584 }
15851586if captured_by_move_projs.is_empty() {
1587return needs_drop(base_path_ty);
1588 }
15891590if is_drop_defined_for_ty {
1591// If drop is implemented for this type then we need it to be fully captured,
1592 // and we know it is not completely captured because of the previous checks.
15931594 // Note that this is a bug in the user code that will be reported by the
1595 // borrow checker, since we can't move out of drop types.
15961597 // The bug exists in the user's code pre-migration, and we don't migrate here.
1598return false;
1599 }
16001601match base_path_ty.kind() {
1602// Observations:
1603 // - `captured_by_move_projs` is not empty. Therefore we can call
1604 // `captured_by_move_projs.first().unwrap()` safely.
1605 // - All entries in `captured_by_move_projs` have at least one projection.
1606 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
16071608 // We don't capture derefs in case of move captures, which would have be applied to
1609 // access any further paths.
1610 ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1611 ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1612 ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
16131614 ty::Adt(def, args) => {
1615// Multi-variant enums are captured in entirety,
1616 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1617match (&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);
16181619// Only Field projections can be applied to a non-box Adt.
1620if !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!(
1621 captured_by_move_projs.iter().all(|projs| matches!(
1622 projs.first().unwrap().kind,
1623 ProjectionKind::Field(..)
1624 ))
1625 );
1626def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1627 |(i, field)| {
1628let paths_using_field = captured_by_move_projs1629 .iter()
1630 .filter_map(|projs| {
1631if let ProjectionKind::Field(field_idx, _) =
1632projs.first().unwrap().kind
1633 {
1634if field_idx == i { Some(&projs[1..]) } else { None }
1635 } else {
1636::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1637 }
1638 })
1639 .collect();
16401641let after_field_ty = field.ty(self.tcx, args);
1642self.has_significant_drop_outside_of_captures(
1643closure_def_id,
1644closure_span,
1645after_field_ty,
1646paths_using_field,
1647 )
1648 },
1649 )
1650 }
16511652 ty::Tuple(fields) => {
1653// Only Field projections can be applied to a tuple.
1654if !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!(
1655 captured_by_move_projs.iter().all(|projs| matches!(
1656 projs.first().unwrap().kind,
1657 ProjectionKind::Field(..)
1658 ))
1659 );
16601661fields.iter().enumerate().any(|(i, element_ty)| {
1662let paths_using_field = captured_by_move_projs1663 .iter()
1664 .filter_map(|projs| {
1665if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1666 {
1667if field_idx.index() == i { Some(&projs[1..]) } else { None }
1668 } else {
1669::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1670 }
1671 })
1672 .collect();
16731674self.has_significant_drop_outside_of_captures(
1675closure_def_id,
1676closure_span,
1677element_ty,
1678paths_using_field,
1679 )
1680 })
1681 }
16821683// Anything else would be completely captured and therefore handled already.
1684_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1685 }
1686 }
16871688fn init_capture_kind_for_place(
1689&self,
1690 place: &Place<'tcx>,
1691 capture_clause: hir::CaptureBy,
1692 ) -> ty::UpvarCapture {
1693match capture_clause {
1694// In case of a move closure if the data is accessed through a reference we
1695 // want to capture by ref to allow precise capture using reborrows.
1696 //
1697 // If the data will be moved out of this place, then the place will be truncated
1698 // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1699 //
1700 // For example:
1701 //
1702 // struct Buffer<'a> {
1703 // x: &'a String,
1704 // y: Vec<u8>,
1705 // }
1706 //
1707 // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1708 // let c = move || b.x;
1709 // drop(b);
1710 // c
1711 // }
1712 //
1713 // Even though the closure is declared as move, when we are capturing borrowed data (in
1714 // this case, *b.x) we prefer to capture by reference.
1715 // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1716 // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1717 // before, which is also an error.
1718hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1719 ty::UpvarCapture::ByValue1720 }
1721 hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1722 ty::UpvarCapture::ByUse1723 }
1724 hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1725 ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1726 }
1727 }
1728 }
17291730fn place_for_root_variable(
1731&self,
1732 closure_def_id: LocalDefId,
1733 var_hir_id: HirId,
1734 ) -> Place<'tcx> {
1735let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
17361737Place {
1738 base_ty: self.node_ty(var_hir_id),
1739 base: PlaceBase::Upvar(upvar_id),
1740 projections: Default::default(),
1741 }
1742 }
17431744fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1745self.has_rustc_attrs && {
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(closure_def_id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcCaptureAnalysis) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}.is_some()find_attr!(self.tcx, closure_def_id, RustcCaptureAnalysis)1746 }
17471748fn log_capture_analysis_first_pass(
1749&self,
1750 closure_def_id: LocalDefId,
1751 capture_information: &InferredCaptureInformation<'tcx>,
1752 closure_span: Span,
1753 ) {
1754if self.should_log_capture_analysis(closure_def_id) {
1755let mut diag =
1756self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1757for (place, capture_info) in capture_information {
1758let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1759let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
})format!("Capturing {capture_str}");
17601761let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1762 diag.span_note(span, output_str);
1763 }
1764diag.emit();
1765 }
1766 }
17671768fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1769if self.should_log_capture_analysis(closure_def_id) {
1770if let Some(min_captures) =
1771self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1772 {
1773let mut diag =
1774self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
17751776for (_, min_captures_for_var) in min_captures {
1777for capture in min_captures_for_var {
1778let place = &capture.place;
1779let capture_info = &capture.info;
17801781let capture_str =
1782 construct_capture_info_string(self.tcx, place, capture_info);
1783let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
})format!("Min Capture {capture_str}");
17841785if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1786let path_span = capture_info
1787 .path_expr_id
1788 .map_or(closure_span, |e| self.tcx.hir_span(e));
1789let capture_kind_span = capture_info
1790 .capture_kind_expr_id
1791 .map_or(closure_span, |e| self.tcx.hir_span(e));
17921793let mut multi_span: MultiSpan =
1794 MultiSpan::from_spans(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[path_span, capture_kind_span]))vec![path_span, capture_kind_span]);
17951796let capture_kind_label =
1797 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1798let path_label = construct_path_string(self.tcx, place);
17991800 multi_span.push_span_label(path_span, path_label);
1801 multi_span.push_span_label(capture_kind_span, capture_kind_label);
18021803 diag.span_note(multi_span, output_str);
1804 } else {
1805let span = capture_info
1806 .path_expr_id
1807 .map_or(closure_span, |e| self.tcx.hir_span(e));
18081809 diag.span_note(span, output_str);
1810 };
1811 }
1812 }
1813diag.emit();
1814 }
1815 }
1816 }
18171818/// A captured place is mutable if
1819 /// 1. Projections don't include a Deref of an immut-borrow, **and**
1820 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
1821fn determine_capture_mutability(
1822&self,
1823 typeck_results: &'a TypeckResults<'tcx>,
1824 place: &Place<'tcx>,
1825 ) -> hir::Mutability {
1826let var_hir_id = match place.base {
1827 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1828_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1829 };
18301831let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
18321833let mut is_mutbl = bm.1;
18341835for pointer_ty in place.deref_tys() {
1836match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
1837// We don't capture derefs of raw ptrs
1838 ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
18391840// Dereferencing a mut-ref allows us to mut the Place if we don't deref
1841 // an immut-ref after on top of this.
1842ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
18431844// The place isn't mutable once we dereference an immutable reference.
1845ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
18461847// Dereferencing a box doesn't change mutability
1848ty::Adt(def, ..) if def.is_box() => {}
18491850 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!(
1851self.tcx.hir_span(var_hir_id),
1852"deref of unexpected pointer type {:?}",
1853 unexpected_ty
1854 ),
1855 }
1856 }
18571858is_mutbl1859 }
1860}
18611862/// Determines whether a child capture that is derived from a parent capture
1863/// should be borrowed with the lifetime of the parent coroutine-closure's env.
1864///
1865/// There are two cases when this needs to happen:
1866///
1867/// (1.) Are we borrowing data owned by the parent closure? We can determine if
1868/// that is the case by checking if the parent capture is by move, EXCEPT if we
1869/// apply a deref projection of an immutable reference, reborrows of immutable
1870/// references which aren't restricted to the LUB of the lifetimes of the deref
1871/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
1872///
1873/// ```rust
1874/// let x = &1i32; // Let's call this lifetime `'1`.
1875/// let c = async move || {
1876/// println!("{:?}", *x);
1877/// // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
1878/// // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
1879/// };
1880/// ```
1881///
1882/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
1883/// mutable borrow cannot live for longer than either the parent *or* the borrow
1884/// that we have on the original upvar. Therefore we always need to borrow the
1885/// child capture with the lifetime of the parent coroutine-closure's env.
1886///
1887/// ```rust
1888/// let mut x = 1i32;
1889/// let c = async || {
1890/// x = 1;
1891/// // The parent borrows `x` for some `&'1 mut i32`.
1892/// // However, when we call `c()`, we implicitly autoref for the signature of
1893/// // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
1894/// // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
1895/// // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
1896/// };
1897/// ```
1898///
1899/// If either of these cases apply, then we should capture the borrow with the
1900/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
1901/// not correct, then the program is not unsound, since we still borrowck and validate
1902/// the choices made from this function -- the only side-effect is that the user
1903/// may receive unnecessary borrowck errors.
1904fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
1905 parent_capture: &ty::CapturedPlace<'tcx>,
1906 child_capture: &ty::CapturedPlace<'tcx>,
1907) -> bool {
1908// (1.)
1909(!parent_capture.is_by_ref()
1910// This is just inlined `place.deref_tys()` but truncated to just
1911 // the child projections. Namely, look for a `&T` deref, since we
1912 // can always extend `&'short mut &'long T` to `&'long T`.
1913&& !child_capture1914 .place
1915 .projections
1916 .iter()
1917 .enumerate()
1918 .skip(parent_capture.place.projections.len())
1919 .any(|(idx, proj)| {
1920#[allow(non_exhaustive_omitted_patterns)] match proj.kind {
ProjectionKind::Deref => true,
_ => false,
}matches!(proj.kind, ProjectionKind::Deref)1921 && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
{
ty::Ref(.., ty::Mutability::Not) => true,
_ => false,
}matches!(
1922 child_capture.place.ty_before_projection(idx).kind(),
1923 ty::Ref(.., ty::Mutability::Not)
1924 )1925 }))
1926// (2.)
1927 || #[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))1928}
19291930/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
1931/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
1932fn restrict_repr_packed_field_ref_capture<'tcx>(
1933mut place: Place<'tcx>,
1934mut curr_borrow_kind: ty::UpvarCapture,
1935) -> (Place<'tcx>, ty::UpvarCapture) {
1936let pos = place.projections.iter().enumerate().position(|(i, p)| {
1937let ty = place.ty_before_projection(i);
19381939// Return true for fields of packed structs.
1940match p.kind {
1941 ProjectionKind::Field(..) => match ty.kind() {
1942 ty::Adt(def, _) if def.repr().packed() => {
1943// We stop here regardless of field alignment. Field alignment can change as
1944 // types change, including the types of private fields in other crates, and that
1945 // shouldn't affect how we compute our captures.
1946true
1947}
19481949_ => false,
1950 },
1951_ => false,
1952 }
1953 });
19541955if let Some(pos) = pos {
1956truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
1957 }
19581959 (place, curr_borrow_kind)
1960}
19611962/// Returns a Ty that applies the specified capture kind on the provided capture Ty
1963fn apply_capture_kind_on_capture_ty<'tcx>(
1964 tcx: TyCtxt<'tcx>,
1965 ty: Ty<'tcx>,
1966 capture_kind: UpvarCapture,
1967 region: ty::Region<'tcx>,
1968) -> Ty<'tcx> {
1969match capture_kind {
1970 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
1971 ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
1972 }
1973}
19741975/// Returns the Span of where the value with the provided HirId would be dropped
1976fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
1977let owner_id = tcx.hir_get_enclosing_scope(hir_id).unwrap();
19781979let owner_node = tcx.hir_node(owner_id);
1980let owner_span = match owner_node {
1981 hir::Node::Item(item) => match item.kind {
1982 hir::ItemKind::Fn { body: owner_id, .. } => tcx.hir_span(owner_id.hir_id),
1983_ => {
1984::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);
1985 }
1986 },
1987 hir::Node::Block(block) => tcx.hir_span(block.hir_id),
1988 hir::Node::TraitItem(item) => tcx.hir_span(item.hir_id()),
1989 hir::Node::ImplItem(item) => tcx.hir_span(item.hir_id()),
1990_ => {
1991::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);
1992 }
1993 };
1994tcx.sess.source_map().end_point(owner_span)
1995}
19961997struct InferBorrowKind<'tcx> {
1998// The def-id of the closure whose kind and upvar accesses are being inferred.
1999closure_def_id: LocalDefId,
20002001/// For each Place that is captured by the closure, we track the minimal kind of
2002 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2003 ///
2004 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2005 /// s.str2 via a MutableBorrow
2006 ///
2007 /// ```rust,no_run
2008 /// struct SomeStruct { str1: String, str2: String };
2009 ///
2010 /// // Assume that the HirId for the variable definition is `V1`
2011 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2012 ///
2013 /// let fix_s = |new_s2| {
2014 /// // Assume that the HirId for the expression `s.str1` is `E1`
2015 /// println!("Updating SomeStruct with str1={0}", s.str1);
2016 /// // Assume that the HirId for the expression `*s.str2` is `E2`
2017 /// s.str2 = new_s2;
2018 /// };
2019 /// ```
2020 ///
2021 /// For closure `fix_s`, (at a high level) the map contains
2022 ///
2023 /// ```ignore (illustrative)
2024 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2025 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2026 /// ```
2027capture_information: InferredCaptureInformation<'tcx>,
2028 fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2029}
20302031impl<'tcx> euv::Delegate<'tcx> for InferBorrowKind<'tcx> {
2032#[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(2032u32),
::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")]2033fn fake_read(
2034&mut self,
2035 place_with_id: &PlaceWithHirId<'tcx>,
2036 cause: FakeReadCause,
2037 diag_expr_id: HirId,
2038 ) {
2039let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
20402041// We need to restrict Fake Read precision to avoid fake reading unsafe code,
2042 // such as deref of a raw pointer.
2043let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
20442045let (place, _) =
2046 restrict_capture_precision(place_with_id.place.clone(), dummy_capture_kind);
20472048let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2049self.fake_reads.push((place, cause, diag_expr_id));
2050 }
20512052#[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(2052u32),
::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")]2053fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2054let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2055assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
20562057self.capture_information.push((
2058 place_with_id.place.clone(),
2059 ty::CaptureInfo {
2060 capture_kind_expr_id: Some(diag_expr_id),
2061 path_expr_id: Some(diag_expr_id),
2062 capture_kind: ty::UpvarCapture::ByValue,
2063 },
2064 ));
2065 }
20662067#[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(2067u32),
::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")]2068fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2069let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2070assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
20712072self.capture_information.push((
2073 place_with_id.place.clone(),
2074 ty::CaptureInfo {
2075 capture_kind_expr_id: Some(diag_expr_id),
2076 path_expr_id: Some(diag_expr_id),
2077 capture_kind: ty::UpvarCapture::ByUse,
2078 },
2079 ));
2080 }
20812082#[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(2082u32),
::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")]2083fn borrow(
2084&mut self,
2085 place_with_id: &PlaceWithHirId<'tcx>,
2086 diag_expr_id: HirId,
2087 bk: ty::BorrowKind,
2088 ) {
2089let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2090assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
20912092// The region here will get discarded/ignored
2093let capture_kind = ty::UpvarCapture::ByRef(bk);
20942095// We only want repr packed restriction to be applied to reading references into a packed
2096 // struct, and not when the data is being moved. Therefore we call this method here instead
2097 // of in `restrict_capture_precision`.
2098let (place, mut capture_kind) =
2099 restrict_repr_packed_field_ref_capture(place_with_id.place.clone(), capture_kind);
21002101// Raw pointers don't inherit mutability
2102if place_with_id.place.deref_tys().any(Ty::is_raw_ptr) {
2103 capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2104 }
21052106self.capture_information.push((
2107 place,
2108 ty::CaptureInfo {
2109 capture_kind_expr_id: Some(diag_expr_id),
2110 path_expr_id: Some(diag_expr_id),
2111 capture_kind,
2112 },
2113 ));
2114 }
21152116#[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(2116u32),
::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")]2117fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2118self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2119 }
2120}
21212122/// Rust doesn't permit moving fields out of a type that implements drop
2123x;#[instrument(skip(fcx), ret, level = "debug")]2124fn restrict_precision_for_drop_types<'a, 'tcx>(
2125 fcx: &'a FnCtxt<'a, 'tcx>,
2126mut place: Place<'tcx>,
2127mut curr_mode: ty::UpvarCapture,
2128) -> (Place<'tcx>, ty::UpvarCapture) {
2129let is_copy_type = fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty());
21302131if let (false, UpvarCapture::ByValue) = (is_copy_type, curr_mode) {
2132for i in 0..place.projections.len() {
2133match place.ty_before_projection(i).kind() {
2134 ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2135 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2136break;
2137 }
2138_ => {}
2139 }
2140 }
2141 }
21422143 (place, curr_mode)
2144}
21452146/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2147/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2148/// them completely.
2149/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2150fn restrict_precision_for_unsafe(
2151mut place: Place<'_>,
2152mut curr_mode: ty::UpvarCapture,
2153) -> (Place<'_>, ty::UpvarCapture) {
2154if place.base_ty.is_raw_ptr() {
2155truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2156 }
21572158if place.base_ty.is_union() {
2159truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2160 }
21612162for (i, proj) in place.projections.iter().enumerate() {
2163if proj.ty.is_raw_ptr() {
2164// Don't apply any projections on top of a raw ptr.
2165truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2166break;
2167 }
21682169if proj.ty.is_union() {
2170// Don't capture precise fields of a union.
2171truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2172break;
2173 }
2174 }
21752176 (place, curr_mode)
2177}
21782179/// Truncate projections so that the following rules are obeyed by the captured `place`:
2180/// - No Index projections are captured, since arrays are captured completely.
2181/// - No unsafe block is required to capture `place`.
2182///
2183/// Returns the truncated place and updated capture mode.
2184x;#[instrument(ret, level = "debug")]2185fn restrict_capture_precision(
2186 place: Place<'_>,
2187 curr_mode: ty::UpvarCapture,
2188) -> (Place<'_>, ty::UpvarCapture) {
2189let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
21902191if place.projections.is_empty() {
2192// Nothing to do here
2193return (place, curr_mode);
2194 }
21952196for (i, proj) in place.projections.iter().enumerate() {
2197match proj.kind {
2198 ProjectionKind::Index | ProjectionKind::Subslice => {
2199// Arrays are completely captured, so we drop Index and Subslice projections
2200truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2201return (place, curr_mode);
2202 }
2203 ProjectionKind::Deref => {}
2204 ProjectionKind::OpaqueCast => {}
2205 ProjectionKind::Field(..) => {}
2206 ProjectionKind::UnwrapUnsafeBinder => {}
2207 }
2208 }
22092210 (place, curr_mode)
2211}
22122213/// Truncate deref of any reference.
2214x;#[instrument(ret, level = "debug")]2215fn adjust_for_move_closure(
2216mut place: Place<'_>,
2217mut kind: ty::UpvarCapture,
2218) -> (Place<'_>, ty::UpvarCapture) {
2219let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
22202221if let Some(idx) = first_deref {
2222 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2223 }
22242225 (place, ty::UpvarCapture::ByValue)
2226}
22272228/// Truncate deref of any reference.
2229x;#[instrument(ret, level = "debug")]2230fn adjust_for_use_closure(
2231mut place: Place<'_>,
2232mut kind: ty::UpvarCapture,
2233) -> (Place<'_>, ty::UpvarCapture) {
2234let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
22352236if let Some(idx) = first_deref {
2237 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2238 }
22392240 (place, ty::UpvarCapture::ByUse)
2241}
22422243/// Adjust closure capture just that if taking ownership of data, only move data
2244/// from enclosing stack frame.
2245x;#[instrument(ret, level = "debug")]2246fn adjust_for_non_move_closure(
2247mut place: Place<'_>,
2248mut kind: ty::UpvarCapture,
2249) -> (Place<'_>, ty::UpvarCapture) {
2250let contains_deref =
2251 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
22522253match kind {
2254 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
2255if let Some(idx) = contains_deref {
2256 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2257 }
2258 }
22592260 ty::UpvarCapture::ByRef(..) => {}
2261 }
22622263 (place, kind)
2264}
22652266fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2267let variable_name = match place.base {
2268 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2269_ => ::rustc_middle::util::bug::bug_fmt(format_args!("Capture_information should only contain upvars"))bug!("Capture_information should only contain upvars"),
2270 };
22712272let mut projections_str = String::new();
2273for (i, item) in place.projections.iter().enumerate() {
2274let proj = match item.kind {
2275 ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
})format!("({a:?}, {b:?})"),
2276 ProjectionKind::Deref => String::from("Deref"),
2277 ProjectionKind::Index => String::from("Index"),
2278 ProjectionKind::Subslice => String::from("Subslice"),
2279 ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2280 ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2281 };
2282if i != 0 {
2283 projections_str.push(',');
2284 }
2285 projections_str.push_str(proj.as_str());
2286 }
22872288::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
projections_str))
})format!("{variable_name}[{projections_str}]")2289}
22902291fn construct_capture_kind_reason_string<'tcx>(
2292 tcx: TyCtxt<'_>,
2293 place: &Place<'tcx>,
2294 capture_info: &ty::CaptureInfo,
2295) -> String {
2296let place_str = construct_place_string(tcx, place);
22972298let capture_kind_str = match capture_info.capture_kind {
2299 ty::UpvarCapture::ByValue => "ByValue".into(),
2300 ty::UpvarCapture::ByUse => "ByUse".into(),
2301 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2302 };
23032304::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")2305}
23062307fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2308let place_str = construct_place_string(tcx, place);
23092310::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} used here", place_str))
})format!("{place_str} used here")2311}
23122313fn construct_capture_info_string<'tcx>(
2314 tcx: TyCtxt<'_>,
2315 place: &Place<'tcx>,
2316 capture_info: &ty::CaptureInfo,
2317) -> String {
2318let place_str = construct_place_string(tcx, place);
23192320let capture_kind_str = match capture_info.capture_kind {
2321 ty::UpvarCapture::ByValue => "ByValue".into(),
2322 ty::UpvarCapture::ByUse => "ByUse".into(),
2323 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2324 };
2325::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
capture_kind_str))
})format!("{place_str} -> {capture_kind_str}")2326}
23272328fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2329tcx.hir_name(var_hir_id)
2330}
23312332#[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(2332u32),
::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))]2333fn should_do_rust_2021_incompatible_closure_captures_analysis(
2334 tcx: TyCtxt<'_>,
2335 closure_id: HirId,
2336) -> bool {
2337if tcx.sess.at_least_rust_2021() {
2338return false;
2339 }
23402341let level = tcx
2342 .lint_level_at_node(lint::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id)
2343 .level;
23442345 !matches!(level, lint::Level::Allow)
2346}
23472348/// Return a two string tuple (s1, s2)
2349/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2350/// - s2: Comma separated names of the variables being migrated.
2351fn migration_suggestion_for_2229(
2352 tcx: TyCtxt<'_>,
2353 need_migrations: &[NeededMigration],
2354) -> (String, String) {
2355let need_migrations_variables = need_migrations2356 .iter()
2357 .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2358 .collect::<Vec<_>>();
23592360let migration_ref_concat =
2361need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
23622363let migration_string = if 1 == need_migrations.len() {
2364::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = {0}",
migration_ref_concat))
})format!("let _ = {migration_ref_concat}")2365 } else {
2366::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = ({0})",
migration_ref_concat))
})format!("let _ = ({migration_ref_concat})")2367 };
23682369let migrated_variables_concat =
2370need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", v))
})format!("`{v}`")).collect::<Vec<_>>().join(", ");
23712372 (migration_string, migrated_variables_concat)
2373}
23742375/// Helper function to determine if we need to escalate CaptureKind from
2376/// CaptureInfo A to B and returns the escalated CaptureInfo.
2377/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2378///
2379/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2380/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2381///
2382/// It is the caller's duty to figure out which path_expr_id to use.
2383///
2384/// If both the CaptureKind and Expression are considered to be equivalent,
2385/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2386/// expressions reported back to the user as part of diagnostics based on which appears earlier
2387/// in the closure. This can be achieved simply by calling
2388/// `determine_capture_info(existing_info, current_info)`. This works out because the
2389/// expressions that occur earlier in the closure body than the current expression are processed before.
2390/// Consider the following example
2391/// ```rust,no_run
2392/// struct Point { x: i32, y: i32 }
2393/// let mut p = Point { x: 10, y: 10 };
2394///
2395/// let c = || {
2396/// p.x += 10; // E1
2397/// // ...
2398/// // More code
2399/// // ...
2400/// p.x += 10; // E2
2401/// };
2402/// ```
2403/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2404/// and both have an expression associated, however for diagnostics we prefer reporting
2405/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2406/// would've already handled `E1`, and have an existing capture_information for it.
2407/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2408/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2409fn determine_capture_info(
2410 capture_info_a: ty::CaptureInfo,
2411 capture_info_b: ty::CaptureInfo,
2412) -> ty::CaptureInfo {
2413// If the capture kind is equivalent then, we don't need to escalate and can compare the
2414 // expressions.
2415let eq_capture_kind = match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2416 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue) => true,
2417 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse) => true,
2418 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => ref_a == ref_b,
2419 (ty::UpvarCapture::ByValue, _)
2420 | (ty::UpvarCapture::ByUse, _)
2421 | (ty::UpvarCapture::ByRef(_), _) => false,
2422 };
24232424if eq_capture_kind {
2425match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2426 (Some(_), _) | (None, None) => capture_info_a,
2427 (None, Some(_)) => capture_info_b,
2428 }
2429 } else {
2430// We select the CaptureKind which ranks higher based the following priority order:
2431 // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2432match (capture_info_a.capture_kind, capture_info_b.capture_kind) {
2433 (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByValue)
2434 | (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByUse) => {
2435::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")2436 }
2437 (ty::UpvarCapture::ByValue, ty::UpvarCapture::ByValue)
2438 | (ty::UpvarCapture::ByUse, ty::UpvarCapture::ByUse)
2439 | (ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse, ty::UpvarCapture::ByRef(_)) => {
2440capture_info_a2441 }
2442 (ty::UpvarCapture::ByRef(_), ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse) => {
2443capture_info_b2444 }
2445 (ty::UpvarCapture::ByRef(ref_a), ty::UpvarCapture::ByRef(ref_b)) => {
2446match (ref_a, ref_b) {
2447// Take LHS:
2448(BorrowKind::UniqueImmutable | BorrowKind::Mutable, BorrowKind::Immutable)
2449 | (BorrowKind::Mutable, BorrowKind::UniqueImmutable) => capture_info_a,
24502451// Take RHS:
2452(BorrowKind::Immutable, BorrowKind::UniqueImmutable | BorrowKind::Mutable)
2453 | (BorrowKind::UniqueImmutable, BorrowKind::Mutable) => capture_info_b,
24542455 (BorrowKind::Immutable, BorrowKind::Immutable)
2456 | (BorrowKind::UniqueImmutable, BorrowKind::UniqueImmutable)
2457 | (BorrowKind::Mutable, BorrowKind::Mutable) => {
2458::rustc_middle::util::bug::bug_fmt(format_args!("Expected unequal capture kinds"));bug!("Expected unequal capture kinds");
2459 }
2460 }
2461 }
2462 }
2463 }
2464}
24652466/// Truncates `place` to have up to `len` projections.
2467/// `curr_mode` is the current required capture kind for the place.
2468/// Returns the truncated `place` and the updated required capture kind.
2469///
2470/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2471/// contained `Deref` of `&mut`.
2472fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2473 place: &mut Place<'tcx>,
2474 curr_mode: &mut ty::UpvarCapture,
2475 len: usize,
2476) {
2477let 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));
24782479// If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2480 // UniqueImmBorrow
2481 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2482 // we don't need to worry about that case here.
2483match curr_mode {
2484 ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2485for i in len..place.projections.len() {
2486if place.projections[i].kind == ProjectionKind::Deref
2487 && is_mut_ref(place.ty_before_projection(i))
2488 {
2489*curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2490break;
2491 }
2492 }
2493 }
24942495 ty::UpvarCapture::ByRef(..) => {}
2496 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2497 }
24982499place.projections.truncate(len);
2500}
25012502/// Determines the Ancestry relationship of Place A relative to Place B
2503///
2504/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2505/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2506/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2507fn determine_place_ancestry_relation<'tcx>(
2508 place_a: &Place<'tcx>,
2509 place_b: &Place<'tcx>,
2510) -> PlaceAncestryRelation {
2511// If Place A and Place B don't start off from the same root variable, they are divergent.
2512if place_a.base != place_b.base {
2513return PlaceAncestryRelation::Divergent;
2514 }
25152516// Assume of length of projections_a = n
2517let projections_a = &place_a.projections;
25182519// Assume of length of projections_b = m
2520let projections_b = &place_b.projections;
25212522let same_initial_projections =
2523 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
25242525if same_initial_projections {
2526use std::cmp::Ordering;
25272528// First min(n, m) projections are the same
2529 // Select Ancestor/Descendant
2530match projections_b.len().cmp(&projections_a.len()) {
2531 Ordering::Greater => PlaceAncestryRelation::Ancestor,
2532 Ordering::Equal => PlaceAncestryRelation::SamePlace,
2533 Ordering::Less => PlaceAncestryRelation::Descendant,
2534 }
2535 } else {
2536 PlaceAncestryRelation::Divergent2537 }
2538}
25392540/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2541/// borrow checking perspective, allowing us to save us on the size of the capture.
2542///
2543///
2544/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2545/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2546/// rightmost deref of the capture if the deref is applied to a shared ref.
2547///
2548/// Reason we only drop the last deref is because of the following edge case:
2549///
2550/// ```
2551/// # struct A { field_of_a: Box<i32> }
2552/// # struct B {}
2553/// # struct C<'a>(&'a i32);
2554/// struct MyStruct<'a> {
2555/// a: &'static A,
2556/// b: B,
2557/// c: C<'a>,
2558/// }
2559///
2560/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2561/// || drop(&*m.a.field_of_a)
2562/// // Here we really do want to capture `*m.a` because that outlives `'static`
2563///
2564/// // If we capture `m`, then the closure no longer outlives `'static`
2565/// // it is constrained to `'a`
2566/// }
2567/// ```
2568x;#[instrument(ret, level = "debug")]2569fn truncate_capture_for_optimization(
2570mut place: Place<'_>,
2571mut curr_mode: ty::UpvarCapture,
2572) -> (Place<'_>, ty::UpvarCapture) {
2573let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
25742575// Find the rightmost deref (if any). All the projections that come after this
2576 // are fields or other "in-place pointer adjustments"; these refer therefore to
2577 // data owned by whatever pointer is being dereferenced here.
2578let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
25792580match idx {
2581// If that pointer is a shared reference, then we don't need those fields.
2582Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2583 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2584 }
2585None | Some(_) => {}
2586 }
25872588 (place, curr_mode)
2589}
25902591/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2592/// `span` is the span of the closure.
2593fn enable_precise_capture(span: Span) -> bool {
2594// We use span here to ensure that if the closure was generated by a macro with a different
2595 // edition.
2596span.at_least_rust_2021()
2597}