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::{cmp, iter};
3435use rustc_abi::FIRST_VARIANT;
36use rustc_attr_ir::find_attr;
37use rustc_attr_ir::lang_items::LangItem;
38use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
39use rustc_data_structures::unord::{ExtendUnord, UnordSet};
40use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
41use rustc_hir::def_id::LocalDefId;
42use rustc_hir::intravisit::{self, Visitor};
43use rustc_hir::{selfas hir, HirId};
44use rustc_lint_defs::builtin::RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES;
45use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind};
46use rustc_middle::mir::FakeReadCause;
47use rustc_middle::traits::ObligationCauseCode;
48use rustc_middle::ty::{
49self, BorrowKind, ClosureSizeProfileData, Ty, TyCtxt, TypeVisitableExtas _, TypeckResults,
50Unnormalized, UpvarArgs, UpvarCapture,
51};
52use rustc_span::{BytePos, Pos, Span, Symbol, bug, span_bug, sym};
53use rustc_trait_selection::infer::InferCtxtExt;
54use tracing::{debug, instrument};
5556use super::FnCtxt;
57use crate::expr_use_visitoras euv;
58use crate::expr_use_visitor::Delegateas _;
5960/// Describe the relationship between the paths of two places
61/// eg:
62/// - `foo` is ancestor of `foo.bar.baz`
63/// - `foo.bar.baz` is an descendant of `foo.bar`
64/// - `foo.bar` and `foo.baz` are divergent
65enum PlaceAncestryRelation {
66 Ancestor,
67 Descendant,
68 SamePlace,
69 Divergent,
70}
7172/// Intermediate format to store a captured `Place` and associated `ty::CaptureInfo`
73/// during capture analysis. Information in this map feeds into the minimum capture
74/// analysis pass.
75type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>;
7677impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
78pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) {
79InferBorrowKindVisitor { fcx: self }.visit_body(body);
8081// it's our job to process these.
82if !self.deferred_call_resolutions.borrow().is_empty() {
::core::panicking::panic("assertion failed: self.deferred_call_resolutions.borrow().is_empty()")
};assert!(self.deferred_call_resolutions.borrow().is_empty());
83 }
8485pub(crate) fn infer_closure_kind_for_diagnostic(
86&self,
87 closure_def_id: LocalDefId,
88 ) -> Option<(ty::ClosureKind, Option<(Span, Place<'tcx>)>)> {
89let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
90let hir::Node::Expr(expr) = self.tcx.hir_node_by_def_id(closure_def_id) else {
91return None;
92 };
93let hir::ExprKind::Closure(&hir::Closure {
94 capture_clause,
95 body: body_id,
96 explicit_captures,
97 ..
98 }) = expr.kind
99else {
100return None;
101 };
102let body = self.tcx.hir_body(body_id);
103104// We cannot reliably infer the closure kind if there are nested closures whose
105 // captures have not yet been analyzed.
106struct HasNestedClosure(bool);
107impl<'v> Visitor<'v> for HasNestedClosure {
108fn visit_expr(&mut self, expr: &'v hir::Expr<'v>) {
109if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Closure(..) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Closure(..)) {
110self.0 = true;
111return;
112 }
113 intravisit::walk_expr(self, expr);
114 }
115 }
116let mut has_nested = HasNestedClosure(false);
117has_nested.visit_body(body);
118if has_nested.0 {
119return None;
120 }
121122let closure_fcx = FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id);
123124let mut delegate = InferBorrowKind {
125 fcx: &closure_fcx,
126closure_def_id,
127 capture_information: Default::default(),
128 fake_reads: Default::default(),
129 };
130131let _ = euv::ExprUseVisitor::new(&closure_fcx, &mut delegate).consume_body(body);
132133for capture in explicit_captures {
134let place = closure_fcx.place_for_root_variable(closure_def_id, capture.var_hir_id);
135 delegate.consume(&PlaceWithHirId { hir_id: capture.var_hir_id, place }, hir_id);
136 }
137138let (_, closure_kind, mut origin) = self139 .process_collected_capture_information(capture_clause, &delegate.capture_information);
140141// Bail out if a by-value capture has unresolved inference variables, since
142 // fallback might later resolve the type to `Copy` (making the closure `Fn`).
143if closure_kind == ty::ClosureKind::FnOnce {
144for (place, capture_info) in &delegate.capture_information {
145if #[allow(non_exhaustive_omitted_patterns)] match capture_info.capture_kind {
ty::UpvarCapture::ByValue => true,
_ => false,
}matches!(capture_info.capture_kind, ty::UpvarCapture::ByValue)146 && place.ty().has_infer()
147 {
148return None;
149 }
150 }
151 }
152153if !enable_precise_capture(expr.span) {
154if let Some((_, ref mut place)) = origin {
155place.projections.clear();
156 }
157 }
158159Some((closure_kind, origin))
160 }
161}
162163/// Intermediate format to store the hir_id pointing to the use that resulted in the
164/// corresponding place being captured and a String which contains the captured value's
165/// name (i.e: a.b.c)
166#[derive(#[automatically_derived]
impl ::core::clone::Clone for UpvarMigrationInfo {
#[inline]
fn clone(&self) -> Self {
match self {
Self::CapturingPrecise { source_expr: __self_0, var_name: __self_1
} =>
Self::CapturingPrecise {
source_expr: ::core::clone::Clone::clone(__self_0),
var_name: ::core::clone::Clone::clone(__self_1),
},
Self::CapturingNothing { use_span: __self_0 } =>
Self::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 {
Self::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),
Self::CapturingNothing { use_span: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"CapturingNothing", "use_span", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for UpvarMigrationInfo { }
#[automatically_derived]
impl ::core::cmp::PartialEq for UpvarMigrationInfo {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::CapturingPrecise {
source_expr: __self_0, var_name: __self_1 },
Self::CapturingPrecise {
source_expr: __arg1_0, var_name: __arg1_1 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(Self::CapturingNothing { use_span: __self_0 },
Self::CapturingNothing { use_span: __arg1_0 }) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for UpvarMigrationInfo {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<HirId>>;
let _: ::core::cmp::AssertParamIsEq<String>;
let _: ::core::cmp::AssertParamIsEq<Span>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for UpvarMigrationInfo {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::CapturingPrecise { source_expr: __self_0, var_name: __self_1
} => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
Self::CapturingNothing { use_span: __self_0 } =>
::core::hash::Hash::hash(__self_0, state),
}
}
}Hash)]
167enum UpvarMigrationInfo {
168/// We previously captured all of `x`, but now we capture some sub-path.
169CapturingPrecise { source_expr: Option<HirId>, var_name: String },
170 CapturingNothing {
171// where the variable appears in the closure (but is not captured)
172use_span: Span,
173 },
174}
175176/// Reasons that we might issue a migration warning.
177#[derive(#[automatically_derived]
impl ::core::clone::Clone for MigrationWarningReason {
#[inline]
fn clone(&self) -> Self {
Self {
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() -> Self {
Self {
auto_traits: ::core::default::Default::default(),
drop_order: ::core::default::Default::default(),
}
}
}Default, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MigrationWarningReason { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MigrationWarningReason {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.drop_order == other.drop_order &&
self.auto_traits == other.auto_traits
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MigrationWarningReason {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Vec<&'static str>>;
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MigrationWarningReason {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MigrationWarningReason {
#[inline]
fn cmp(&self, other: &Self) -> ::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)]
178struct MigrationWarningReason {
179/// When we used to capture `x` in its entirety, we implemented the auto-trait(s)
180 /// in this vec, but now we don't.
181auto_traits: Vec<&'static str>,
182183/// When we used to capture `x` in its entirety, we would execute some destructors
184 /// at a different time.
185drop_order: bool,
186}
187188impl MigrationWarningReason {
189fn migration_message(&self) -> String {
190let base = "changes to closure capture in Rust 2021 will affect";
191if !self.auto_traits.is_empty() && self.drop_order {
192::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")193 } else if self.drop_order {
194::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} drop order", base))
})format!("{base} drop order")195 } else {
196::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} which traits the closure implements",
base))
})format!("{base} which traits the closure implements")197 }
198 }
199}
200201/// Intermediate format to store information needed to generate a note in the migration lint.
202struct MigrationLintNote {
203 captures_info: UpvarMigrationInfo,
204205/// reasons why migration is needed for this capture
206reason: MigrationWarningReason,
207}
208209/// Intermediate format to store the hir id of the root variable and a HashSet containing
210/// information on why the root variable should be fully captured
211struct NeededMigration {
212 var_hir_id: HirId,
213 diagnostics_info: Vec<MigrationLintNote>,
214}
215216struct InferBorrowKindVisitor<'a, 'tcx> {
217 fcx: &'a FnCtxt<'a, 'tcx>,
218}
219220impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
221fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
222match expr.kind {
223 hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
224let body = self.fcx.tcx.hir_body(body_id);
225self.visit_body(body);
226self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
227 }
228_ => {}
229 }
230231 intravisit::walk_expr(self, expr);
232 }
233234fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
235let body = self.fcx.tcx.hir_body(c.body);
236self.visit_body(body);
237 }
238}
239240impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
241/// Analysis starting point.
242{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(242u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_hir_id")
}> =
::tracing::__macro_support::FieldName::new("closure_hir_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("body_id")
}> =
::tracing::__macro_support::FieldName::new("body_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("capture_clause")
}> =
::tracing::__macro_support::FieldName::new("capture_clause");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_hir_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_clause)
as &dyn ::tracing::field::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_span::macros::bug_impl(Some(span),
format_args!("type of closure expr {0:?} is not a closure {1:?}",
closure_hir_id, ty), Location::caller());
}
};
let args = self.deeply_resolve_ignoring_regions(args);
let closure_def_id = closure_def_id.expect_local();
{
match (&self.tcx.hir_body_owner_def_id(body.id()),
&closure_def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
let closure_fcx =
FnCtxt::new(self, self.tcx.param_env(closure_def_id),
closure_def_id);
let mut delegate =
InferBorrowKind {
fcx: &closure_fcx,
closure_def_id,
capture_information: Default::default(),
fake_reads: Default::default(),
};
let _ =
euv::ExprUseVisitor::new(&closure_fcx,
&mut delegate).consume_body(body);
let explicit_captures =
match self.tcx.hir_node(closure_hir_id).expect_expr().kind {
hir::ExprKind::Closure(closure) =>
closure.explicit_captures,
_ =>
::rustc_span::macros::bug_impl(None,
format_args!("expected closure expr for {0:?}",
closure_hir_id), Location::caller()),
};
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_span::macros::bug_impl(None,
format_args!("impossible case reached"),
Location::caller());
};
for stmt in block.stmts {
let hir::StmtKind::Let(hir::LetStmt {
init: Some(init), source: hir::LocalSource::AsyncFn, pat, ..
}) =
stmt.kind else {
::rustc_span::macros::bug_impl(None,
format_args!("impossible case reached"),
Location::caller());
};
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_span::macros::bug_impl(None,
format_args!("impossible case reached"),
Location::caller());
};
let hir::def::Res::Local(local_id) =
path.res else {
::rustc_span::macros::bug_impl(None,
format_args!("impossible case reached"),
Location::caller());
};
let place =
closure_fcx.place_for_root_variable(closure_def_id,
local_id);
delegate.capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(init.hir_id),
path_expr_id: Some(init.hir_id),
capture_kind: UpvarCapture::ByValue,
}));
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:390",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(390u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("For closure={0:?}, capture_information={1:#?}",
closure_def_id, delegate.capture_information) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
self.log_capture_analysis_first_pass(closure_def_id,
&delegate.capture_information, span);
let (mut capture_information, closure_kind, origin) =
self.process_collected_capture_information(capture_clause,
&delegate.capture_information);
for capture in explicit_captures {
let place =
closure_fcx.place_for_root_variable(closure_def_id,
capture.var_hir_id);
capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(closure_hir_id),
path_expr_id: Some(closure_hir_id),
capture_kind: UpvarCapture::ByValue,
}));
}
self.compute_min_captures(closure_def_id, capture_information,
span);
let closure_hir_id =
self.tcx.local_def_id_to_hir_id(closure_def_id);
if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx,
closure_hir_id) {
self.perform_2229_migration_analysis(closure_def_id, body_id,
capture_clause, span);
}
let after_feature_tys = self.final_upvar_tys(closure_def_id);
if !enable_precise_capture(span) {
let mut capture_information:
InferredCaptureInformation<'tcx> = Default::default();
if let Some(upvars) =
self.tcx.upvars_mentioned(closure_def_id) {
for var_hir_id in upvars.keys() {
let place =
closure_fcx.place_for_root_variable(closure_def_id,
*var_hir_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:435",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(435u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("seed place {0:?}",
place) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let capture_kind =
self.init_capture_kind_for_place(&place, capture_clause);
let fake_info =
ty::CaptureInfo {
capture_kind_expr_id: None,
path_expr_id: None,
capture_kind,
};
capture_information.push((place, fake_info));
}
}
self.compute_min_captures(closure_def_id, capture_information,
span);
}
let before_feature_tys = self.final_upvar_tys(closure_def_id);
if infer_kind {
let closure_kind_ty =
match args {
UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
UpvarArgs::CoroutineClosure(args) =>
args.as_coroutine_closure().kind_ty(),
UpvarArgs::Coroutine(_) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("coroutines don\'t have an inferred kind")));
}
};
self.demand_eqtype(span,
Ty::from_closure_kind(self.tcx, closure_kind),
closure_kind_ty);
if let Some(mut origin) = origin {
if !enable_precise_capture(span) {
origin.1.projections.clear()
}
self.typeck_results.borrow_mut().closure_kind_origins_mut().insert(closure_hir_id,
origin);
}
}
if let UpvarArgs::CoroutineClosure(args) = args {
if let Some(guar) = args.error_reported().err() {
self.demand_eqtype(span,
args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
Ty::new_error(self.tcx, guar));
} else {
let closure_env_region: ty::Region<'_> =
ty::Region::new_bound(self.tcx, ty::INNERMOST,
ty::BoundRegion {
var: ty::BoundVar::ZERO,
kind: ty::BoundRegionKind::ClosureEnv,
});
let num_args =
args.as_coroutine_closure().coroutine_closure_sig().skip_binder().tupled_inputs_ty.tuple_fields().len();
let typeck_results = self.typeck_results.borrow();
let tupled_upvars_ty_for_borrow =
Ty::new_tup_from_iter(self.tcx,
ty::analyze_coroutine_closure_captures(typeck_results.closure_min_captures_flattened(closure_def_id),
typeck_results.closure_min_captures_flattened(self.tcx.coroutine_for_closure(closure_def_id).expect_local()).skip(num_args),
|(_, parent_capture), (_, child_capture)|
{
let needs_ref =
should_reborrow_from_env_of_parent_coroutine_closure(parent_capture,
child_capture);
let upvar_ty = child_capture.place.ty();
let capture = child_capture.info.capture_kind;
apply_capture_kind_on_capture_ty(self.tcx, upvar_ty,
capture,
if needs_ref {
closure_env_region
} else { self.tcx.lifetimes.re_erased })
}));
let coroutine_captures_by_ref_ty =
Ty::new_fn_ptr(self.tcx,
ty::Binder::bind_with_vars(self.tcx.mk_fn_sig_safe_rust_abi([],
tupled_upvars_ty_for_borrow),
self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)])));
self.demand_eqtype(span,
args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
coroutine_captures_by_ref_ty);
if infer_kind {
let ty::Coroutine(_, coroutine_args) =
*self.typeck_results.borrow().expr_ty(body.value).kind() else {
::rustc_span::macros::bug_impl(None,
format_args!("impossible case reached"),
Location::caller());
};
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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:607",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(607u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_hir_id")
}> =
::tracing::__macro_support::FieldName::new("closure_hir_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("args")
}> =
::tracing::__macro_support::FieldName::new("args");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("final_upvar_tys")
}> =
::tracing::__macro_support::FieldName::new("final_upvar_tys");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_hir_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&final_upvar_tys)
as &dyn ::tracing::field::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")]243fn analyze_closure(
244&self,
245 closure_hir_id: HirId,
246 span: Span,
247 body_id: hir::BodyId,
248 body: &'tcx hir::Body<'tcx>,
249mut capture_clause: hir::CaptureBy,
250 ) {
251// Extract the type of the closure.
252let ty = self.node_ty(closure_hir_id);
253let (closure_def_id, args, infer_kind) = match *ty.kind() {
254 ty::Closure(def_id, args) => {
255 (def_id, UpvarArgs::Closure(args), self.closure_kind(ty).is_none())
256 }
257 ty::CoroutineClosure(def_id, args) => {
258 (def_id, UpvarArgs::CoroutineClosure(args), self.closure_kind(ty).is_none())
259 }
260 ty::Coroutine(def_id, args) => (def_id, UpvarArgs::Coroutine(args), false),
261 ty::Error(_) => {
262// #51714: skip analysis when we have already encountered type errors
263return;
264 }
265_ => {
266span_bug!(
267 span,
268"type of closure expr {:?} is not a closure {:?}",
269 closure_hir_id,
270 ty
271 );
272 }
273 };
274let args = self.deeply_resolve_ignoring_regions(args);
275let closure_def_id = closure_def_id.expect_local();
276277assert_eq!(self.tcx.hir_body_owner_def_id(body.id()), closure_def_id);
278279let closure_fcx = FnCtxt::new(self, self.tcx.param_env(closure_def_id), closure_def_id);
280281let mut delegate = InferBorrowKind {
282 fcx: &closure_fcx,
283 closure_def_id,
284 capture_information: Default::default(),
285 fake_reads: Default::default(),
286 };
287288// First collect the captures implied by the operations in the closure
289 // body. This records how each place is actually used: borrowed, modified,
290 // moved, and so on.
291let _ = euv::ExprUseVisitor::new(&closure_fcx, &mut delegate).consume_body(body);
292293// Save the captures that must be upgraded to by-value after inferring
294 // the closure kind from the operations in the body.
295let explicit_captures = match self.tcx.hir_node(closure_hir_id).expect_expr().kind {
296 hir::ExprKind::Closure(closure) => closure.explicit_captures,
297_ => bug!("expected closure expr for {:?}", closure_hir_id),
298 };
299300// There are several curious situations with coroutine-closures where
301 // analysis is too aggressive with borrows when the coroutine-closure is
302 // marked `move`. Specifically:
303 //
304 // 1. If the coroutine-closure was inferred to be `FnOnce` during signature
305 // inference, then it's still possible that we try to borrow upvars from
306 // the coroutine-closure because they are not used by the coroutine body
307 // in a way that forces a move. See the test:
308 // `async-await/async-closures/force-move-due-to-inferred-kind.rs`.
309 //
310 // 2. If the coroutine-closure is forced to be `FnOnce` due to the way it
311 // uses its upvars (e.g. it consumes a non-copy value), but not *all* upvars
312 // would force the closure to `FnOnce`.
313 // See the test: `async-await/async-closures/force-move-due-to-actually-fnonce.rs`.
314 //
315 // This would lead to an impossible to satisfy situation, since `AsyncFnOnce`
316 // coroutine bodies can't borrow from their parent closure. To fix this,
317 // we force the inner coroutine to also be `move`. This only matters for
318 // coroutine-closures that are `move` since otherwise they themselves will
319 // be borrowing from the outer environment, so there's no self-borrows occurring.
320if let UpvarArgs::Coroutine(..) = args
321 && let hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure) =
322self.tcx.coroutine_kind(closure_def_id).expect("coroutine should have kind")
323 && let parent_hir_id =
324self.tcx.local_def_id_to_hir_id(self.tcx.local_parent(closure_def_id))
325 && let parent_ty = self.node_ty(parent_hir_id)
326 && let hir::CaptureBy::Value { move_kw } =
327self.tcx.hir_node(parent_hir_id).expect_closure().capture_clause
328 {
329// (1.) Closure signature inference forced this closure to `FnOnce`.
330if let Some(ty::ClosureKind::FnOnce) = self.closure_kind(parent_ty) {
331 capture_clause = hir::CaptureBy::Value { move_kw };
332 }
333// (2.) The way that the closure uses its upvars means it's `FnOnce`.
334else if self.coroutine_body_consumes_upvars(closure_def_id, body) {
335 capture_clause = hir::CaptureBy::Value { move_kw };
336 }
337 }
338339// As noted in `lower_coroutine_body_with_moved_arguments`, we default the capture mode
340 // to `ByRef` for the `async {}` block internal to async fns/closure. This means
341 // that we would *not* be moving all of the parameters into the async block in all cases.
342 // For example, when one of the arguments is `Copy`, we turn a consuming use into a copy of
343 // a reference, so for `async fn x(t: i32) {}`, we'd only take a reference to `t`.
344 //
345 // We force all of these arguments to be captured by move before we do expr use analysis.
346 //
347 // FIXME(async_closures): This could be cleaned up. It's a bit janky that we're just
348 // moving all of the `LocalSource::AsyncFn` locals here.
349if let Some(hir::CoroutineKind::Desugared(
350_,
351 hir::CoroutineSource::Fn | hir::CoroutineSource::Closure,
352 )) = self.tcx.coroutine_kind(closure_def_id)
353 {
354let hir::ExprKind::Block(block, _) = body.value.kind else {
355bug!();
356 };
357for stmt in block.stmts {
358let hir::StmtKind::Let(hir::LetStmt {
359 init: Some(init),
360 source: hir::LocalSource::AsyncFn,
361 pat,
362 ..
363 }) = stmt.kind
364else {
365bug!();
366 };
367let hir::PatKind::Binding(hir::BindingMode(hir::ByRef::No, _), _, _, _) = pat.kind
368else {
369// Complex pattern, skip the non-upvar local.
370continue;
371 };
372let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = init.kind else {
373bug!();
374 };
375let hir::def::Res::Local(local_id) = path.res else {
376bug!();
377 };
378let place = closure_fcx.place_for_root_variable(closure_def_id, local_id);
379 delegate.capture_information.push((
380 place,
381 ty::CaptureInfo {
382 capture_kind_expr_id: Some(init.hir_id),
383 path_expr_id: Some(init.hir_id),
384 capture_kind: UpvarCapture::ByValue,
385 },
386 ));
387 }
388 }
389390debug!(
391"For closure={:?}, capture_information={:#?}",
392 closure_def_id, delegate.capture_information
393 );
394395self.log_capture_analysis_first_pass(closure_def_id, &delegate.capture_information, span);
396397let (mut capture_information, closure_kind, origin) = self
398.process_collected_capture_information(capture_clause, &delegate.capture_information);
399400// `move(expr)` requires its synthetic local to be captured by value,
401 // regardless of how the closure body uses it. Apply that requirement
402 // after closure-kind inference so capturing a value does not by itself
403 // make the closure `FnOnce`.
404for capture in explicit_captures {
405let place = closure_fcx.place_for_root_variable(closure_def_id, capture.var_hir_id);
406 capture_information.push((
407 place,
408 ty::CaptureInfo {
409 capture_kind_expr_id: Some(closure_hir_id),
410 path_expr_id: Some(closure_hir_id),
411 capture_kind: UpvarCapture::ByValue,
412 },
413 ));
414 }
415416self.compute_min_captures(closure_def_id, capture_information, span);
417418let closure_hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id);
419420if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) {
421self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span);
422 }
423424let after_feature_tys = self.final_upvar_tys(closure_def_id);
425426// We now fake capture information for all variables that are mentioned within the closure
427 // We do this after handling migrations so that min_captures computes before
428if !enable_precise_capture(span) {
429let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();
430431if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
432for var_hir_id in upvars.keys() {
433let place = closure_fcx.place_for_root_variable(closure_def_id, *var_hir_id);
434435debug!("seed place {:?}", place);
436437let capture_kind = self.init_capture_kind_for_place(&place, capture_clause);
438let fake_info = ty::CaptureInfo {
439 capture_kind_expr_id: None,
440 path_expr_id: None,
441 capture_kind,
442 };
443444 capture_information.push((place, fake_info));
445 }
446 }
447448// This will update the min captures based on this new fake information.
449self.compute_min_captures(closure_def_id, capture_information, span);
450 }
451452let before_feature_tys = self.final_upvar_tys(closure_def_id);
453454if infer_kind {
455// Unify the (as yet unbound) type variable in the closure
456 // args with the kind we inferred.
457let closure_kind_ty = match args {
458 UpvarArgs::Closure(args) => args.as_closure().kind_ty(),
459 UpvarArgs::CoroutineClosure(args) => args.as_coroutine_closure().kind_ty(),
460 UpvarArgs::Coroutine(_) => unreachable!("coroutines don't have an inferred kind"),
461 };
462self.demand_eqtype(
463 span,
464 Ty::from_closure_kind(self.tcx, closure_kind),
465 closure_kind_ty,
466 );
467468// If we have an origin, store it.
469if let Some(mut origin) = origin {
470if !enable_precise_capture(span) {
471// Without precise captures, we just capture the base and ignore
472 // the projections.
473origin.1.projections.clear()
474 }
475476self.typeck_results
477 .borrow_mut()
478 .closure_kind_origins_mut()
479 .insert(closure_hir_id, origin);
480 }
481 }
482483// For coroutine-closures, we additionally must compute the
484 // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref
485 // version of the coroutine-closure's output coroutine.
486 //
487 // If the args already reference an error, computing the by-ref upvar
488 // tuple may itself reach malformed types. We still equate the
489 // `coroutine_captures_by_ref_ty` inference variable to an error type
490 // so downstream consumers (e.g. `has_self_borrows`) can rely on it
491 // being resolved to either an `FnPtr` or `Error` rather than remaining
492 // an unconstrained inference variable.
493if let UpvarArgs::CoroutineClosure(args) = args {
494if let Some(guar) = args.error_reported().err() {
495self.demand_eqtype(
496 span,
497 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
498 Ty::new_error(self.tcx, guar),
499 );
500 } else {
501let closure_env_region: ty::Region<'_> = ty::Region::new_bound(
502self.tcx,
503 ty::INNERMOST,
504 ty::BoundRegion {
505 var: ty::BoundVar::ZERO,
506 kind: ty::BoundRegionKind::ClosureEnv,
507 },
508 );
509510let num_args = args
511 .as_coroutine_closure()
512 .coroutine_closure_sig()
513 .skip_binder()
514 .tupled_inputs_ty
515 .tuple_fields()
516 .len();
517let typeck_results = self.typeck_results.borrow();
518519let tupled_upvars_ty_for_borrow = Ty::new_tup_from_iter(
520self.tcx,
521 ty::analyze_coroutine_closure_captures(
522 typeck_results.closure_min_captures_flattened(closure_def_id),
523 typeck_results
524 .closure_min_captures_flattened(
525self.tcx.coroutine_for_closure(closure_def_id).expect_local(),
526 )
527// Skip the captures that are just moving the closure's args
528 // into the coroutine. These are always by move, and we append
529 // those later in the `CoroutineClosureSignature` helper functions.
530.skip(num_args),
531 |(_, parent_capture), (_, child_capture)| {
532// This is subtle. See documentation on function.
533let needs_ref = should_reborrow_from_env_of_parent_coroutine_closure(
534 parent_capture,
535 child_capture,
536 );
537538let upvar_ty = child_capture.place.ty();
539let capture = child_capture.info.capture_kind;
540// Not all upvars are captured by ref, so use
541 // `apply_capture_kind_on_capture_ty` to ensure that we
542 // compute the right captured type.
543apply_capture_kind_on_capture_ty(
544self.tcx,
545 upvar_ty,
546 capture,
547if needs_ref {
548 closure_env_region
549 } else {
550self.tcx.lifetimes.re_erased
551 },
552 )
553 },
554 ),
555 );
556let coroutine_captures_by_ref_ty = Ty::new_fn_ptr(
557self.tcx,
558 ty::Binder::bind_with_vars(
559self.tcx.mk_fn_sig_safe_rust_abi([], tupled_upvars_ty_for_borrow),
560self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(
561 ty::BoundRegionKind::ClosureEnv,
562 )]),
563 ),
564 );
565self.demand_eqtype(
566 span,
567 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
568 coroutine_captures_by_ref_ty,
569 );
570571// Additionally, we can now constrain the coroutine's kind type.
572 //
573 // We only do this if `infer_kind`, because if we have constrained
574 // the kind from closure signature inference, the kind inferred
575 // for the inner coroutine may actually be more restrictive.
576if infer_kind {
577let ty::Coroutine(_, coroutine_args) =
578*self.typeck_results.borrow().expr_ty(body.value).kind()
579else {
580bug!();
581 };
582self.demand_eqtype(
583 span,
584 coroutine_args.as_coroutine().kind_ty(),
585 Ty::from_coroutine_closure_kind(self.tcx, closure_kind),
586 );
587 }
588 }
589 }
590591self.log_closure_min_capture_info(closure_def_id, span);
592593// Now that we've analyzed the closure, we know how each
594 // variable is borrowed, and we know what traits the closure
595 // implements (Fn vs FnMut etc). We now have some updates to do
596 // with that information.
597 //
598 // Note that no closure type C may have an upvar of type C
599 // (though it may reference itself via a trait object). This
600 // results from the desugaring of closures to a struct like
601 // `Foo<..., UV0...UVn>`. If one of those upvars referenced
602 // C, then the type would have infinite size (and the
603 // inference algorithm will reject it).
604605 // Equate the type variables for the upvars with the actual types.
606let final_upvar_tys = self.final_upvar_tys(closure_def_id);
607debug!(?closure_hir_id, ?args, ?final_upvar_tys);
608609if self.tcx.features().unsized_fn_params() {
610for capture in
611self.typeck_results.borrow().closure_min_captures_flattened(closure_def_id)
612 {
613if let UpvarCapture::ByValue = capture.info.capture_kind {
614self.require_type_is_sized(
615 capture.place.ty(),
616 capture.get_path_span(self.tcx),
617 ObligationCauseCode::SizedClosureCapture(closure_def_id),
618 );
619 }
620 }
621 }
622623// Build a tuple (U0..Un) of the final upvar types U0..Un
624 // and unify the upvar tuple type in the closure with it:
625let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys);
626self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type);
627628let fake_reads = delegate.fake_reads;
629630self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads);
631632if self.tcx.sess.opts.unstable_opts.profile_closures {
633self.typeck_results.borrow_mut().closure_size_eval.insert(
634 closure_def_id,
635 ClosureSizeProfileData {
636 before_feature_tys: Ty::new_tup(self.tcx, &before_feature_tys),
637 after_feature_tys: Ty::new_tup(self.tcx, &after_feature_tys),
638 },
639 );
640 }
641642// If we are also inferred the closure kind here,
643 // process any deferred resolutions.
644let deferred_call_resolutions = self.remove_deferred_call_resolutions(closure_def_id);
645for deferred_call_resolution in deferred_call_resolutions {
646 deferred_call_resolution.resolve(&FnCtxt::new(self, self.param_env, closure_def_id));
647 }
648 }
649650/// Determines whether the body of the coroutine uses its upvars in a way that
651 /// consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`.
652 /// In a more detailed comment above, we care whether this happens, since if
653 /// this happens, we want to force the coroutine to move all of the upvars it
654 /// would've borrowed from the parent coroutine-closure.
655 ///
656 /// This only really makes sense to be called on the child coroutine of a
657 /// coroutine-closure.
658fn coroutine_body_consumes_upvars(
659&self,
660 coroutine_def_id: LocalDefId,
661 body: &'tcx hir::Body<'tcx>,
662 ) -> bool {
663// This block contains argument capturing details. Since arguments
664 // aren't upvars, we do not care about them for determining if the
665 // coroutine body actually consumes its upvars.
666let hir::ExprKind::Block(&hir::Block { expr: Some(body), .. }, None) = body.value.kind
667else {
668::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller());bug!();
669 };
670// Specifically, we only care about the *real* body of the coroutine.
671 // We skip out into the drop-temps within the block of the body in order
672 // to skip over the args of the desugaring.
673let hir::ExprKind::DropTemps(body) = body.kind else {
674::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller());bug!();
675 };
676677let coroutine_fcx =
678FnCtxt::new(self, self.tcx.param_env(coroutine_def_id), coroutine_def_id);
679680let mut delegate = InferBorrowKind {
681 fcx: &coroutine_fcx,
682 closure_def_id: coroutine_def_id,
683 capture_information: Default::default(),
684 fake_reads: Default::default(),
685 };
686687let _ = euv::ExprUseVisitor::new(&coroutine_fcx, &mut delegate).consume_expr(body);
688689let (_, kind, _) = self.process_collected_capture_information(
690 hir::CaptureBy::Ref,
691&delegate.capture_information,
692 );
693694#[allow(non_exhaustive_omitted_patterns)] match kind {
ty::ClosureKind::FnOnce => true,
_ => false,
}matches!(kind, ty::ClosureKind::FnOnce)695 }
696697// Returns a list of `Ty`s for each upvar.
698fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>> {
699self.typeck_results
700 .borrow()
701 .closure_min_captures_flattened(closure_id)
702 .map(|captured_place| {
703let upvar_ty = captured_place.place.ty();
704let capture = captured_place.info.capture_kind;
705706{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:706",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(706u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("captured_place.place")
}> =
::tracing::__macro_support::FieldName::new("captured_place.place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("upvar_ty")
}> =
::tracing::__macro_support::FieldName::new("upvar_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("capture")
}> =
::tracing::__macro_support::FieldName::new("capture");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("captured_place.mutability")
}> =
::tracing::__macro_support::FieldName::new("captured_place.mutability");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&captured_place.place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&upvar_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&captured_place.mutability)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?captured_place.place, ?upvar_ty, ?capture, ?captured_place.mutability);
707708apply_capture_kind_on_capture_ty(
709self.tcx,
710upvar_ty,
711capture,
712self.tcx.lifetimes.re_erased,
713 )
714 })
715 .collect()
716 }
717718/// Adjusts the closure capture information to ensure that the operations aren't unsafe,
719 /// and that the path can be captured with required capture kind (depending on use in closure,
720 /// move closure etc.)
721 ///
722 /// Returns the set of adjusted information along with the inferred closure kind and span
723 /// associated with the closure kind inference.
724 ///
725 /// Note that we *always* infer a minimal kind, even if
726 /// we don't always *use* that in the final result (i.e., sometimes
727 /// we've taken the closure kind from the expectations instead, and
728 /// for coroutines we don't even implement the closure traits
729 /// really).
730 ///
731 /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple
732 /// contains a `Some()` with the `Place` that caused us to do so.
733fn process_collected_capture_information(
734&self,
735 capture_clause: hir::CaptureBy,
736 capture_information: &InferredCaptureInformation<'tcx>,
737 ) -> (InferredCaptureInformation<'tcx>, ty::ClosureKind, Option<(Span, Place<'tcx>)>) {
738let mut closure_kind = ty::ClosureKind::LATTICE_BOTTOM;
739let mut origin: Option<(Span, Place<'tcx>)> = None;
740741let processed = capture_information742 .iter()
743 .cloned()
744 .map(|(place, mut capture_info)| {
745// Apply rules for safety before inferring closure kind
746let (place, capture_kind) =
747restrict_capture_precision(place, capture_info.capture_kind);
748749let (place, capture_kind) = truncate_capture_for_optimization(place, capture_kind);
750751let usage_span = if let Some(usage_expr) = capture_info.path_expr_id {
752self.tcx.hir_span(usage_expr)
753 } else {
754::core::panicking::panic("internal error: entered unreachable code")unreachable!()755 };
756757let updated = match capture_kind {
758 ty::UpvarCapture::ByValue => match closure_kind {
759 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
760 (ty::ClosureKind::FnOnce, Some((usage_span, place.clone())))
761 }
762// If closure is already FnOnce, don't update
763ty::ClosureKind::FnOnce => (closure_kind, origin.take()),
764 },
765766 ty::UpvarCapture::ByRef(
767 ty::BorrowKind::Mutable | ty::BorrowKind::UniqueImmutable,
768 ) => {
769match closure_kind {
770 ty::ClosureKind::Fn => {
771 (ty::ClosureKind::FnMut, Some((usage_span, place.clone())))
772 }
773// Don't update the origin
774ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce => {
775 (closure_kind, origin.take())
776 }
777 }
778 }
779780_ => (closure_kind, origin.take()),
781 };
782783closure_kind = updated.0;
784origin = updated.1;
785786let (place, capture_kind) = match capture_clause {
787 hir::CaptureBy::Value { .. } => adjust_for_move_closure(place, capture_kind),
788 hir::CaptureBy::Use { .. } => adjust_for_use_closure(place, capture_kind),
789 hir::CaptureBy::Ref => adjust_for_non_move_closure(place, capture_kind),
790 };
791792// This restriction needs to be applied after we have handled adjustments for `move`
793 // closures. We want to make sure any adjustment that might make us move the place into
794 // the closure gets handled.
795let (place, capture_kind) =
796restrict_precision_for_drop_types(self, place, capture_kind);
797798capture_info.capture_kind = capture_kind;
799 (place, capture_info)
800 })
801 .collect();
802803 (processed, closure_kind, origin)
804 }
805806/// Analyzes the information collected by `InferBorrowKind` to compute the min number of
807 /// Places (and corresponding capture kind) that we need to keep track of to support all
808 /// the required captured paths.
809 ///
810 ///
811 /// Note: If this function is called multiple times for the same closure, it will update
812 /// the existing min_capture map that is stored in TypeckResults.
813 ///
814 /// Eg:
815 /// ```
816 /// #[derive(Debug)]
817 /// struct Point { x: i32, y: i32 }
818 ///
819 /// let s = String::from("s"); // hir_id_s
820 /// let mut p = Point { x: 2, y: -2 }; // his_id_p
821 /// let c = || {
822 /// println!("{s:?}"); // L1
823 /// p.x += 10; // L2
824 /// println!("{}" , p.y); // L3
825 /// println!("{p:?}"); // L4
826 /// drop(s); // L5
827 /// };
828 /// ```
829 /// and let hir_id_L1..5 be the expressions pointing to use of a captured variable on
830 /// the lines L1..5 respectively.
831 ///
832 /// InferBorrowKind results in a structure like this:
833 ///
834 /// ```ignore (illustrative)
835 /// {
836 /// Place(base: hir_id_s, projections: [], ....) -> {
837 /// capture_kind_expr: hir_id_L5,
838 /// path_expr_id: hir_id_L5,
839 /// capture_kind: ByValue
840 /// },
841 /// Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
842 /// capture_kind_expr: hir_id_L2,
843 /// path_expr_id: hir_id_L2,
844 /// capture_kind: ByValue
845 /// },
846 /// Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
847 /// capture_kind_expr: hir_id_L3,
848 /// path_expr_id: hir_id_L3,
849 /// capture_kind: ByValue
850 /// },
851 /// Place(base: hir_id_p, projections: [], ...) -> {
852 /// capture_kind_expr: hir_id_L4,
853 /// path_expr_id: hir_id_L4,
854 /// capture_kind: ByValue
855 /// },
856 /// }
857 /// ```
858 ///
859 /// After the min capture analysis, we get:
860 /// ```ignore (illustrative)
861 /// {
862 /// hir_id_s -> [
863 /// Place(base: hir_id_s, projections: [], ....) -> {
864 /// capture_kind_expr: hir_id_L5,
865 /// path_expr_id: hir_id_L5,
866 /// capture_kind: ByValue
867 /// },
868 /// ],
869 /// hir_id_p -> [
870 /// Place(base: hir_id_p, projections: [], ...) -> {
871 /// capture_kind_expr: hir_id_L2,
872 /// path_expr_id: hir_id_L4,
873 /// capture_kind: ByValue
874 /// },
875 /// ],
876 /// }
877 /// ```
878{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(878u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_def_id")
}> =
::tracing::__macro_support::FieldName::new("closure_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("capture_information")
}> =
::tracing::__macro_support::FieldName::new("capture_information");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_span")
}> =
::tracing::__macro_support::FieldName::new("closure_span");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&capture_information)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
as &dyn ::tracing::field::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_span::macros::bug_impl(None,
format_args!("Expected upvar, found={0:?}", base),
Location::caller()),
};
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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1003",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1003u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::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_span::macros::bug_impl(None,
format_args!("ProjectionKind {0:?} was unexpected", p),
Location::caller())
}
}
}
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_span::macros::bug_impl(None,
format_args!("ProjectionKinds {0:?} or {1:?} were unexpected",
l, r), Location::caller()),
}
}
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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1064",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1064u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};
typeck_results.closure_min_captures.insert(closure_def_id,
root_var_min_capture_list);
}
}
}#[instrument(level = "debug", skip(self))]879fn compute_min_captures(
880&self,
881 closure_def_id: LocalDefId,
882 capture_information: InferredCaptureInformation<'tcx>,
883 closure_span: Span,
884 ) {
885if capture_information.is_empty() {
886return;
887 }
888889let mut typeck_results = self.typeck_results.borrow_mut();
890891let mut root_var_min_capture_list =
892 typeck_results.closure_min_captures.remove(&closure_def_id).unwrap_or_default();
893894for (mut place, capture_info) in capture_information.into_iter() {
895let var_hir_id = match place.base {
896 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
897 base => bug!("Expected upvar, found={:?}", base),
898 };
899let var_ident = self.tcx.hir_ident(var_hir_id);
900901let Some(min_cap_list) = root_var_min_capture_list.get_mut(&var_hir_id) else {
902let mutability = self.determine_capture_mutability(&typeck_results, &place);
903let min_cap_list =
904vec![ty::CapturedPlace { var_ident, place, info: capture_info, mutability }];
905 root_var_min_capture_list.insert(var_hir_id, min_cap_list);
906continue;
907 };
908909// Go through each entry in the current list of min_captures
910 // - if ancestor is found, update its capture kind to account for current place's
911 // capture information.
912 //
913 // - if descendant is found, remove it from the list, and update the current place's
914 // capture information to account for the descendant's capture kind.
915 //
916 // We can never be in a case where the list contains both an ancestor and a descendant
917 // Also there can only be ancestor but in case of descendants there might be
918 // multiple.
919920let mut descendant_found = false;
921let mut updated_capture_info = capture_info;
922 min_cap_list.retain(|possible_descendant| {
923match determine_place_ancestry_relation(&place, &possible_descendant.place) {
924// current place is ancestor of possible_descendant
925PlaceAncestryRelation::Ancestor => {
926 descendant_found = true;
927928let mut possible_descendant = possible_descendant.clone();
929let backup_path_expr_id = updated_capture_info.path_expr_id;
930931// Truncate the descendant (already in min_captures) to be same as the ancestor to handle any
932 // possible change in capture mode.
933truncate_place_to_len_and_update_capture_kind(
934&mut possible_descendant.place,
935&mut possible_descendant.info.capture_kind,
936 place.projections.len(),
937 );
938939 updated_capture_info =
940 determine_capture_info(updated_capture_info, possible_descendant.info);
941942// we need to keep the ancestor's `path_expr_id`
943updated_capture_info.path_expr_id = backup_path_expr_id;
944false
945}
946947_ => true,
948 }
949 });
950951let mut ancestor_found = false;
952if !descendant_found {
953for possible_ancestor in min_cap_list.iter_mut() {
954match determine_place_ancestry_relation(&place, &possible_ancestor.place) {
955 PlaceAncestryRelation::SamePlace => {
956 ancestor_found = true;
957 possible_ancestor.info = determine_capture_info(
958 possible_ancestor.info,
959 updated_capture_info,
960 );
961962// Only one related place will be in the list.
963break;
964 }
965// current place is descendant of possible_ancestor
966PlaceAncestryRelation::Descendant => {
967 ancestor_found = true;
968let backup_path_expr_id = possible_ancestor.info.path_expr_id;
969970// Truncate the descendant (current place) to be same as the ancestor to handle any
971 // possible change in capture mode.
972truncate_place_to_len_and_update_capture_kind(
973&mut place,
974&mut updated_capture_info.capture_kind,
975 possible_ancestor.place.projections.len(),
976 );
977978 possible_ancestor.info = determine_capture_info(
979 possible_ancestor.info,
980 updated_capture_info,
981 );
982983// we need to keep the ancestor's `path_expr_id`
984possible_ancestor.info.path_expr_id = backup_path_expr_id;
985986// Only one related place will be in the list.
987break;
988 }
989_ => {}
990 }
991 }
992 }
993994// Only need to insert when we don't have an ancestor in the existing min capture list
995if !ancestor_found {
996let mutability = self.determine_capture_mutability(&typeck_results, &place);
997let captured_place =
998 ty::CapturedPlace { var_ident, place, info: updated_capture_info, mutability };
999 min_cap_list.push(captured_place);
1000 }
1001 }
10021003debug!(
1004"For closure={:?}, min_captures before sorting={:?}",
1005 closure_def_id, root_var_min_capture_list
1006 );
10071008// Now that we have the minimized list of captures, sort the captures by field id.
1009 // This causes the closure to capture the upvars in the same order as the fields are
1010 // declared which is also the drop order. Thus, in situations where we capture all the
1011 // fields of some type, the observable drop order will remain the same as it previously
1012 // was even though we're dropping each capture individually.
1013 // See https://github.com/rust-lang/project-rfc-2229/issues/42 and
1014 // `tests/ui/closures/2229_closure_analysis/preserve_field_drop_order.rs`.
1015for (_, captures) in &mut root_var_min_capture_list {
1016 captures.sort_by(|capture1, capture2| {
1017fn is_field<'a>(p: &&Projection<'a>) -> bool {
1018match p.kind {
1019 ProjectionKind::Field(_, _) => true,
1020 ProjectionKind::Deref
1021 | ProjectionKind::OpaqueCast
1022 | ProjectionKind::UnwrapUnsafeBinder => false,
1023 p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
1024bug!("ProjectionKind {:?} was unexpected", p)
1025 }
1026 }
1027 }
10281029// Need to sort only by Field projections, so filter away others.
1030 // A previous implementation considered other projection types too
1031 // but that caused ICE #118144
1032let capture1_field_projections = capture1.place.projections.iter().filter(is_field);
1033let capture2_field_projections = capture2.place.projections.iter().filter(is_field);
10341035for (p1, p2) in capture1_field_projections.zip(capture2_field_projections) {
1036// We do not need to look at the `Projection.ty` fields here because at each
1037 // step of the iteration, the projections will either be the same and therefore
1038 // the types must be as well or the current projection will be different and
1039 // we will return the result of comparing the field indexes.
1040match (p1.kind, p2.kind) {
1041 (ProjectionKind::Field(i1, _), ProjectionKind::Field(i2, _)) => {
1042// Compare only if paths are different.
1043 // Otherwise continue to the next iteration
1044if i1 != i2 {
1045return i1.cmp(&i2);
1046 }
1047 }
1048// Given the filter above, this arm should never be hit
1049(l, r) => bug!("ProjectionKinds {:?} or {:?} were unexpected", l, r),
1050 }
1051 }
10521053self.dcx().span_delayed_bug(
1054 closure_span,
1055format!(
1056"two identical projections: ({:?}, {:?})",
1057 capture1.place.projections, capture2.place.projections
1058 ),
1059 );
1060 std::cmp::Ordering::Equal
1061 });
1062 }
10631064debug!(
1065"For closure={:?}, min_captures after sorting={:#?}",
1066 closure_def_id, root_var_min_capture_list
1067 );
1068 typeck_results.closure_min_captures.insert(closure_def_id, root_var_min_capture_list);
1069 }
10701071/// Perform the migration analysis for RFC 2229, and emit lint
1072 /// `disjoint_capture_drop_reorder` if needed.
1073fn perform_2229_migration_analysis(
1074&self,
1075 closure_def_id: LocalDefId,
1076 body_id: hir::BodyId,
1077 capture_clause: hir::CaptureBy,
1078 span: Span,
1079 ) {
1080struct MigrationLint<'a, 'tcx> {
1081 closure_def_id: LocalDefId,
1082 closure_drop_location_span: Span,
1083 this: &'a FnCtxt<'a, 'tcx>,
1084 body_id: hir::BodyId,
1085 need_migrations: Vec<NeededMigration>,
1086 migration_message: String,
1087 }
10881089impl<'a, 'b, 'tcx> Diagnostic<'a> for MigrationLint<'b, 'tcx> {
1090fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> {
1091let Self {
1092 closure_def_id,
1093 closure_drop_location_span,
1094 this,
1095 body_id,
1096 need_migrations,
1097 migration_message,
1098 } = self;
1099let mut lint = Diag::new(dcx, level, migration_message);
11001101let (migration_string, migrated_variables_concat) =
1102migration_suggestion_for_2229(this.tcx, &need_migrations);
11031104let closure_hir_id = this.tcx.local_def_id_to_hir_id(closure_def_id);
1105let closure_head_span = this.tcx.def_span(closure_def_id);
11061107for NeededMigration { var_hir_id, diagnostics_info } in &need_migrations {
1108// Labels all the usage of the captured variable and why they are responsible
1109 // for migration being needed
1110for lint_note in diagnostics_info.iter() {
1111match &lint_note.captures_info {
1112 UpvarMigrationInfo::CapturingPrecise {
1113 source_expr: Some(capture_expr_id),
1114 var_name: captured_name,
1115 } => {
1116let cause_span = this.tcx.hir_span(*capture_expr_id);
1117 lint.span_label(cause_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in Rust 2018, this closure captures all of `{0}`, but in Rust 2021, it will only capture `{1}`",
this.tcx.hir_name(*var_hir_id), captured_name))
})format!("in Rust 2018, this closure captures all of `{}`, but in Rust 2021, it will only capture `{}`",
1118 this.tcx.hir_name(*var_hir_id),
1119 captured_name,
1120 ));
1121 }
1122 UpvarMigrationInfo::CapturingNothing { use_span } => {
1123 lint.span_label(*use_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in Rust 2018, this causes the closure to capture `{0}`, but in Rust 2021, it has no effect",
this.tcx.hir_name(*var_hir_id)))
})format!("in Rust 2018, this causes the closure to capture `{}`, but in Rust 2021, it has no effect",
1124 this.tcx.hir_name(*var_hir_id),
1125 ));
1126 }
11271128_ => {}
1129 }
11301131// Add a label pointing to where a captured variable affected by drop
1132 // order is dropped.
1133if lint_note.reason.drop_order {
1134let var_name = this.tcx.hir_name(*var_hir_id);
1135match &lint_note.captures_info {
1136 UpvarMigrationInfo::CapturingPrecise {
1137 var_name: captured_name,
1138 ..
1139 } => {
1140 lint.span_label(
1141 closure_drop_location_span,
1142::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",
var_name, captured_name))
})format!(
1143"in Rust 2018, `{var_name}` is dropped here, but in Rust 2021, \
1144 only `{captured_name}` will be dropped here as part of the closure"
1145),
1146 );
1147 }
1148 UpvarMigrationInfo::CapturingNothing { use_span: _ } => {
1149 lint.span_label(
1150 closure_drop_location_span,
1151::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",
var_name))
})format!(
1152"in Rust 2018, `{var_name}` is dropped here along with \
1153 the closure, but in Rust 2021 `{var_name}` is not part \
1154 of the closure"
1155),
1156 );
1157 }
1158 }
1159 }
11601161// Add a label explaining why a closure no longer implements a trait
1162for &missing_trait in &lint_note.reason.auto_traits {
1163// not capturing something anymore cannot cause a trait to fail to be implemented:
1164match &lint_note.captures_info {
1165 UpvarMigrationInfo::CapturingPrecise {
1166 var_name: captured_name,
1167 ..
1168 } => {
1169let var_name = this.tcx.hir_name(*var_hir_id);
1170 lint.span_label(
1171 closure_head_span,
1172::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!(
1173"\
1174 in Rust 2018, this closure implements {missing_trait} \
1175 as `{var_name}` implements {missing_trait}, but in Rust 2021, \
1176 this closure will no longer implement {missing_trait} \
1177 because `{var_name}` is not fully captured \
1178 and `{captured_name}` does not implement {missing_trait}"
1179),
1180 );
1181 }
11821183// Cannot happen: if we don't capture a variable, we impl strictly more traits
1184 UpvarMigrationInfo::CapturingNothing { use_span } => ::rustc_span::macros::bug_impl(Some(*use_span),
format_args!("missing trait from not capturing something"),
Location::caller())span_bug!(
1185*use_span,
1186"missing trait from not capturing something"
1187),
1188 }
1189 }
1190 }
1191 }
11921193let 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!(
1194"add a dummy let to cause {migrated_variables_concat} to be fully captured"
1195);
11961197let closure_span = this.tcx.hir_span_with_body(closure_hir_id);
1198let mut closure_body_span = {
1199// If the body was entirely expanded from a macro
1200 // invocation, i.e. the body is not contained inside the
1201 // closure span, then we walk up the expansion until we
1202 // find the span before the expansion.
1203let s = this.tcx.hir_span_with_body(body_id.hir_id);
1204s.find_ancestor_inside(closure_span).unwrap_or(s)
1205 };
12061207if let Ok(mut s) = this.tcx.sess.source_map().span_to_snippet(closure_body_span) {
1208if s.starts_with('$') {
1209// Looks like a macro fragment. Try to find the real block.
1210if let hir::Node::Expr(&hir::Expr {
1211 kind: hir::ExprKind::Block(block, ..),
1212 ..
1213 }) = this.tcx.hir_node(body_id.hir_id)
1214 {
1215// If the body is a block (with `{..}`), we use the span of that block.
1216 // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`.
1217 // Since we know it's a block, we know we can insert the `let _ = ..` without
1218 // breaking the macro syntax.
1219if let Ok(snippet) =
1220this.tcx.sess.source_map().span_to_snippet(block.span)
1221 {
1222closure_body_span = block.span;
1223s = snippet;
1224 }
1225 }
1226 }
12271228let mut lines = s.lines();
1229let line1 = lines.next().unwrap_or_default();
12301231if line1.trim_end() == "{" {
1232// This is a multi-line closure with just a `{` on the first line,
1233 // so we put the `let` on its own line.
1234 // We take the indentation from the next non-empty line.
1235let line2 = lines.find(|line| !line.is_empty()).unwrap_or_default();
1236let indent =
1237line2.split_once(|c: char| !c.is_whitespace()).unwrap_or_default().0;
1238lint.span_suggestion(
1239closure_body_span1240 .with_lo(closure_body_span.lo() + BytePos::from_usize(line1.len()))
1241 .shrink_to_lo(),
1242diagnostic_msg,
1243::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n{0}{1};", indent,
migration_string))
})format!("\n{indent}{migration_string};"),
1244 Applicability::MachineApplicable,
1245 );
1246 } else if line1.starts_with('{') {
1247// This is a closure with its body wrapped in
1248 // braces, but with more than just the opening
1249 // brace on the first line. We put the `let`
1250 // directly after the `{`.
1251lint.span_suggestion(
1252closure_body_span1253 .with_lo(closure_body_span.lo() + BytePos(1))
1254 .shrink_to_lo(),
1255diagnostic_msg,
1256::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0};", migration_string))
})format!(" {migration_string};"),
1257 Applicability::MachineApplicable,
1258 );
1259 } else {
1260// This is a closure without braces around the body.
1261 // We add braces to add the `let` before the body.
1262lint.multipart_suggestion(
1263diagnostic_msg,
1264::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![
1265 (
1266 closure_body_span.shrink_to_lo(),
1267format!("{{ {migration_string}; "),
1268 ),
1269 (closure_body_span.shrink_to_hi(), " }".to_string()),
1270 ],
1271 Applicability::MachineApplicable,
1272 );
1273 }
1274 } else {
1275lint.span_suggestion(
1276closure_span,
1277diagnostic_msg,
1278migration_string,
1279 Applicability::HasPlaceholders,
1280 );
1281 }
1282lint1283 }
1284 }
12851286let (need_migrations, reasons) = self.compute_2229_migrations(
1287closure_def_id,
1288span,
1289capture_clause,
1290self.typeck_results.borrow().closure_min_captures.get(&closure_def_id),
1291 );
12921293// Without a valid drop location, the closure syntax is invalid, and
1294 // emitted lints become nonsensical.
1295if !need_migrations.is_empty()
1296 && let Some(drop_location_span) =
1297drop_location_span(self.tcx, self.tcx.local_def_id_to_hir_id(closure_def_id))
1298 {
1299self.tcx.emit_node_span_lint(
1300RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
1301self.tcx.local_def_id_to_hir_id(closure_def_id),
1302self.tcx.def_span(closure_def_id),
1303MigrationLint {
1304 this: self,
1305 closure_drop_location_span: drop_location_span,
1306 migration_message: reasons.migration_message(),
1307closure_def_id,
1308body_id,
1309need_migrations,
1310 },
1311 );
1312 }
1313 }
13141315/// Combines all the reasons for 2229 migrations
1316fn compute_2229_migrations_reasons(
1317&self,
1318 auto_trait_reasons: UnordSet<&'static str>,
1319 drop_order: bool,
1320 ) -> MigrationWarningReason {
1321MigrationWarningReason {
1322 auto_traits: auto_trait_reasons.into_sorted_stable_ord(),
1323drop_order,
1324 }
1325 }
13261327/// Figures out the list of root variables (and their types) that aren't completely
1328 /// captured by the closure when `capture_disjoint_fields` is enabled and auto-traits
1329 /// differ between the root variable and the captured paths.
1330 ///
1331 /// Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names
1332 /// if migration is needed for traits for the provided var_hir_id, otherwise returns None
1333fn compute_2229_migrations_for_trait(
1334&self,
1335 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1336 var_hir_id: HirId,
1337 closure_clause: hir::CaptureBy,
1338 ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> {
1339let auto_traits_def_id = [
1340self.tcx.lang_items().clone_trait(),
1341self.tcx.lang_items().sync_trait(),
1342self.tcx.get_diagnostic_item(sym::Send),
1343self.tcx.lang_items().unpin_trait(),
1344self.tcx.get_diagnostic_item(sym::unwind_safe_trait),
1345self.tcx.get_diagnostic_item(sym::ref_unwind_safe_trait),
1346 ];
1347const AUTO_TRAITS: [&str; 6] =
1348 ["`Clone`", "`Sync`", "`Send`", "`Unpin`", "`UnwindSafe`", "`RefUnwindSafe`"];
13491350let root_var_min_capture_list = min_captures.and_then(|m| m.get(&var_hir_id))?;
13511352let ty = self.deeply_resolve_ignoring_regions(self.node_ty(var_hir_id));
13531354let ty = match closure_clause {
1355 hir::CaptureBy::Value { .. } => ty, // For move closure the capture kind should be by value
1356hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {
1357// For non move closure the capture kind is the max capture kind of all captures
1358 // according to the ordering ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue
1359let mut max_capture_info = root_var_min_capture_list.first().unwrap().info;
1360for capture in root_var_min_capture_list.iter() {
1361 max_capture_info = determine_capture_info(max_capture_info, capture.info);
1362 }
13631364apply_capture_kind_on_capture_ty(
1365self.tcx,
1366ty,
1367max_capture_info.capture_kind,
1368self.tcx.lifetimes.re_erased,
1369 )
1370 }
1371 };
13721373let mut obligations_should_hold = Vec::new();
1374// Checks if a root variable implements any of the auto traits
1375for check_trait in auto_traits_def_id.iter() {
1376 obligations_should_hold.push(check_trait.is_some_and(|check_trait| {
1377self.infcx
1378 .type_implements_trait(check_trait, [ty], self.param_env)
1379 .must_apply_modulo_regions()
1380 }));
1381 }
13821383let mut problematic_captures = FxIndexMap::default();
1384// Check whether captured fields also implement the trait
1385for capture in root_var_min_capture_list.iter() {
1386let ty = apply_capture_kind_on_capture_ty(
1387self.tcx,
1388 capture.place.ty(),
1389 capture.info.capture_kind,
1390self.tcx.lifetimes.re_erased,
1391 );
13921393// Checks if a capture implements any of the auto traits
1394let mut obligations_holds_for_capture = Vec::new();
1395for check_trait in auto_traits_def_id.iter() {
1396 obligations_holds_for_capture.push(check_trait.is_some_and(|check_trait| {
1397self.infcx
1398 .type_implements_trait(check_trait, [ty], self.param_env)
1399 .must_apply_modulo_regions()
1400 }));
1401 }
14021403let mut capture_problems = UnordSet::default();
14041405// Checks if for any of the auto traits, one or more trait is implemented
1406 // by the root variable but not by the capture
1407for (idx, _) in obligations_should_hold.iter().enumerate() {
1408if !obligations_holds_for_capture[idx] && obligations_should_hold[idx] {
1409 capture_problems.insert(AUTO_TRAITS[idx]);
1410 }
1411 }
14121413if !capture_problems.is_empty() {
1414 problematic_captures.insert(
1415 UpvarMigrationInfo::CapturingPrecise {
1416 source_expr: capture.info.path_expr_id,
1417 var_name: capture.to_string(self.tcx),
1418 },
1419 capture_problems,
1420 );
1421 }
1422 }
1423if !problematic_captures.is_empty() {
1424return Some(problematic_captures);
1425 }
1426None1427 }
14281429/// Figures out the list of root variables (and their types) that aren't completely
1430 /// captured by the closure when `capture_disjoint_fields` is enabled and drop order of
1431 /// some path starting at that root variable **might** be affected.
1432 ///
1433 /// The output list would include a root variable if:
1434 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1435 /// enabled, **and**
1436 /// - It wasn't completely captured by the closure, **and**
1437 /// - One of the paths starting at this root variable, that is not captured needs Drop.
1438 ///
1439 /// This function only returns a HashSet of CapturesInfo for significant drops. If there
1440 /// are no significant drops than None is returned
1441{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1441u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_def_id")
}> =
::tracing::__macro_support::FieldName::new("closure_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_span")
}> =
::tracing::__macro_support::FieldName::new("closure_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("min_captures")
}> =
::tracing::__macro_support::FieldName::new("min_captures");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_clause")
}> =
::tracing::__macro_support::FieldName::new("closure_clause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("var_hir_id")
}> =
::tracing::__macro_support::FieldName::new("var_hir_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_captures)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_clause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&var_hir_id)
as &dyn ::tracing::field::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.deeply_resolve_ignoring_regions(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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1457",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1457u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("does not have significant drop")
as &dyn ::tracing::field::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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1470",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1470u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("no path starting from it is used")
as &dyn ::tracing::field::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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1488",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1488u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("root_var_min_capture_list")
}> =
::tracing::__macro_support::FieldName::new("root_var_min_capture_list");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&root_var_min_capture_list)
as &dyn ::tracing::field::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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1507",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1507u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("projections_list")
}> =
::tracing::__macro_support::FieldName::new("projections_list");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&projections_list)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1508",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1508u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diagnostics_info")
}> =
::tracing::__macro_support::FieldName::new("diagnostics_info");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diagnostics_info)
as &dyn ::tracing::field::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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1511",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1511u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("is_moved")
}> =
::tracing::__macro_support::FieldName::new("is_moved");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_moved)
as &dyn ::tracing::field::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 /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:1515",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1515u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("is_not_completely_captured")
}> =
::tracing::__macro_support::FieldName::new("is_not_completely_captured");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_not_completely_captured)
as &dyn ::tracing::field::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))]1442fn compute_2229_migrations_for_drop(
1443&self,
1444 closure_def_id: LocalDefId,
1445 closure_span: Span,
1446 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1447 closure_clause: hir::CaptureBy,
1448 var_hir_id: HirId,
1449 ) -> Option<FxIndexSet<UpvarMigrationInfo>> {
1450let ty = self.deeply_resolve_ignoring_regions(self.node_ty(var_hir_id));
14511452// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1453if !ty.has_significant_drop(
1454self.tcx,
1455 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1456 ) {
1457debug!("does not have significant drop");
1458return None;
1459 }
14601461let Some(root_var_min_capture_list) = min_captures.and_then(|m| m.get(&var_hir_id)) else {
1462// The upvar is mentioned within the closure but no path starting from it is
1463 // used. This occurs when you have (e.g.)
1464 //
1465 // ```
1466 // let x = move || {
1467 // let _ = y;
1468 // });
1469 // ```
1470debug!("no path starting from it is used");
14711472match closure_clause {
1473// Only migrate if closure is a move closure
1474hir::CaptureBy::Value { .. } => {
1475let mut diagnostics_info = FxIndexSet::default();
1476let upvars =
1477self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar");
1478let upvar = upvars[&var_hir_id];
1479 diagnostics_info
1480 .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span });
1481return Some(diagnostics_info);
1482 }
1483 hir::CaptureBy::Ref | hir::CaptureBy::Use { .. } => {}
1484 }
14851486return None;
1487 };
1488debug!(?root_var_min_capture_list);
14891490let mut projections_list = Vec::new();
1491let mut diagnostics_info = FxIndexSet::default();
14921493for captured_place in root_var_min_capture_list.iter() {
1494match captured_place.info.capture_kind {
1495// Only care about captures that are moved into the closure
1496ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
1497 projections_list.push(captured_place.place.projections.as_slice());
1498 diagnostics_info.insert(UpvarMigrationInfo::CapturingPrecise {
1499 source_expr: captured_place.info.path_expr_id,
1500 var_name: captured_place.to_string(self.tcx),
1501 });
1502 }
1503 ty::UpvarCapture::ByRef(..) => {}
1504 }
1505 }
15061507debug!(?projections_list);
1508debug!(?diagnostics_info);
15091510let is_moved = !projections_list.is_empty();
1511debug!(?is_moved);
15121513let is_not_completely_captured =
1514 root_var_min_capture_list.iter().any(|capture| !capture.place.projections.is_empty());
1515debug!(?is_not_completely_captured);
15161517if is_moved
1518 && is_not_completely_captured
1519 && self.has_significant_drop_outside_of_captures(
1520 closure_def_id,
1521 closure_span,
1522 ty,
1523 projections_list,
1524 )
1525 {
1526return Some(diagnostics_info);
1527 }
15281529None
1530}
15311532/// Figures out the list of root variables (and their types) that aren't completely
1533 /// captured by the closure when `capture_disjoint_fields` is enabled and either drop
1534 /// order of some path starting at that root variable **might** be affected or auto-traits
1535 /// differ between the root variable and the captured paths.
1536 ///
1537 /// The output list would include a root variable if:
1538 /// - It would have been moved into the closure when `capture_disjoint_fields` wasn't
1539 /// enabled, **and**
1540 /// - It wasn't completely captured by the closure, **and**
1541 /// - One of the paths starting at this root variable, that is not captured needs Drop **or**
1542 /// - One of the paths captured does not implement all the auto-traits its root variable
1543 /// implements.
1544 ///
1545 /// Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String
1546 /// containing the reason why root variables whose HirId is contained in the vector should
1547 /// be captured
1548{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(1548u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_def_id")
}> =
::tracing::__macro_support::FieldName::new("closure_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_span")
}> =
::tracing::__macro_support::FieldName::new("closure_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_clause")
}> =
::tracing::__macro_support::FieldName::new("closure_clause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("min_captures")
}> =
::tracing::__macro_support::FieldName::new("min_captures");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_clause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_captures)
as &dyn ::tracing::field::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))]1549fn compute_2229_migrations(
1550&self,
1551 closure_def_id: LocalDefId,
1552 closure_span: Span,
1553 closure_clause: hir::CaptureBy,
1554 min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>,
1555 ) -> (Vec<NeededMigration>, MigrationWarningReason) {
1556let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) else {
1557return (Vec::new(), MigrationWarningReason::default());
1558 };
15591560let mut need_migrations = Vec::new();
1561let mut auto_trait_migration_reasons = UnordSet::default();
1562let mut drop_migration_needed = false;
15631564// Perform auto-trait analysis
1565for (&var_hir_id, _) in upvars.iter() {
1566let mut diagnostics_info = Vec::new();
15671568let auto_trait_diagnostic = self
1569.compute_2229_migrations_for_trait(min_captures, var_hir_id, closure_clause)
1570 .unwrap_or_default();
15711572let drop_reorder_diagnostic = if let Some(diagnostics_info) = self
1573.compute_2229_migrations_for_drop(
1574 closure_def_id,
1575 closure_span,
1576 min_captures,
1577 closure_clause,
1578 var_hir_id,
1579 ) {
1580 drop_migration_needed = true;
1581 diagnostics_info
1582 } else {
1583 FxIndexSet::default()
1584 };
15851586// Combine all the captures responsible for needing migrations into one IndexSet
1587let mut capture_diagnostic = drop_reorder_diagnostic.clone();
1588for key in auto_trait_diagnostic.keys() {
1589 capture_diagnostic.insert(key.clone());
1590 }
15911592let mut capture_diagnostic = capture_diagnostic.into_iter().collect::<Vec<_>>();
1593 capture_diagnostic.sort_by_cached_key(|info| match info {
1594 UpvarMigrationInfo::CapturingPrecise { source_expr: _, var_name } => {
1595 (0, Some(var_name.clone()))
1596 }
1597 UpvarMigrationInfo::CapturingNothing { use_span: _ } => (1, None),
1598 });
1599for captures_info in capture_diagnostic {
1600// Get the auto trait reasons of why migration is needed because of that capture, if there are any
1601let capture_trait_reasons =
1602if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) {
1603 reasons.clone()
1604 } else {
1605 UnordSet::default()
1606 };
16071608// Check if migration is needed because of drop reorder as a result of that capture
1609let capture_drop_reorder_reason = drop_reorder_diagnostic.contains(&captures_info);
16101611// Combine all the reasons of why the root variable should be captured as a result of
1612 // auto trait implementation issues
1613auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied());
16141615 diagnostics_info.push(MigrationLintNote {
1616 captures_info,
1617 reason: self.compute_2229_migrations_reasons(
1618 capture_trait_reasons,
1619 capture_drop_reorder_reason,
1620 ),
1621 });
1622 }
16231624if !diagnostics_info.is_empty() {
1625 need_migrations.push(NeededMigration { var_hir_id, diagnostics_info });
1626 }
1627 }
1628 (
1629 need_migrations,
1630self.compute_2229_migrations_reasons(
1631 auto_trait_migration_reasons,
1632 drop_migration_needed,
1633 ),
1634 )
1635 }
16361637/// This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type
1638 /// of a root variable and a list of captured paths starting at this root variable (expressed
1639 /// using list of `Projection` slices), it returns true if there is a path that is not
1640 /// captured starting at this root variable that implements Drop.
1641 ///
1642 /// The way this function works is at a given call it looks at type `base_path_ty` of some base
1643 /// path say P and then list of projection slices which represent the different captures moved
1644 /// into the closure starting off of P.
1645 ///
1646 /// This will make more sense with an example:
1647 ///
1648 /// ```rust,edition2021
1649 ///
1650 /// struct FancyInteger(i32); // This implements Drop
1651 ///
1652 /// struct Point { x: FancyInteger, y: FancyInteger }
1653 /// struct Color;
1654 ///
1655 /// struct Wrapper { p: Point, c: Color }
1656 ///
1657 /// fn f(w: Wrapper) {
1658 /// let c = || {
1659 /// // Closure captures w.p.x and w.c by move.
1660 /// };
1661 ///
1662 /// c();
1663 /// }
1664 /// ```
1665 ///
1666 /// If `capture_disjoint_fields` wasn't enabled the closure would've moved `w` instead of the
1667 /// precise paths. If we look closely `w.p.y` isn't captured which implements Drop and
1668 /// therefore Drop ordering would change and we want this function to return true.
1669 ///
1670 /// Call stack to figure out if we need to migrate for `w` would look as follows:
1671 ///
1672 /// Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and
1673 /// `w[c]`.
1674 /// Notation:
1675 /// - Ty(place): Type of place
1676 /// - `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs`
1677 /// respectively.
1678 /// ```ignore (illustrative)
1679 /// (Ty(w), [ &[p, x], &[c] ])
1680 /// // |
1681 /// // ----------------------------
1682 /// // | |
1683 /// // v v
1684 /// (Ty(w.p), [ &[x] ]) (Ty(w.c), [ &[] ]) // I(1)
1685 /// // | |
1686 /// // v v
1687 /// (Ty(w.p), [ &[x] ]) false
1688 /// // |
1689 /// // |
1690 /// // -------------------------------
1691 /// // | |
1692 /// // v v
1693 /// (Ty((w.p).x), [ &[] ]) (Ty((w.p).y), []) // IMP 2
1694 /// // | |
1695 /// // v v
1696 /// false NeedsSignificantDrop(Ty(w.p.y))
1697 /// // |
1698 /// // v
1699 /// true
1700 /// ```
1701 ///
1702 /// IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`.
1703 /// This implies that the `w.c` is completely captured by the closure.
1704 /// Since drop for this path will be called when the closure is
1705 /// dropped we don't need to migrate for it.
1706 ///
1707 /// IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this
1708 /// path wasn't captured by the closure. Also note that even
1709 /// though we didn't capture this path, the function visits it,
1710 /// which is kind of the point of this function. We then return
1711 /// if the type of `w.p.y` implements Drop, which in this case is
1712 /// true.
1713 ///
1714 /// Consider another example:
1715 ///
1716 /// ```ignore (pseudo-rust)
1717 /// struct X;
1718 /// impl Drop for X {}
1719 ///
1720 /// struct Y(X);
1721 /// impl Drop for Y {}
1722 ///
1723 /// fn foo() {
1724 /// let y = Y(X);
1725 /// let c = || move(y.0);
1726 /// }
1727 /// ```
1728 ///
1729 /// Note that `y.0` is captured by the closure. When this function is called for `y`, it will
1730 /// return true, because even though all paths starting at `y` are captured, `y` itself
1731 /// implements Drop which will be affected since `y` isn't completely captured.
1732fn has_significant_drop_outside_of_captures(
1733&self,
1734 closure_def_id: LocalDefId,
1735 closure_span: Span,
1736 base_path_ty: Ty<'tcx>,
1737 captured_by_move_projs: Vec<&[Projection<'tcx>]>,
1738 ) -> bool {
1739// FIXME(#132279): Using `non_body_analysis` here feels wrong.
1740let needs_drop = |ty: Ty<'tcx>| {
1741ty.has_significant_drop(
1742self.tcx,
1743 ty::TypingEnv::non_body_analysis(self.tcx, closure_def_id),
1744 )
1745 };
17461747let is_drop_defined_for_ty = |ty: Ty<'tcx>| {
1748let drop_trait = self.tcx.require_lang_item(LangItem::Drop, closure_span);
1749self.infcx
1750 .type_implements_trait(drop_trait, [ty], self.tcx.param_env(closure_def_id))
1751 .must_apply_modulo_regions()
1752 };
17531754let is_drop_defined_for_ty = is_drop_defined_for_ty(base_path_ty);
17551756// If there is a case where no projection is applied on top of current place
1757 // then there must be exactly one capture corresponding to such a case. Note that this
1758 // represents the case of the path being completely captured by the variable.
1759 //
1760 // eg. If `a.b` is captured and we are processing `a.b`, then we can't have the closure also
1761 // capture `a.b.c`, because that violates min capture.
1762let is_completely_captured = captured_by_move_projs.iter().any(|projs| projs.is_empty());
17631764if !(!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));
17651766if is_completely_captured {
1767// The place is captured entirely, so doesn't matter if needs dtor, it will be drop
1768 // when the closure is dropped.
1769return false;
1770 }
17711772if captured_by_move_projs.is_empty() {
1773return needs_drop(base_path_ty);
1774 }
17751776if is_drop_defined_for_ty {
1777// If drop is implemented for this type then we need it to be fully captured,
1778 // and we know it is not completely captured because of the previous checks.
17791780 // Note that this is a bug in the user code that will be reported by the
1781 // borrow checker, since we can't move out of drop types.
17821783 // The bug exists in the user's code pre-migration, and we don't migrate here.
1784return false;
1785 }
17861787match base_path_ty.kind() {
1788// Observations:
1789 // - `captured_by_move_projs` is not empty. Therefore we can call
1790 // `captured_by_move_projs.first().unwrap()` safely.
1791 // - All entries in `captured_by_move_projs` have at least one projection.
1792 // Therefore we can call `captured_by_move_projs.first().unwrap().first().unwrap()` safely.
17931794 // We don't capture derefs in case of move captures, which would have be applied to
1795 // access any further paths.
1796 ty::Adt(def, _) if def.is_box() => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1797 ty::Ref(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1798 ty::RawPtr(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
17991800 ty::Adt(def, args) => {
1801// Multi-variant enums are captured in entirety,
1802 // which would've been handled in the case of single empty slice in `captured_by_move_projs`.
1803{
match (&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);
18041805// Only Field projections can be applied to a non-box Adt.
1806if !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!(
1807 captured_by_move_projs.iter().all(|projs| matches!(
1808 projs.first().unwrap().kind,
1809 ProjectionKind::Field(..)
1810 ))
1811 );
1812def.variants().get(FIRST_VARIANT).unwrap().fields.iter_enumerated().any(
1813 |(i, field)| {
1814let paths_using_field = captured_by_move_projs1815 .iter()
1816 .filter_map(|projs| {
1817if let ProjectionKind::Field(field_idx, _) =
1818projs.first().unwrap().kind
1819 {
1820if field_idx == i { Some(&projs[1..]) } else { None }
1821 } else {
1822::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1823 }
1824 })
1825 .collect();
18261827let after_field_ty = field.ty(self.tcx, args).skip_norm_wip();
1828self.has_significant_drop_outside_of_captures(
1829closure_def_id,
1830closure_span,
1831after_field_ty,
1832paths_using_field,
1833 )
1834 },
1835 )
1836 }
18371838 ty::Tuple(fields) => {
1839// Only Field projections can be applied to a tuple.
1840if !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!(
1841 captured_by_move_projs.iter().all(|projs| matches!(
1842 projs.first().unwrap().kind,
1843 ProjectionKind::Field(..)
1844 ))
1845 );
18461847fields.iter().enumerate().any(|(i, element_ty)| {
1848let paths_using_field = captured_by_move_projs1849 .iter()
1850 .filter_map(|projs| {
1851if let ProjectionKind::Field(field_idx, _) = projs.first().unwrap().kind
1852 {
1853if field_idx.index() == i { Some(&projs[1..]) } else { None }
1854 } else {
1855::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1856 }
1857 })
1858 .collect();
18591860self.has_significant_drop_outside_of_captures(
1861closure_def_id,
1862closure_span,
1863element_ty,
1864paths_using_field,
1865 )
1866 })
1867 }
18681869// Anything else would be completely captured and therefore handled already.
1870_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1871 }
1872 }
18731874fn init_capture_kind_for_place(
1875&self,
1876 place: &Place<'tcx>,
1877 capture_clause: hir::CaptureBy,
1878 ) -> ty::UpvarCapture {
1879match capture_clause {
1880// In case of a move closure if the data is accessed through a reference we
1881 // want to capture by ref to allow precise capture using reborrows.
1882 //
1883 // If the data will be moved out of this place, then the place will be truncated
1884 // at the first Deref in `adjust_for_move_closure` and then moved into the closure.
1885 //
1886 // For example:
1887 //
1888 // struct Buffer<'a> {
1889 // x: &'a String,
1890 // y: Vec<u8>,
1891 // }
1892 //
1893 // fn get<'a>(b: Buffer<'a>) -> impl Sized + 'a {
1894 // let c = move || b.x;
1895 // drop(b);
1896 // c
1897 // }
1898 //
1899 // Even though the closure is declared as move, when we are capturing borrowed data (in
1900 // this case, *b.x) we prefer to capture by reference.
1901 // Otherwise you'd get an error in 2021 immediately because you'd be trying to take
1902 // ownership of the (borrowed) String or else you'd take ownership of b, as in 2018 and
1903 // before, which is also an error.
1904hir::CaptureBy::Value { .. } if !place.deref_tys().any(Ty::is_ref) => {
1905 ty::UpvarCapture::ByValue1906 }
1907 hir::CaptureBy::Use { .. } if !place.deref_tys().any(Ty::is_ref) => {
1908 ty::UpvarCapture::ByUse1909 }
1910 hir::CaptureBy::Value { .. } | hir::CaptureBy::Use { .. } | hir::CaptureBy::Ref => {
1911 ty::UpvarCapture::ByRef(BorrowKind::Immutable)
1912 }
1913 }
1914 }
19151916fn place_for_root_variable(
1917&self,
1918 closure_def_id: LocalDefId,
1919 var_hir_id: HirId,
1920 ) -> Place<'tcx> {
1921let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id);
19221923let place = Place {
1924 base_ty: self.node_ty(var_hir_id),
1925 base: PlaceBase::Upvar(upvar_id),
1926 projections: Default::default(),
1927 };
19281929// Normalize eagerly when inserting into `capture_information`, so all downstream
1930 // capture analysis can assume a normalized `Place`.
1931self.normalize(self.tcx.hir_span(var_hir_id), Unnormalized::new_wip(place))
1932 }
19331934fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool {
1935self.has_rustc_attrs && {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(closure_def_id,
&self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcCaptureAnalysis) =>
{
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, closure_def_id, RustcCaptureAnalysis)1936 }
19371938fn log_capture_analysis_first_pass(
1939&self,
1940 closure_def_id: LocalDefId,
1941 capture_information: &InferredCaptureInformation<'tcx>,
1942 closure_span: Span,
1943 ) {
1944if self.should_log_capture_analysis(closure_def_id) {
1945let mut diag =
1946self.dcx().struct_span_err(closure_span, "First Pass analysis includes:");
1947for (place, capture_info) in capture_information {
1948let capture_str = construct_capture_info_string(self.tcx, place, capture_info);
1949let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Capturing {0}", capture_str))
})format!("Capturing {capture_str}");
19501951let span = capture_info.path_expr_id.map_or(closure_span, |e| self.tcx.hir_span(e));
1952 diag.span_note(span, output_str);
1953 }
1954diag.emit();
1955 }
1956 }
19571958fn log_closure_min_capture_info(&self, closure_def_id: LocalDefId, closure_span: Span) {
1959if self.should_log_capture_analysis(closure_def_id) {
1960if let Some(min_captures) =
1961self.typeck_results.borrow().closure_min_captures.get(&closure_def_id)
1962 {
1963let mut diag =
1964self.dcx().struct_span_err(closure_span, "Min Capture analysis includes:");
19651966for (_, min_captures_for_var) in min_captures {
1967for capture in min_captures_for_var {
1968let place = &capture.place;
1969let capture_info = &capture.info;
19701971let capture_str =
1972 construct_capture_info_string(self.tcx, place, capture_info);
1973let output_str = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Min Capture {0}", capture_str))
})format!("Min Capture {capture_str}");
19741975if capture.info.path_expr_id != capture.info.capture_kind_expr_id {
1976let path_span = capture_info
1977 .path_expr_id
1978 .map_or(closure_span, |e| self.tcx.hir_span(e));
1979let capture_kind_span = capture_info
1980 .capture_kind_expr_id
1981 .map_or(closure_span, |e| self.tcx.hir_span(e));
19821983let mut multi_span: MultiSpan =
1984 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]);
19851986let capture_kind_label =
1987 construct_capture_kind_reason_string(self.tcx, place, capture_info);
1988let path_label = construct_path_string(self.tcx, place);
19891990 multi_span.push_span_label(path_span, path_label);
1991 multi_span.push_span_label(capture_kind_span, capture_kind_label);
19921993 diag.span_note(multi_span, output_str);
1994 } else {
1995let span = capture_info
1996 .path_expr_id
1997 .map_or(closure_span, |e| self.tcx.hir_span(e));
19981999 diag.span_note(span, output_str);
2000 };
2001 }
2002 }
2003diag.emit();
2004 }
2005 }
2006 }
20072008/// A captured place is mutable if
2009 /// 1. Projections don't include a Deref of an immut-borrow, **and**
2010 /// 2. PlaceBase is mut or projections include a Deref of a mut-borrow.
2011fn determine_capture_mutability(
2012&self,
2013 typeck_results: &'a TypeckResults<'tcx>,
2014 place: &Place<'tcx>,
2015 ) -> hir::Mutability {
2016let var_hir_id = match place.base {
2017 PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
2018_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2019 };
20202021let bm = *typeck_results.pat_binding_modes().get(var_hir_id).expect("missing binding mode");
20222023let mut is_mutbl = bm.1;
20242025for pointer_ty in place.deref_tys() {
2026match self.structurally_resolve_type(self.tcx.hir_span(var_hir_id), pointer_ty).kind() {
2027// We don't capture derefs of raw ptrs
2028 ty::RawPtr(_, _) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
20292030// Dereferencing a mut-ref allows us to mut the Place if we don't deref
2031 // an immut-ref after on top of this.
2032ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut,
20332034// The place isn't mutable once we dereference an immutable reference.
2035ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not,
20362037// Dereferencing a box doesn't change mutability
2038ty::Adt(def, ..) if def.is_box() => {}
20392040 unexpected_ty => ::rustc_span::macros::bug_impl(Some(self.tcx.hir_span(var_hir_id)),
format_args!("deref of unexpected pointer type {0:?}", unexpected_ty),
Location::caller())span_bug!(
2041self.tcx.hir_span(var_hir_id),
2042"deref of unexpected pointer type {:?}",
2043 unexpected_ty
2044 ),
2045 }
2046 }
20472048is_mutbl2049 }
2050}
20512052/// Determines whether a child capture that is derived from a parent capture
2053/// should be borrowed with the lifetime of the parent coroutine-closure's env.
2054///
2055/// There are two cases when this needs to happen:
2056///
2057/// (1.) Are we borrowing data owned by the parent closure? We can determine if
2058/// that is the case by checking if the parent capture is by move, EXCEPT if we
2059/// apply a deref projection of an immutable reference, reborrows of immutable
2060/// references which aren't restricted to the LUB of the lifetimes of the deref
2061/// chain. This is why `&'short mut &'long T` can be reborrowed as `&'long T`.
2062///
2063/// ```rust
2064/// let x = &1i32; // Let's call this lifetime `'1`.
2065/// let c = async move || {
2066/// println!("{:?}", *x);
2067/// // Even though the inner coroutine borrows by ref, we're only capturing `*x`,
2068/// // not `x`, so the inner closure is allowed to reborrow the data for `'1`.
2069/// };
2070/// ```
2071///
2072/// (2.) If a coroutine is mutably borrowing from a parent capture, then that
2073/// mutable borrow cannot live for longer than either the parent *or* the borrow
2074/// that we have on the original upvar. Therefore we always need to borrow the
2075/// child capture with the lifetime of the parent coroutine-closure's env.
2076///
2077/// ```rust
2078/// let mut x = 1i32;
2079/// let c = async || {
2080/// x = 1;
2081/// // The parent borrows `x` for some `&'1 mut i32`.
2082/// // However, when we call `c()`, we implicitly autoref for the signature of
2083/// // `AsyncFnMut::async_call_mut`. Let's call that lifetime `'call`. Since
2084/// // the maximum that `&'call mut &'1 mut i32` can be reborrowed is `&'call mut i32`,
2085/// // the inner coroutine should capture w/ the lifetime of the coroutine-closure.
2086/// };
2087/// ```
2088///
2089/// If either of these cases apply, then we should capture the borrow with the
2090/// lifetime of the parent coroutine-closure's env. Luckily, if this function is
2091/// not correct, then the program is not unsound, since we still borrowck and validate
2092/// the choices made from this function -- the only side-effect is that the user
2093/// may receive unnecessary borrowck errors.
2094fn should_reborrow_from_env_of_parent_coroutine_closure<'tcx>(
2095 parent_capture: &ty::CapturedPlace<'tcx>,
2096 child_capture: &ty::CapturedPlace<'tcx>,
2097) -> bool {
2098// (1.)
2099(!parent_capture.is_by_ref()
2100// This is just inlined `place.deref_tys()` but truncated to just
2101 // the child projections. Namely, look for a `&T` deref, since we
2102 // can always extend `&'short mut &'long T` to `&'long T`.
2103&& !child_capture2104 .place
2105 .projections
2106 .iter()
2107 .enumerate()
2108 .skip(parent_capture.place.projections.len())
2109 .any(|(idx, proj)| {
2110#[allow(non_exhaustive_omitted_patterns)] match proj.kind {
ProjectionKind::Deref => true,
_ => false,
}matches!(proj.kind, ProjectionKind::Deref)2111 && #[allow(non_exhaustive_omitted_patterns)] match child_capture.place.ty_before_projection(idx).kind()
{
ty::Ref(.., ty::Mutability::Not) => true,
_ => false,
}matches!(
2112 child_capture.place.ty_before_projection(idx).kind(),
2113 ty::Ref(.., ty::Mutability::Not)
2114 )2115 }))
2116// (2.)
2117 || #[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))2118}
21192120/// Truncate the capture so that the place being borrowed is in accordance with RFC 1240,
2121/// which states that it's unsafe to take a reference into a struct marked `repr(packed)`.
2122fn restrict_repr_packed_field_ref_capture<'tcx>(
2123mut place: Place<'tcx>,
2124mut curr_borrow_kind: ty::UpvarCapture,
2125) -> (Place<'tcx>, ty::UpvarCapture) {
2126let pos = place.projections.iter().enumerate().position(|(i, p)| {
2127let ty = place.ty_before_projection(i);
21282129// Return true for fields of packed structs.
2130match p.kind {
2131 ProjectionKind::Field(..) => match ty.kind() {
2132 ty::Adt(def, _) if def.repr().packed() => {
2133// We stop here regardless of field alignment. Field alignment can change as
2134 // types change, including the types of private fields in other crates, and that
2135 // shouldn't affect how we compute our captures.
2136true
2137}
21382139_ => false,
2140 },
2141_ => false,
2142 }
2143 });
21442145if let Some(pos) = pos {
2146truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_borrow_kind, pos);
2147 }
21482149 (place, curr_borrow_kind)
2150}
21512152/// Returns a Ty that applies the specified capture kind on the provided capture Ty
2153fn apply_capture_kind_on_capture_ty<'tcx>(
2154 tcx: TyCtxt<'tcx>,
2155 ty: Ty<'tcx>,
2156 capture_kind: UpvarCapture,
2157 region: ty::Region<'tcx>,
2158) -> Ty<'tcx> {
2159match capture_kind {
2160 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => ty,
2161 ty::UpvarCapture::ByRef(kind) => Ty::new_ref(tcx, region, ty, kind.to_mutbl_lossy()),
2162 }
2163}
21642165/// Returns the Span of where the value with the provided HirId would be dropped
2166fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Option<Span> {
2167let owner_id = tcx.hir_get_enclosing_scope(hir_id)?;
21682169let hir_id = match tcx.hir_node(owner_id) {
2170 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { body, .. }, .. }) => body.hir_id,
2171 hir::Node::Block(block) => block.hir_id,
2172 hir::Node::TraitItem(item) => item.hir_id(),
2173 hir::Node::ImplItem(item) => item.hir_id(),
2174_ => return None,
2175 };
2176Some(tcx.sess.source_map().end_point(tcx.hir_span(hir_id)))
2177}
21782179struct InferBorrowKind<'a, 'tcx> {
2180 fcx: &'a FnCtxt<'a, 'tcx>,
2181// The def-id of the closure whose kind and upvar accesses are being inferred.
2182closure_def_id: LocalDefId,
21832184/// For each Place that is captured by the closure, we track the minimal kind of
2185 /// access we need (ref, ref mut, move, etc) and the expression that resulted in such access.
2186 ///
2187 /// Consider closure where s.str1 is captured via an ImmutableBorrow and
2188 /// s.str2 via a MutableBorrow
2189 ///
2190 /// ```rust,no_run
2191 /// struct SomeStruct { str1: String, str2: String };
2192 ///
2193 /// // Assume that the HirId for the variable definition is `V1`
2194 /// let mut s = SomeStruct { str1: format!("s1"), str2: format!("s2") };
2195 ///
2196 /// let fix_s = |new_s2| {
2197 /// // Assume that the HirId for the expression `s.str1` is `E1`
2198 /// println!("Updating SomeStruct with str1={0}", s.str1);
2199 /// // Assume that the HirId for the expression `*s.str2` is `E2`
2200 /// s.str2 = new_s2;
2201 /// };
2202 /// ```
2203 ///
2204 /// For closure `fix_s`, (at a high level) the map contains
2205 ///
2206 /// ```ignore (illustrative)
2207 /// Place { V1, [ProjectionKind::Field(Index=0, Variant=0)] } : CaptureKind { E1, ImmutableBorrow }
2208 /// Place { V1, [ProjectionKind::Field(Index=1, Variant=0)] } : CaptureKind { E2, MutableBorrow }
2209 /// ```
2210capture_information: InferredCaptureInformation<'tcx>,
2211 fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
2212}
22132214impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
2215{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2215u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place_with_id")
}> =
::tracing::__macro_support::FieldName::new("place_with_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diag_expr_id")
}> =
::tracing::__macro_support::FieldName::new("diag_expr_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let PlaceBase::Upvar(_) =
place_with_id.place.base else { return };
let dummy_capture_kind =
ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
let span = self.fcx.tcx.hir_span(diag_expr_id);
let place =
self.fcx.normalize(span,
Unnormalized::new_wip(place_with_id.place.clone()));
let (place, _) =
restrict_capture_precision(place, dummy_capture_kind);
let (place, _) =
restrict_repr_packed_field_ref_capture(place,
dummy_capture_kind);
self.fake_reads.push((place, cause, diag_expr_id));
}
}
}#[instrument(skip(self), level = "debug")]2216fn fake_read(
2217&mut self,
2218 place_with_id: &PlaceWithHirId<'tcx>,
2219 cause: FakeReadCause,
2220 diag_expr_id: HirId,
2221 ) {
2222let PlaceBase::Upvar(_) = place_with_id.place.base else { return };
22232224// We need to restrict Fake Read precision to avoid fake reading unsafe code,
2225 // such as deref of a raw pointer.
2226let dummy_capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
22272228let span = self.fcx.tcx.hir_span(diag_expr_id);
2229let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
22302231let (place, _) = restrict_capture_precision(place, dummy_capture_kind);
22322233let (place, _) = restrict_repr_packed_field_ref_capture(place, dummy_capture_kind);
2234self.fake_reads.push((place, cause, diag_expr_id));
2235 }
22362237{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2237u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place_with_id")
}> =
::tracing::__macro_support::FieldName::new("place_with_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diag_expr_id")
}> =
::tracing::__macro_support::FieldName::new("diag_expr_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let PlaceBase::Upvar(upvar_id) =
place_with_id.place.base else { return };
{
match (&self.closure_def_id, &upvar_id.closure_expr_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
let span = self.fcx.tcx.hir_span(diag_expr_id);
let place =
self.fcx.normalize(span,
Unnormalized::new_wip(place_with_id.place.clone()));
self.capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(diag_expr_id),
path_expr_id: Some(diag_expr_id),
capture_kind: ty::UpvarCapture::ByValue,
}));
}
}
}#[instrument(skip(self), level = "debug")]2238fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2239let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2240assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
22412242let span = self.fcx.tcx.hir_span(diag_expr_id);
2243let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
22442245self.capture_information.push((
2246 place,
2247 ty::CaptureInfo {
2248 capture_kind_expr_id: Some(diag_expr_id),
2249 path_expr_id: Some(diag_expr_id),
2250 capture_kind: ty::UpvarCapture::ByValue,
2251 },
2252 ));
2253 }
22542255{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2255u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place_with_id")
}> =
::tracing::__macro_support::FieldName::new("place_with_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diag_expr_id")
}> =
::tracing::__macro_support::FieldName::new("diag_expr_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let PlaceBase::Upvar(upvar_id) =
place_with_id.place.base else { return };
{
match (&self.closure_def_id, &upvar_id.closure_expr_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
let span = self.fcx.tcx.hir_span(diag_expr_id);
let place =
self.fcx.normalize(span,
Unnormalized::new_wip(place_with_id.place.clone()));
self.capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(diag_expr_id),
path_expr_id: Some(diag_expr_id),
capture_kind: ty::UpvarCapture::ByUse,
}));
}
}
}#[instrument(skip(self), level = "debug")]2256fn use_cloned(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2257let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2258assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
22592260let span = self.fcx.tcx.hir_span(diag_expr_id);
2261let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
22622263self.capture_information.push((
2264 place,
2265 ty::CaptureInfo {
2266 capture_kind_expr_id: Some(diag_expr_id),
2267 path_expr_id: Some(diag_expr_id),
2268 capture_kind: ty::UpvarCapture::ByUse,
2269 },
2270 ));
2271 }
22722273{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2273u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place_with_id")
}> =
::tracing::__macro_support::FieldName::new("place_with_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diag_expr_id")
}> =
::tracing::__macro_support::FieldName::new("diag_expr_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("bk")
}> =
::tracing::__macro_support::FieldName::new("bk");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_with_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bk)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let PlaceBase::Upvar(upvar_id) =
place_with_id.place.base else { return };
{
match (&self.closure_def_id, &upvar_id.closure_expr_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
let capture_kind = ty::UpvarCapture::ByRef(bk);
let span = self.fcx.tcx.hir_span(diag_expr_id);
let place =
self.fcx.normalize(span,
Unnormalized::new_wip(place_with_id.place.clone()));
let (place, mut capture_kind) =
restrict_repr_packed_field_ref_capture(place, capture_kind);
if place.deref_tys().any(Ty::is_raw_ptr) {
capture_kind =
ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
}
self.capture_information.push((place,
ty::CaptureInfo {
capture_kind_expr_id: Some(diag_expr_id),
path_expr_id: Some(diag_expr_id),
capture_kind,
}));
}
}
}#[instrument(skip(self), level = "debug")]2274fn borrow(
2275&mut self,
2276 place_with_id: &PlaceWithHirId<'tcx>,
2277 diag_expr_id: HirId,
2278 bk: ty::BorrowKind,
2279 ) {
2280let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return };
2281assert_eq!(self.closure_def_id, upvar_id.closure_expr_id);
22822283// The region here will get discarded/ignored
2284let capture_kind = ty::UpvarCapture::ByRef(bk);
22852286let span = self.fcx.tcx.hir_span(diag_expr_id);
2287let place = self.fcx.normalize(span, Unnormalized::new_wip(place_with_id.place.clone()));
22882289// We only want repr packed restriction to be applied to reading references into a packed
2290 // struct, and not when the data is being moved. Therefore we call this method here instead
2291 // of in `restrict_capture_precision`.
2292let (place, mut capture_kind) = restrict_repr_packed_field_ref_capture(place, capture_kind);
22932294// Raw pointers don't inherit mutability
2295if place.deref_tys().any(Ty::is_raw_ptr) {
2296 capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2297 }
22982299self.capture_information.push((
2300 place,
2301 ty::CaptureInfo {
2302 capture_kind_expr_id: Some(diag_expr_id),
2303 path_expr_id: Some(diag_expr_id),
2304 capture_kind,
2305 },
2306 ));
2307 }
23082309{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2309u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("assignee_place")
}> =
::tracing::__macro_support::FieldName::new("assignee_place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diag_expr_id")
}> =
::tracing::__macro_support::FieldName::new("diag_expr_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&assignee_place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag_expr_id)
as &dyn ::tracing::field::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")]2310fn mutate(&mut self, assignee_place: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) {
2311self.borrow(assignee_place, diag_expr_id, ty::BorrowKind::Mutable);
2312 }
2313}
23142315/// Rust doesn't permit moving fields out of a type that implements drop
2316{}
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("restrict_precision_for_drop_types",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2316u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place")
}> =
::tracing::__macro_support::FieldName::new("place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("curr_mode")
}> =
::tracing::__macro_support::FieldName::new("curr_mode");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&curr_mode)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
(Place<'tcx>, ty::UpvarCapture) = loop {};
return __tracing_attr_fake_return;
}
{
if curr_mode == UpvarCapture::ByValue &&
!fcx.infcx.type_is_copy_modulo_regions(fcx.param_env,
place.ty()) {
for i in 0..place.projections.len() {
match place.ty_before_projection(i).kind() {
ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
truncate_place_to_len_and_update_capture_kind(&mut place,
&mut curr_mode, i);
break;
}
_ => {}
}
}
}
(place, curr_mode)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:2316",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2316u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(skip(fcx), ret, level = "debug")]2317fn restrict_precision_for_drop_types<'a, 'tcx>(
2318 fcx: &'a FnCtxt<'a, 'tcx>,
2319mut place: Place<'tcx>,
2320mut curr_mode: ty::UpvarCapture,
2321) -> (Place<'tcx>, ty::UpvarCapture) {
2322if curr_mode == UpvarCapture::ByValue
2323 && !fcx.infcx.type_is_copy_modulo_regions(fcx.param_env, place.ty())
2324 {
2325for i in 0..place.projections.len() {
2326match place.ty_before_projection(i).kind() {
2327 ty::Adt(def, _) if def.destructor(fcx.tcx).is_some() => {
2328 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2329break;
2330 }
2331_ => {}
2332 }
2333 }
2334 }
23352336 (place, curr_mode)
2337}
23382339/// Truncate `place` so that an `unsafe` block isn't required to capture it.
2340/// - No projections are applied to raw pointers, since these require unsafe blocks. We capture
2341/// them completely.
2342/// - No projections are applied on top of Union ADTs, since these require unsafe blocks.
2343fn restrict_precision_for_unsafe(
2344mut place: Place<'_>,
2345mut curr_mode: ty::UpvarCapture,
2346) -> (Place<'_>, ty::UpvarCapture) {
2347if place.base_ty.is_raw_ptr() {
2348truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2349 }
23502351if place.base_ty.is_union() {
2352truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, 0);
2353 }
23542355for (i, proj) in place.projections.iter().enumerate() {
2356if proj.ty.is_raw_ptr() {
2357// Don't apply any projections on top of a raw ptr.
2358truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2359break;
2360 }
23612362if proj.ty.is_union() {
2363// Don't capture precise fields of a union.
2364truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i + 1);
2365break;
2366 }
2367 }
23682369 (place, curr_mode)
2370}
23712372/// Truncate projections so that the following rules are obeyed by the captured `place`:
2373/// - No Index projections are captured, since arrays are captured completely.
2374/// - No unsafe block is required to capture `place`.
2375///
2376/// Returns the truncated place and updated capture mode.
2377{}
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("restrict_capture_precision",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2377u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place")
}> =
::tracing::__macro_support::FieldName::new("place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("curr_mode")
}> =
::tracing::__macro_support::FieldName::new("curr_mode");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&curr_mode)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
(Place<'_>, ty::UpvarCapture) = loop {};
return __tracing_attr_fake_return;
}
{
let (mut place, mut curr_mode) =
restrict_precision_for_unsafe(place, curr_mode);
if place.projections.is_empty() {
return (place, curr_mode);
}
for (i, proj) in place.projections.iter().enumerate() {
match proj.kind {
ProjectionKind::Index | ProjectionKind::Subslice => {
truncate_place_to_len_and_update_capture_kind(&mut place,
&mut curr_mode, i);
return (place, curr_mode);
}
ProjectionKind::Deref => {}
ProjectionKind::OpaqueCast => {}
ProjectionKind::Field(..) => {}
ProjectionKind::UnwrapUnsafeBinder => {}
}
}
(place, curr_mode)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:2377",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2377u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(ret, level = "debug")]2378fn restrict_capture_precision(
2379 place: Place<'_>,
2380 curr_mode: ty::UpvarCapture,
2381) -> (Place<'_>, ty::UpvarCapture) {
2382let (mut place, mut curr_mode) = restrict_precision_for_unsafe(place, curr_mode);
23832384if place.projections.is_empty() {
2385// Nothing to do here
2386return (place, curr_mode);
2387 }
23882389for (i, proj) in place.projections.iter().enumerate() {
2390match proj.kind {
2391 ProjectionKind::Index | ProjectionKind::Subslice => {
2392// Arrays are completely captured, so we drop Index and Subslice projections
2393truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i);
2394return (place, curr_mode);
2395 }
2396 ProjectionKind::Deref => {}
2397 ProjectionKind::OpaqueCast => {}
2398 ProjectionKind::Field(..) => {}
2399 ProjectionKind::UnwrapUnsafeBinder => {}
2400 }
2401 }
24022403 (place, curr_mode)
2404}
24052406/// Truncate deref of any reference.
2407{}
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("adjust_for_move_closure",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2407u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place")
}> =
::tracing::__macro_support::FieldName::new("place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("kind")
}> =
::tracing::__macro_support::FieldName::new("kind");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
(Place<'_>, ty::UpvarCapture) = loop {};
return __tracing_attr_fake_return;
}
{
let first_deref =
place.projections.iter().position(|proj|
proj.kind == ProjectionKind::Deref);
if let Some(idx) = first_deref {
truncate_place_to_len_and_update_capture_kind(&mut place,
&mut kind, idx);
}
(place, ty::UpvarCapture::ByValue)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:2407",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2407u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(ret, level = "debug")]2408fn adjust_for_move_closure(
2409mut place: Place<'_>,
2410mut kind: ty::UpvarCapture,
2411) -> (Place<'_>, ty::UpvarCapture) {
2412let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
24132414if let Some(idx) = first_deref {
2415 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2416 }
24172418 (place, ty::UpvarCapture::ByValue)
2419}
24202421/// Truncate deref of any reference.
2422{}
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("adjust_for_use_closure",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2422u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place")
}> =
::tracing::__macro_support::FieldName::new("place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("kind")
}> =
::tracing::__macro_support::FieldName::new("kind");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
(Place<'_>, ty::UpvarCapture) = loop {};
return __tracing_attr_fake_return;
}
{
let first_deref =
place.projections.iter().position(|proj|
proj.kind == ProjectionKind::Deref);
if let Some(idx) = first_deref {
truncate_place_to_len_and_update_capture_kind(&mut place,
&mut kind, idx);
}
(place, ty::UpvarCapture::ByUse)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:2422",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2422u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(ret, level = "debug")]2423fn adjust_for_use_closure(
2424mut place: Place<'_>,
2425mut kind: ty::UpvarCapture,
2426) -> (Place<'_>, ty::UpvarCapture) {
2427let first_deref = place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
24282429if let Some(idx) = first_deref {
2430 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2431 }
24322433 (place, ty::UpvarCapture::ByUse)
2434}
24352436/// Adjust closure capture just that if taking ownership of data, only move data
2437/// from enclosing stack frame.
2438{}
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("adjust_for_non_move_closure",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2438u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place")
}> =
::tracing::__macro_support::FieldName::new("place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("kind")
}> =
::tracing::__macro_support::FieldName::new("kind");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
(Place<'_>, ty::UpvarCapture) = loop {};
return __tracing_attr_fake_return;
}
{
let contains_deref =
place.projections.iter().position(|proj|
proj.kind == ProjectionKind::Deref);
match kind {
ty::UpvarCapture::ByValue => {
if let Some(idx) = contains_deref {
truncate_place_to_len_and_update_capture_kind(&mut place,
&mut kind, idx);
}
}
ty::UpvarCapture::ByUse => {
kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
}
ty::UpvarCapture::ByRef(..) => {}
}
(place, kind)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:2438",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2438u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(ret, level = "debug")]2439fn adjust_for_non_move_closure(
2440mut place: Place<'_>,
2441mut kind: ty::UpvarCapture,
2442) -> (Place<'_>, ty::UpvarCapture) {
2443let contains_deref =
2444 place.projections.iter().position(|proj| proj.kind == ProjectionKind::Deref);
24452446match kind {
2447 ty::UpvarCapture::ByValue => {
2448if let Some(idx) = contains_deref {
2449 truncate_place_to_len_and_update_capture_kind(&mut place, &mut kind, idx);
2450 }
2451 }
24522453// A non-`move`/`use` closure that only `.use`s an upvar does not need to
2454 // own (and thus clone-on-capture) the value. The `ByUse` kind here can only
2455 // come from a `x.use` in the body (a `use ||` capture clause goes through
2456 // `adjust_for_use_closure` instead). Capturing such a place by immutable
2457 // borrow lets the `.use` expression clone per evaluation, rather than also
2458 // cloning the value into the closure at construction time. See #157141.
2459ty::UpvarCapture::ByUse => {
2460 kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable);
2461 }
24622463 ty::UpvarCapture::ByRef(..) => {}
2464 }
24652466 (place, kind)
2467}
24682469fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2470let variable_name = match place.base {
2471 PlaceBase::Upvar(upvar_id) => var_name(tcx, upvar_id.var_path.hir_id).to_string(),
2472_ => ::rustc_span::macros::bug_impl(None,
format_args!("Capture_information should only contain upvars"),
Location::caller())bug!("Capture_information should only contain upvars"),
2473 };
24742475let mut projections_str = String::new();
2476for (i, item) in place.projections.iter().enumerate() {
2477let proj = match item.kind {
2478 ProjectionKind::Field(a, b) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0:?}, {1:?})", a, b))
})format!("({a:?}, {b:?})"),
2479 ProjectionKind::Deref => String::from("Deref"),
2480 ProjectionKind::Index => String::from("Index"),
2481 ProjectionKind::Subslice => String::from("Subslice"),
2482 ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
2483 ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
2484 };
2485if i != 0 {
2486 projections_str.push(',');
2487 }
2488 projections_str.push_str(proj.as_str());
2489 }
24902491::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}[{1}]", variable_name,
projections_str))
})format!("{variable_name}[{projections_str}]")2492}
24932494fn construct_capture_kind_reason_string<'tcx>(
2495 tcx: TyCtxt<'_>,
2496 place: &Place<'tcx>,
2497 capture_info: &ty::CaptureInfo,
2498) -> String {
2499let place_str = construct_place_string(tcx, place);
25002501let capture_kind_str = match capture_info.capture_kind {
2502 ty::UpvarCapture::ByValue => "ByValue".into(),
2503 ty::UpvarCapture::ByUse => "ByUse".into(),
2504 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2505 };
25062507::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")2508}
25092510fn construct_path_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String {
2511let place_str = construct_place_string(tcx, place);
25122513::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} used here", place_str))
})format!("{place_str} used here")2514}
25152516fn construct_capture_info_string<'tcx>(
2517 tcx: TyCtxt<'_>,
2518 place: &Place<'tcx>,
2519 capture_info: &ty::CaptureInfo,
2520) -> String {
2521let place_str = construct_place_string(tcx, place);
25222523let capture_kind_str = match capture_info.capture_kind {
2524 ty::UpvarCapture::ByValue => "ByValue".into(),
2525 ty::UpvarCapture::ByUse => "ByUse".into(),
2526 ty::UpvarCapture::ByRef(kind) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", kind))
})format!("{kind:?}"),
2527 };
2528::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} -> {1}", place_str,
capture_kind_str))
})format!("{place_str} -> {capture_kind_str}")2529}
25302531fn var_name(tcx: TyCtxt<'_>, var_hir_id: HirId) -> Symbol {
2532tcx.hir_name(var_hir_id)
2533}
25342535{}
#[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("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2535u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_id")
}> =
::tracing::__macro_support::FieldName::new("closure_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if tcx.sess.at_least_rust_2021() { return false; }
!tcx.lint_level_spec_at_node(RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES,
closure_id).is_allow()
}
}
}#[instrument(level = "debug", skip(tcx))]2536fn should_do_rust_2021_incompatible_closure_captures_analysis(
2537 tcx: TyCtxt<'_>,
2538 closure_id: HirId,
2539) -> bool {
2540if tcx.sess.at_least_rust_2021() {
2541return false;
2542 }
25432544 !tcx.lint_level_spec_at_node(RUST_2021_INCOMPATIBLE_CLOSURE_CAPTURES, closure_id).is_allow()
2545}
25462547/// Return a two string tuple (s1, s2)
2548/// - s1: Line of code that is needed for the migration: eg: `let _ = (&x, ...)`.
2549/// - s2: Comma separated names of the variables being migrated.
2550fn migration_suggestion_for_2229(
2551 tcx: TyCtxt<'_>,
2552 need_migrations: &[NeededMigration],
2553) -> (String, String) {
2554let need_migrations_variables = need_migrations2555 .iter()
2556 .map(|NeededMigration { var_hir_id: v, .. }| var_name(tcx, *v))
2557 .collect::<Vec<_>>();
25582559let migration_ref_concat =
2560need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", v)) })format!("&{v}")).collect::<Vec<_>>().join(", ");
25612562let migration_string = if 1 == need_migrations.len() {
2563::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = {0}",
migration_ref_concat))
})format!("let _ = {migration_ref_concat}")2564 } else {
2565::alloc::__export::must_use({
::alloc::fmt::format(format_args!("let _ = ({0})",
migration_ref_concat))
})format!("let _ = ({migration_ref_concat})")2566 };
25672568let migrated_variables_concat =
2569need_migrations_variables.iter().map(|v| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", v))
})format!("`{v}`")).collect::<Vec<_>>().join(", ");
25702571 (migration_string, migrated_variables_concat)
2572}
25732574/// Helper function to determine if we need to escalate CaptureKind from
2575/// CaptureInfo A to B and returns the escalated CaptureInfo.
2576/// (Note: CaptureInfo contains CaptureKind and an expression that led to capture it in that way)
2577///
2578/// If both `CaptureKind`s are considered equivalent, then the CaptureInfo is selected based
2579/// on the `CaptureInfo` containing an associated `capture_kind_expr_id`.
2580///
2581/// It is the caller's duty to figure out which path_expr_id to use.
2582///
2583/// If both the CaptureKind and Expression are considered to be equivalent,
2584/// then `CaptureInfo` A is preferred. This can be useful in cases where we want to prioritize
2585/// expressions reported back to the user as part of diagnostics based on which appears earlier
2586/// in the closure. This can be achieved simply by calling
2587/// `determine_capture_info(existing_info, current_info)`. This works out because the
2588/// expressions that occur earlier in the closure body than the current expression are processed before.
2589/// Consider the following example
2590/// ```rust,no_run
2591/// struct Point { x: i32, y: i32 }
2592/// let mut p = Point { x: 10, y: 10 };
2593///
2594/// let c = || {
2595/// p.x += 10; // E1
2596/// // ...
2597/// // More code
2598/// // ...
2599/// p.x += 10; // E2
2600/// };
2601/// ```
2602/// `CaptureKind` associated with both `E1` and `E2` will be ByRef(MutBorrow),
2603/// and both have an expression associated, however for diagnostics we prefer reporting
2604/// `E1` since it appears earlier in the closure body. When `E2` is being processed we
2605/// would've already handled `E1`, and have an existing capture_information for it.
2606/// Calling `determine_capture_info(existing_info_e1, current_info_e2)` will return
2607/// `existing_info_e1` in this case, allowing us to point to `E1` in case of diagnostics.
2608fn determine_capture_info(
2609 capture_info_a: ty::CaptureInfo,
2610 capture_info_b: ty::CaptureInfo,
2611) -> ty::CaptureInfo {
2612// We select the CaptureKind which ranks higher based the following priority order:
2613 // (ByUse | ByValue) > MutBorrow > UniqueImmBorrow > ImmBorrow
2614match capture_info_a.capture_kind.partial_cmp(&capture_info_b.capture_kind) {
2615Some(cmp::Ordering::Equal) => {
2616match (capture_info_a.capture_kind_expr_id, capture_info_b.capture_kind_expr_id) {
2617 (Some(_), _) | (None, None) => capture_info_a,
2618 (None, Some(_)) => capture_info_b,
2619 }
2620 }
2621Some(cmp::Ordering::Greater) => capture_info_a,
2622Some(cmp::Ordering::Less) => capture_info_b,
2623None => ::rustc_span::macros::bug_impl(None,
format_args!("Same capture can\'t be ByUse and ByValue at the same time"),
Location::caller())bug!("Same capture can't be ByUse and ByValue at the same time"),
2624 }
2625}
26262627/// Truncates `place` to have up to `len` projections.
2628/// `curr_mode` is the current required capture kind for the place.
2629/// Returns the truncated `place` and the updated required capture kind.
2630///
2631/// Note: Capture kind changes from `MutBorrow` to `UniqueImmBorrow` if the truncated part of the `place`
2632/// contained `Deref` of `&mut`.
2633fn truncate_place_to_len_and_update_capture_kind<'tcx>(
2634 place: &mut Place<'tcx>,
2635 curr_mode: &mut ty::UpvarCapture,
2636 len: usize,
2637) {
2638let 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));
26392640// If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow ->
2641 // UniqueImmBorrow
2642 // Note that if the place contained Deref of a raw pointer it would've not been MutBorrow, so
2643 // we don't need to worry about that case here.
2644match curr_mode {
2645 ty::UpvarCapture::ByRef(ty::BorrowKind::Mutable) => {
2646for i in len..place.projections.len() {
2647if place.projections[i].kind == ProjectionKind::Deref
2648 && is_mut_ref(place.ty_before_projection(i))
2649 {
2650*curr_mode = ty::UpvarCapture::ByRef(ty::BorrowKind::UniqueImmutable);
2651break;
2652 }
2653 }
2654 }
26552656 ty::UpvarCapture::ByRef(..) => {}
2657 ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
2658 }
26592660place.projections.truncate(len);
2661}
26622663/// Determines the Ancestry relationship of Place A relative to Place B
2664///
2665/// `PlaceAncestryRelation::Ancestor` implies Place A is ancestor of Place B
2666/// `PlaceAncestryRelation::Descendant` implies Place A is descendant of Place B
2667/// `PlaceAncestryRelation::Divergent` implies neither of them is the ancestor of the other.
2668fn determine_place_ancestry_relation<'tcx>(
2669 place_a: &Place<'tcx>,
2670 place_b: &Place<'tcx>,
2671) -> PlaceAncestryRelation {
2672// If Place A and Place B don't start off from the same root variable, they are divergent.
2673if place_a.base != place_b.base {
2674return PlaceAncestryRelation::Divergent;
2675 }
26762677// Assume of length of projections_a = n
2678let projections_a = &place_a.projections;
26792680// Assume of length of projections_b = m
2681let projections_b = &place_b.projections;
26822683let same_initial_projections =
2684 iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind);
26852686if same_initial_projections {
2687use std::cmp::Ordering;
26882689// First min(n, m) projections are the same
2690 // Select Ancestor/Descendant
2691match projections_b.len().cmp(&projections_a.len()) {
2692 Ordering::Greater => PlaceAncestryRelation::Ancestor,
2693 Ordering::Equal => PlaceAncestryRelation::SamePlace,
2694 Ordering::Less => PlaceAncestryRelation::Descendant,
2695 }
2696 } else {
2697 PlaceAncestryRelation::Divergent2698 }
2699}
27002701/// Reduces the precision of the captured place when the precision doesn't yield any benefit from
2702/// borrow checking perspective, allowing us to save us on the size of the capture.
2703///
2704///
2705/// Fields that are read through a shared reference will always be read via a shared ref or a copy,
2706/// and therefore capturing precise paths yields no benefit. This optimization truncates the
2707/// rightmost deref of the capture if the deref is applied to a shared ref.
2708///
2709/// Reason we only drop the last deref is because of the following edge case:
2710///
2711/// ```
2712/// # struct A { field_of_a: Box<i32> }
2713/// # struct B {}
2714/// # struct C<'a>(&'a i32);
2715/// struct MyStruct<'a> {
2716/// a: &'static A,
2717/// b: B,
2718/// c: C<'a>,
2719/// }
2720///
2721/// fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
2722/// || drop(&*m.a.field_of_a)
2723/// // Here we really do want to capture `*m.a` because that outlives `'static`
2724///
2725/// // If we capture `m`, then the closure no longer outlives `'static`
2726/// // it is constrained to `'a`
2727/// }
2728/// ```
2729{}
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("truncate_capture_for_optimization",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2729u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("place")
}> =
::tracing::__macro_support::FieldName::new("place");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("curr_mode")
}> =
::tracing::__macro_support::FieldName::new("curr_mode");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&curr_mode)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
(Place<'_>, ty::UpvarCapture) = loop {};
return __tracing_attr_fake_return;
}
{
let is_shared_ref =
|ty: Ty<'_>|
#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Ref(.., hir::Mutability::Not) => true,
_ => false,
};
let idx =
place.projections.iter().rposition(|proj|
ProjectionKind::Deref == proj.kind);
match idx {
Some(idx) if is_shared_ref(place.ty_before_projection(idx))
=> {
truncate_place_to_len_and_update_capture_kind(&mut place,
&mut curr_mode, idx + 1)
}
None | Some(_) => {}
}
(place, curr_mode)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs:2729",
"rustc_hir_typeck::upvar", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5c543b0b8c73c7b72bc8284ced4fb22ead15734d/compiler/rustc_hir_typeck/src/upvar.rs"),
::tracing_core::__macro_support::Option::Some(2729u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::upvar"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(ret, level = "debug")]2730fn truncate_capture_for_optimization(
2731mut place: Place<'_>,
2732mut curr_mode: ty::UpvarCapture,
2733) -> (Place<'_>, ty::UpvarCapture) {
2734let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not));
27352736// Find the rightmost deref (if any). All the projections that come after this
2737 // are fields or other "in-place pointer adjustments"; these refer therefore to
2738 // data owned by whatever pointer is being dereferenced here.
2739let idx = place.projections.iter().rposition(|proj| ProjectionKind::Deref == proj.kind);
27402741match idx {
2742// If that pointer is a shared reference, then we don't need those fields.
2743Some(idx) if is_shared_ref(place.ty_before_projection(idx)) => {
2744 truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, idx + 1)
2745 }
2746None | Some(_) => {}
2747 }
27482749 (place, curr_mode)
2750}
27512752/// Precise capture is enabled if user is using Rust Edition 2021 or higher.
2753/// `span` is the span of the closure.
2754fn enable_precise_capture(span: Span) -> bool {
2755// We use span here to ensure that if the closure was generated by a macro with a different
2756 // edition.
2757span.at_least_rust_2021()
2758}