1//! Code to extract the universally quantified regions declared on a
2//! function. For example:
3//!
4//! ```
5//! fn foo<'a, 'b, 'c: 'b>() { }
6//! ```
7//!
8//! here we would return a map assigning each of `{'a, 'b, 'c}`
9//! to an index.
10//!
11//! The code in this file doesn't *do anything* with those results; it
12//! just returns them for other code to use.
1314use std::cell::Cell;
15use std::iter;
1617use rustc_attr_ir::lang_items::LangItem;
18use rustc_data_structures::fx::FxIndexMap;
19use rustc_errors::Diag;
20use rustc_hir::BodyOwnerKind;
21use rustc_hir::def::DefKind;
22use rustc_hir::def_id::{DefId, LocalDefId};
23use rustc_index::IndexVec;
24use rustc_infer::infer::NllRegionVariableOrigin;
25use rustc_macros::extension;
26use rustc_middle::mir::RETURN_PLACE;
27use rustc_middle::ty::print::with_no_trimmed_paths;
28use rustc_middle::ty::{
29self, BoundVariableKind, GenericArgs, InlineConstArgs, InlineConstArgsParts, List, RegionVid,
30Ty, TyCtxt, TypeFoldable, TypeVisitableExt, fold_regions,
31};
32use rustc_span::{ErrorGuaranteed, bug, kw, span_bug, sym};
33use tracing::{debug, instrument};
3435use crate::BorrowckInferCtxt;
36use crate::renumber::RegionCtxt;
3738#[derive(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for
UniversalRegions<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
"UniversalRegions indices fr_static fr_fn_body first_extern_index first_local_index num_universals defining_ty unnormalized_output_ty unnormalized_input_tys yield_ty resume_ty";
let values: &[&dyn ::core::fmt::Debug] =
&[&self.indices, &self.fr_static, &self.fr_fn_body,
&self.first_extern_index, &self.first_local_index,
&self.num_universals, &self.defining_ty,
&self.unnormalized_output_ty, &self.unnormalized_input_tys,
&self.yield_ty, &&self.resume_ty];
::core::fmt::Formatter::debug_struct_fields_finish(f, names, values)
}
}Debug)]
39#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
UniversalRegions<'tcx> {
#[inline]
fn clone(&self) -> Self {
UniversalRegions {
indices: ::core::clone::Clone::clone(&self.indices),
fr_static: ::core::clone::Clone::clone(&self.fr_static),
fr_fn_body: ::core::clone::Clone::clone(&self.fr_fn_body),
first_extern_index: ::core::clone::Clone::clone(&self.first_extern_index),
first_local_index: ::core::clone::Clone::clone(&self.first_local_index),
num_universals: ::core::clone::Clone::clone(&self.num_universals),
defining_ty: ::core::clone::Clone::clone(&self.defining_ty),
unnormalized_output_ty: ::core::clone::Clone::clone(&self.unnormalized_output_ty),
unnormalized_input_tys: ::core::clone::Clone::clone(&self.unnormalized_input_tys),
yield_ty: ::core::clone::Clone::clone(&self.yield_ty),
resume_ty: ::core::clone::Clone::clone(&self.resume_ty),
}
}
}Clone)] // FIXME(#146079)
40pub(crate) struct UniversalRegions<'tcx> {
41 indices: UniversalRegionIndices<'tcx>,
4243/// The vid assigned to `'static`
44pub fr_static: RegionVid,
4546/// A special region vid created to represent the current MIR fn
47 /// body. It will outlive the entire CFG but it will not outlive
48 /// any other universal regions.
49pub fr_fn_body: RegionVid,
5051/// We create region variables such that they are ordered by their
52 /// `RegionClassification`. The first block are globals, then
53 /// externals, then locals. So, things from:
54 /// - `FIRST_GLOBAL_INDEX..first_extern_index` are global,
55 /// - `first_extern_index..first_local_index` are external,
56 /// - `first_local_index..num_universals` are local.
57first_extern_index: usize,
5859/// See `first_extern_index`.
60first_local_index: usize,
6162/// The total number of universal region variables instantiated.
63num_universals: usize,
6465/// The "defining" type for this function, with all universal
66 /// regions instantiated. For a closure or coroutine, this is the
67 /// closure type, but for a top-level function it's the `FnDef`.
68pub defining_ty: DefiningTy<'tcx>,
6970/// The return type of this function, with all regions replaced by
71 /// their universal `RegionVid` equivalents.
72 ///
73 /// N.B., associated types in this type have not been normalized,
74 /// as the name suggests. =)
75pub unnormalized_output_ty: Ty<'tcx>,
7677/// The fully liberated input types of this function, with all
78 /// regions replaced by their universal `RegionVid` equivalents.
79 ///
80 /// N.B., associated types in these types have not been normalized,
81 /// as the name suggests. =)
82 ///
83 /// N.B., in the case of a closure, index 0 is the implicit self parameter,
84 /// and not the first input as seen by the user.
85pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
8687pub yield_ty: Option<Ty<'tcx>>,
8889pub resume_ty: Option<Ty<'tcx>>,
90}
9192/// The "defining type" for this MIR. The key feature of the "defining
93/// type" is that it contains the information needed to derive all the
94/// universal regions that are in scope as well as the types of the
95/// inputs/output from the MIR. In general, early-bound universal
96/// regions appear free in the defining type and late-bound regions
97/// appear bound in the signature.
98#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for DefiningTy<'tcx> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for DefiningTy<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for DefiningTy<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgs<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgs<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgs<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgs<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgs<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgs<'tcx>>;
*self
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for DefiningTy<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Closure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Closure", __self_0, &__self_1),
Self::Coroutine(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Coroutine", __self_0, &__self_1),
Self::CoroutineClosure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"CoroutineClosure", __self_0, &__self_1),
Self::FnDef(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f, "FnDef",
__self_0, &__self_1),
Self::Const(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f, "Const",
__self_0, &__self_1),
Self::InlineConst(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"InlineConst", __self_0, &__self_1),
Self::GlobalAsm(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"GlobalAsm", &__self_0),
}
}
}Debug)]
99pub(crate) enum DefiningTy<'tcx> {
100/// The MIR is a closure. The signature is found via
101 /// `ClosureArgs::closure_sig_ty`.
102Closure(DefId, GenericArgs<'tcx>),
103104/// The MIR is a coroutine. The signature is that coroutines take
105 /// no parameters and return the result of
106 /// `ClosureArgs::coroutine_return_ty`.
107Coroutine(DefId, GenericArgs<'tcx>),
108109/// The MIR is a special kind of closure that returns coroutines.
110 ///
111 /// See the documentation on `CoroutineClosureSignature` for details
112 /// on how to construct the callable signature of the coroutine from
113 /// its args.
114CoroutineClosure(DefId, GenericArgs<'tcx>),
115116/// The MIR is a fn item with the given `DefId` and args. The signature
117 /// of the function can be bound then with the `fn_sig` query.
118FnDef(DefId, GenericArgs<'tcx>),
119120/// The MIR represents some form of constant. The signature then
121 /// is that it has no inputs and a single return value, which is
122 /// the value of the constant.
123Const(DefId, GenericArgs<'tcx>),
124125/// The MIR represents an inline const. The signature has no inputs and a
126 /// single return value found via `InlineConstArgs::ty`.
127InlineConst(DefId, GenericArgs<'tcx>),
128129// Fake body for a global asm. Not particularly useful or interesting,
130 // but we need it so we can properly store the typeck results of the asm
131 // operands, which aren't associated with a body otherwise.
132GlobalAsm(DefId),
133}
134135impl<'tcx> DefiningTy<'tcx> {
136{}
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("new",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(136u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("body_def_id")
}> =
::tracing::__macro_support::FieldName::new("body_def_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(&body_def_id)
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: DefiningTy<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
match tcx.hir_body_owner_kind(body_def_id) {
BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
let defining_ty =
tcx.type_of(body_def_id).instantiate_identity().skip_normalization();
let defining_ty =
if tcx.next_trait_solver_globally() {
ty::set_aliases_to_rigid(tcx, defining_ty)
} else { defining_ty };
match *defining_ty.kind() {
ty::Closure(def_id, args) =>
DefiningTy::Closure(def_id, args),
ty::Coroutine(def_id, args) =>
DefiningTy::Coroutine(def_id, args),
ty::CoroutineClosure(def_id, args) => {
DefiningTy::CoroutineClosure(def_id, args)
}
ty::FnDef(def_id, args) => {
DefiningTy::FnDef(def_id, args.no_bound_vars().unwrap())
}
_ =>
::rustc_span::macros::bug_impl(Some(tcx.def_span(body_def_id)),
format_args!("expected defining type for `{0:?}`: `{1:?}`",
body_def_id, defining_ty), Location::caller()),
}
}
BodyOwnerKind::Const { inline: true } => {
let body = tcx.mir_promoted(body_def_id).0.borrow();
let ty = body.local_decls[RETURN_PLACE].ty;
let typeck_root_def_id =
tcx.typeck_root_def_id(body_def_id.to_def_id());
let parent_args =
GenericArgs::identity_for_item(tcx, typeck_root_def_id);
let args =
InlineConstArgs::new(tcx,
InlineConstArgsParts {
parent_args: parent_args.as_slice(),
ty,
}).args;
DefiningTy::InlineConst(body_def_id.to_def_id(), args)
}
BodyOwnerKind::Const { inline: false } |
BodyOwnerKind::Static(..) => {
let args =
GenericArgs::identity_for_item(tcx,
body_def_id.to_def_id());
DefiningTy::Const(body_def_id.to_def_id(), args)
}
BodyOwnerKind::GlobalAsm =>
DefiningTy::GlobalAsm(body_def_id.to_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/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:136",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(136u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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(level = "debug", skip(tcx), ret)]137pub(crate) fn new(tcx: TyCtxt<'tcx>, body_def_id: LocalDefId) -> DefiningTy<'tcx> {
138match tcx.hir_body_owner_kind(body_def_id) {
139 BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
140let defining_ty =
141 tcx.type_of(body_def_id).instantiate_identity().skip_normalization();
142let defining_ty = if tcx.next_trait_solver_globally() {
143// Closure types come from HIR typeck results, where they were already
144 // normalized during writeback. Wrapping them in an `EarlyBinder`
145 // conservatively makes aliases non-rigid, so restore their rigidness
146 // instead of normalizing them again during borrowck.
147ty::set_aliases_to_rigid(tcx, defining_ty)
148 } else {
149 defining_ty
150 };
151match *defining_ty.kind() {
152 ty::Closure(def_id, args) => DefiningTy::Closure(def_id, args),
153 ty::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, args),
154 ty::CoroutineClosure(def_id, args) => {
155 DefiningTy::CoroutineClosure(def_id, args)
156 }
157 ty::FnDef(def_id, args) => {
158 DefiningTy::FnDef(def_id, args.no_bound_vars().unwrap())
159 }
160_ => span_bug!(
161 tcx.def_span(body_def_id),
162"expected defining type for `{body_def_id:?}`: `{defining_ty:?}`",
163 ),
164 }
165 }
166167 BodyOwnerKind::Const { inline: true } => {
168// This is required for `AscribeUserType` canonical query, which will call
169 // `type_of(inline_const_def_id)`. That `type_of` would inject erased lifetimes
170 // into borrowck, which is ICE #78174.
171 //
172 // As a workaround, inline consts have an additional generic param (`ty`
173 // below), so that `type_of(inline_const_def_id).substs(substs)` uses the
174 // proper type with NLL infer vars.
175 //
176 // Fetch the actual type from MIR, as `type_of` returns something useless
177 // like `<const_ty>`.
178let body = tcx.mir_promoted(body_def_id).0.borrow();
179let ty = body.local_decls[RETURN_PLACE].ty;
180let typeck_root_def_id = tcx.typeck_root_def_id(body_def_id.to_def_id());
181let parent_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
182let args = InlineConstArgs::new(
183 tcx,
184 InlineConstArgsParts { parent_args: parent_args.as_slice(), ty },
185 )
186 .args;
187 DefiningTy::InlineConst(body_def_id.to_def_id(), args)
188 }
189190 BodyOwnerKind::Const { inline: false } | BodyOwnerKind::Static(..) => {
191let args = GenericArgs::identity_for_item(tcx, body_def_id.to_def_id());
192 DefiningTy::Const(body_def_id.to_def_id(), args)
193 }
194195 BodyOwnerKind::GlobalAsm => DefiningTy::GlobalAsm(body_def_id.to_def_id()),
196 }
197 }
198199/// The bound variables for a given defining type. This differs from their usual bound vars
200 /// in that closures and coroutine closures have an additional `'env`, while C-variadic
201 /// functions have an additional region for their implicit `VaList` input.
202pub(crate) fn bound_vars(self, tcx: TyCtxt<'tcx>) -> &'tcx List<BoundVariableKind<'tcx>> {
203match self {
204 DefiningTy::Closure(_, args) => {
205let closure_sig = args.as_closure().sig();
206let inputs_and_output = closure_sig.inputs_and_output();
207tcx.mk_bound_variable_kinds_from_iter(inputs_and_output.bound_vars().iter().chain(
208 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
209 ))
210 }
211212 DefiningTy::CoroutineClosure(_, args) => {
213let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
214tcx.mk_bound_variable_kinds_from_iter(closure_sig.bound_vars().iter().chain(
215 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
216 ))
217 }
218219 DefiningTy::FnDef(def_id, _) => {
220let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
221if sig.skip_binder().c_variadic() {
222// FIXME(#160495): Don't use an anonymous region here
223tcx.mk_bound_variable_kinds_from_iter(sig.bound_vars().iter().chain(
224 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon)),
225 ))
226 } else {
227sig.bound_vars()
228 }
229 }
230231 DefiningTy::Coroutine(..)
232 | DefiningTy::Const(..)
233 | DefiningTy::InlineConst(..)
234 | DefiningTy::GlobalAsm(..) => ty::List::empty(),
235 }
236 }
237238{}
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("inputs_and_output",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(238u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self")
}> =
::tracing::__macro_support::FieldName::new("self");
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(&self)
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:
ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> = loop {};
return __tracing_attr_fake_return;
}
{
match self {
DefiningTy::Closure(def_id, args) => {
let closure_sig = args.as_closure().sig();
let inputs_and_output = closure_sig.inputs_and_output();
let bound_vars = self.bound_vars(tcx);
let br =
ty::BoundRegion {
var: ty::BoundVar::from_usize(bound_vars.len() - 1),
kind: ty::BoundRegionKind::ClosureEnv,
};
let env_region =
ty::Region::new_bound(tcx, ty::INNERMOST, br);
let closure_ty =
tcx.closure_env_ty(Ty::new_closure(tcx, def_id, args),
args.as_closure().kind(), env_region);
let (&output, tuplized_inputs) =
inputs_and_output.skip_binder().split_last().unwrap();
{
match (&tuplized_inputs.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::Some(format_args!("multiple closure inputs")));
}
}
}
};
let &ty::Tuple(inputs) =
tuplized_inputs[0].kind() else {
::rustc_span::macros::bug_impl(None,
format_args!("closure inputs not a tuple: {0:?}",
tuplized_inputs[0]), Location::caller());
};
ty::Binder::bind_with_vars(tcx.mk_type_list_from_iter(iter::once(closure_ty).chain(inputs).chain(iter::once(output))),
bound_vars)
}
DefiningTy::Coroutine(def_id, args) => {
let resume_ty = args.as_coroutine().resume_ty();
let output = args.as_coroutine().return_ty();
let coroutine_ty = Ty::new_coroutine(tcx, def_id, args);
let inputs_and_output =
tcx.mk_type_list(&[coroutine_ty, resume_ty, output]);
ty::Binder::dummy(inputs_and_output)
}
DefiningTy::CoroutineClosure(def_id, args) => {
let closure_sig =
args.as_coroutine_closure().coroutine_closure_sig();
let bound_vars = self.bound_vars(tcx);
let br =
ty::BoundRegion {
var: ty::BoundVar::from_usize(bound_vars.len() - 1),
kind: ty::BoundRegionKind::ClosureEnv,
};
let env_region =
ty::Region::new_bound(tcx, ty::INNERMOST, br);
let closure_kind = args.as_coroutine_closure().kind();
let closure_ty =
tcx.closure_env_ty(Ty::new_coroutine_closure(tcx, def_id,
args), closure_kind, env_region);
let inputs =
closure_sig.skip_binder().tupled_inputs_ty.tuple_fields();
let output =
closure_sig.skip_binder().to_coroutine_given_kind_and_upvars(tcx,
args.as_coroutine_closure().parent_args(),
tcx.coroutine_for_closure(def_id), closure_kind, env_region,
args.as_coroutine_closure().tupled_upvars_ty(),
args.as_coroutine_closure().coroutine_captures_by_ref_ty());
ty::Binder::bind_with_vars(tcx.mk_type_list_from_iter(iter::once(closure_ty).chain(inputs).chain(iter::once(output))),
bound_vars)
}
DefiningTy::FnDef(def_id, _) => {
let sig =
tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
let inputs_and_output = sig.inputs_and_output();
if tcx.fn_sig(def_id).skip_binder().c_variadic() {
let va_list_did =
tcx.require_lang_item(LangItem::VaList,
tcx.def_span(def_id));
let bound_vars = self.bound_vars(tcx);
let br =
ty::BoundRegion {
var: ty::BoundVar::from_usize(bound_vars.len() - 1),
kind: ty::BoundRegionKind::Anon,
};
let region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
let va_list_ty =
tcx.type_of(va_list_did).instantiate(tcx,
&[region.into()]).skip_norm_wip();
let (output_ty, input_tys) =
inputs_and_output.skip_binder().split_last().unwrap();
return ty::Binder::bind_with_vars(tcx.mk_type_list_from_iter(input_tys.iter().copied().chain([va_list_ty,
*output_ty])), bound_vars);
}
inputs_and_output
}
DefiningTy::Const(def_id, _) => {
let ty =
tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
ty::Binder::dummy(tcx.mk_type_list(&[ty]))
}
DefiningTy::InlineConst(_def_id, args) => {
let ty = args.as_inline_const().ty();
ty::Binder::dummy(tcx.mk_type_list(&[ty]))
}
DefiningTy::GlobalAsm(def_id) =>
ty::Binder::dummy(tcx.mk_type_list(&[tcx.type_of(def_id).instantiate_identity().skip_norm_wip()])),
}
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:238",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(238u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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(level = "debug", skip(tcx), ret)]239pub(crate) fn inputs_and_output(
240self,
241 tcx: TyCtxt<'tcx>,
242 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
243match self {
244 DefiningTy::Closure(def_id, args) => {
245let closure_sig = args.as_closure().sig();
246let inputs_and_output = closure_sig.inputs_and_output();
247let bound_vars = self.bound_vars(tcx);
248let br = ty::BoundRegion {
249 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
250 kind: ty::BoundRegionKind::ClosureEnv,
251 };
252let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
253let closure_ty = tcx.closure_env_ty(
254 Ty::new_closure(tcx, def_id, args),
255 args.as_closure().kind(),
256 env_region,
257 );
258259// The "inputs" of the closure in the
260 // signature appear as a tuple. The MIR side
261 // flattens this tuple.
262let (&output, tuplized_inputs) =
263 inputs_and_output.skip_binder().split_last().unwrap();
264assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
265let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
266bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]);
267 };
268269 ty::Binder::bind_with_vars(
270 tcx.mk_type_list_from_iter(
271 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
272 ),
273 bound_vars,
274 )
275 }
276277 DefiningTy::Coroutine(def_id, args) => {
278let resume_ty = args.as_coroutine().resume_ty();
279let output = args.as_coroutine().return_ty();
280let coroutine_ty = Ty::new_coroutine(tcx, def_id, args);
281let inputs_and_output = tcx.mk_type_list(&[coroutine_ty, resume_ty, output]);
282 ty::Binder::dummy(inputs_and_output)
283 }
284285// Construct the signature of the CoroutineClosure for the purposes of borrowck.
286 // This is pretty straightforward -- we:
287 // 1. first grab the `coroutine_closure_sig`,
288 // 2. compute the self type (`&`/`&mut`/no borrow),
289 // 3. flatten the tupled_input_tys,
290 // 4. construct the correct generator type to return with
291 // `CoroutineClosureSignature::to_coroutine_given_kind_and_upvars`.
292 // Then we wrap it all up into a list of inputs and output.
293DefiningTy::CoroutineClosure(def_id, args) => {
294let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
295let bound_vars = self.bound_vars(tcx);
296let br = ty::BoundRegion {
297 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
298 kind: ty::BoundRegionKind::ClosureEnv,
299 };
300let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
301let closure_kind = args.as_coroutine_closure().kind();
302303let closure_ty = tcx.closure_env_ty(
304 Ty::new_coroutine_closure(tcx, def_id, args),
305 closure_kind,
306 env_region,
307 );
308309let inputs = closure_sig.skip_binder().tupled_inputs_ty.tuple_fields();
310let output = closure_sig.skip_binder().to_coroutine_given_kind_and_upvars(
311 tcx,
312 args.as_coroutine_closure().parent_args(),
313 tcx.coroutine_for_closure(def_id),
314 closure_kind,
315 env_region,
316 args.as_coroutine_closure().tupled_upvars_ty(),
317 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
318 );
319320 ty::Binder::bind_with_vars(
321 tcx.mk_type_list_from_iter(
322 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
323 ),
324 bound_vars,
325 )
326 }
327328 DefiningTy::FnDef(def_id, _) => {
329let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
330let inputs_and_output = sig.inputs_and_output();
331332// C-variadic fns also have a `VaList` input that's not listed in the signature
333 // (as it's created inside the body itself, not passed in from outside).
334if tcx.fn_sig(def_id).skip_binder().c_variadic() {
335let va_list_did = tcx.require_lang_item(LangItem::VaList, tcx.def_span(def_id));
336337let bound_vars = self.bound_vars(tcx);
338let br = ty::BoundRegion {
339 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
340 kind: ty::BoundRegionKind::Anon,
341 };
342let region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
343let va_list_ty =
344 tcx.type_of(va_list_did).instantiate(tcx, &[region.into()]).skip_norm_wip();
345346// The signature needs to follow the order [input_tys, va_list_ty, output_ty]
347let (output_ty, input_tys) =
348 inputs_and_output.skip_binder().split_last().unwrap();
349return ty::Binder::bind_with_vars(
350 tcx.mk_type_list_from_iter(
351 input_tys.iter().copied().chain([va_list_ty, *output_ty]),
352 ),
353 bound_vars,
354 );
355 }
356357 inputs_and_output
358 }
359360 DefiningTy::Const(def_id, _) => {
361// For a constant body, there are no inputs, and one
362 // "output" (the type of the constant).
363let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
364 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
365 }
366367 DefiningTy::InlineConst(_def_id, args) => {
368let ty = args.as_inline_const().ty();
369 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
370 }
371372 DefiningTy::GlobalAsm(def_id) => ty::Binder::dummy(
373 tcx.mk_type_list(&[tcx.type_of(def_id).instantiate_identity().skip_norm_wip()]),
374 ),
375 }
376 }
377378/// Returns a list of all the upvar types for this MIR. If this is
379 /// not a closure or coroutine, there are no upvars, and hence it
380 /// will be an empty list. The order of types in this list will
381 /// match up with the upvar order in the HIR, typesystem, and MIR.
382pub(crate) fn upvar_tys(self) -> &'tcx ty::List<Ty<'tcx>> {
383match self {
384 DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(),
385 DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().upvar_tys(),
386 DefiningTy::Coroutine(_, args) => args.as_coroutine().upvar_tys(),
387 DefiningTy::FnDef(..)
388 | DefiningTy::Const(..)
389 | DefiningTy::InlineConst(..)
390 | DefiningTy::GlobalAsm(_) => ty::List::empty(),
391 }
392 }
393394/// Number of implicit inputs -- notably the "environment"
395 /// parameter for closures -- that appear in MIR but not in the
396 /// user's code.
397pub(crate) fn implicit_inputs(self) -> usize {
398match self {
399 DefiningTy::Closure(..)
400 | DefiningTy::CoroutineClosure(..)
401 | DefiningTy::Coroutine(..) => 1,
402 DefiningTy::FnDef(..)
403 | DefiningTy::Const(..)
404 | DefiningTy::InlineConst(..)
405 | DefiningTy::GlobalAsm(_) => 0,
406 }
407 }
408409pub(crate) fn is_fn_def(&self) -> bool {
410#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::FnDef(..) => true,
_ => false,
}matches!(*self, DefiningTy::FnDef(..))411 }
412413pub(crate) fn is_const(&self) -> bool {
414#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::Const(..) | DefiningTy::InlineConst(..) => true,
_ => false,
}matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))415 }
416417pub(crate) fn def_id(&self) -> DefId {
418match *self {
419 DefiningTy::Closure(def_id, ..)
420 | DefiningTy::CoroutineClosure(def_id, ..)
421 | DefiningTy::Coroutine(def_id, ..)
422 | DefiningTy::FnDef(def_id, ..)
423 | DefiningTy::Const(def_id, ..)
424 | DefiningTy::InlineConst(def_id, ..)
425 | DefiningTy::GlobalAsm(def_id) => def_id,
426 }
427 }
428429/// Returns the args of the `DefiningTy`. These are equivalent to the identity
430 /// substs of the body, but replaced with region vids.
431pub(crate) fn args(&self) -> ty::GenericArgs<'tcx> {
432match *self {
433 DefiningTy::Closure(_, args)
434 | DefiningTy::Coroutine(_, args)
435 | DefiningTy::CoroutineClosure(_, args)
436 | DefiningTy::FnDef(_, args)
437 | DefiningTy::Const(_, args)
438 | DefiningTy::InlineConst(_, args) => args,
439 DefiningTy::GlobalAsm(_) => ty::GenericArgs::empty(),
440 }
441 }
442}
443444#[derive(#[automatically_derived]impl<'tcx> ::core::fmt::Debug for
UniversalRegionIndices<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"UniversalRegionIndices indices fr_static encountered_re_error",
&self.indices, &self.fr_static, &&self.encountered_re_error)
}
}Debug)]
445#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
UniversalRegionIndices<'tcx> {
#[inline]
fn clone(&self) -> Self {
UniversalRegionIndices {
indices: ::core::clone::Clone::clone(&self.indices),
fr_static: ::core::clone::Clone::clone(&self.fr_static),
encountered_re_error: ::core::clone::Clone::clone(&self.encountered_re_error),
}
}
}Clone)] // FIXME(#146079)
446struct UniversalRegionIndices<'tcx> {
447/// For those regions that may appear in the parameter environment
448 /// ('static and early-bound regions), we maintain a map from the
449 /// `ty::Region` to the internal `RegionVid` we are using. This is
450 /// used because trait matching and type-checking will feed us
451 /// region constraints that reference those regions and we need to
452 /// be able to map them to our internal `RegionVid`.
453 ///
454 /// This is similar to just using `GenericArgs`, except that it contains
455 /// an entry for `'static`, and also late bound parameters in scope.
456indices: FxIndexMap<ty::Region<'tcx>, RegionVid>,
457458/// The vid assigned to `'static`. Used only for diagnostics.
459pub fr_static: RegionVid,
460461/// Whether we've encountered an error region. If we have, cancel all
462 /// outlives errors, as they are likely bogus.
463pub encountered_re_error: Cell<Option<ErrorGuaranteed>>,
464}
465466#[derive(#[automatically_derived]impl ::core::fmt::Debug for RegionClassification {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
RegionClassification::Global => "Global",
RegionClassification::External => "External",
RegionClassification::Local => "Local",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
RegionClassification {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RegionClassification {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
467pub(crate) enum RegionClassification {
468/// A **global** region is one that can be named from
469 /// anywhere. There is only one, `'static`.
470Global,
471472/// An **external** region is only relevant for
473 /// closures, coroutines, and inline consts. In that
474 /// case, it refers to regions that are free in the type
475 /// -- basically, something bound in the surrounding context.
476 ///
477 /// Consider this example:
478 ///
479 /// ```ignore (pseudo-rust)
480 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
481 /// let closure = for<'x> |x: &'x u32| { .. };
482 /// // ^^^^^^^ pretend this were legal syntax
483 /// // for declaring a late-bound region in
484 /// // a closure signature
485 /// }
486 /// ```
487 ///
488 /// Here, the lifetimes `'a` and `'b` would be **external** to the
489 /// closure.
490 ///
491 /// If we are not analyzing a closure/coroutine/inline-const,
492 /// there are no external lifetimes.
493External,
494495/// A **local** lifetime is one about which we know the full set
496 /// of relevant constraints (that is, relationships to other named
497 /// regions). For a closure, this includes any region bound in
498 /// the closure's signature. For a fn item, this includes all
499 /// regions other than global ones.
500 ///
501 /// Continuing with the example from `External`, if we were
502 /// analyzing the closure, then `'x` would be local (and `'a` and
503 /// `'b` are external). If we are analyzing the function item
504 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
505 /// scope).
506Local,
507}
508509const FIRST_GLOBAL_INDEX: usize = 0;
510511impl<'tcx> UniversalRegions<'tcx> {
512/// Creates a new and fully initialized `UniversalRegions` that
513 /// contains indices for all the free regions found in the given
514 /// MIR -- that is, all the regions that appear in the function's
515 /// signature.
516pub(crate) fn new(infcx: &BorrowckInferCtxt<'tcx>, mir_def: LocalDefId) -> Self {
517UniversalRegionsBuilder { infcx, mir_def }.build()
518 }
519520/// Given a reference to a closure type, extracts all the values
521 /// from its free regions and returns a vector with them. This is
522 /// used when the closure's creator checks that the
523 /// `ClosureRegionRequirements` are met. The requirements from
524 /// `ClosureRegionRequirements` are expressed in terms of
525 /// `RegionVid` entries that map into the returned vector `V`: so
526 /// if the `ClosureRegionRequirements` contains something like
527 /// `'1: '2`, then the caller would impose the constraint that
528 /// `V[1]: V[2]`.
529pub(crate) fn closure_mapping(
530 tcx: TyCtxt<'tcx>,
531 closure_args: GenericArgs<'tcx>,
532 expected_num_vars: usize,
533 closure_def_id: LocalDefId,
534 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
535let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
536region_mapping.push(tcx.lifetimes.re_static);
537tcx.for_each_free_region(&closure_args, |fr| {
538region_mapping.push(fr);
539 });
540541for_each_late_bound_region_in_recursive_scope(tcx, tcx.local_parent(closure_def_id), |r| {
542region_mapping.push(r);
543 });
544545{
match (®ion_mapping.len(), &expected_num_vars) {
(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::Some(format_args!("index vec had unexpected number of variables")));
}
}
}
};assert_eq!(
546 region_mapping.len(),
547 expected_num_vars,
548"index vec had unexpected number of variables"
549);
550551region_mapping552 }
553554/// Returns `true` if `r` is a member of this set of universal regions.
555pub(crate) fn is_universal_region(&self, r: RegionVid) -> bool {
556 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
557 }
558559/// Classifies `r` as a universal region, returning `None` if this
560 /// is not a member of this set of universal regions.
561pub(crate) fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
562let index = r.index();
563if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
564Some(RegionClassification::Global)
565 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
566Some(RegionClassification::External)
567 } else if (self.first_local_index..self.num_universals).contains(&index) {
568Some(RegionClassification::Local)
569 } else {
570None571 }
572 }
573574/// Returns an iterator over all the RegionVids corresponding to
575 /// universally quantified free regions.
576pub(crate) fn universal_regions_iter(&self) -> impl Iterator<Item = RegionVid> + 'static {
577 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize)
578 }
579580/// Returns `true` if `r` is classified as a local region.
581pub(crate) fn is_local_free_region(&self, r: RegionVid) -> bool {
582self.region_classification(r) == Some(RegionClassification::Local)
583 }
584585pub(crate) fn is_external_free_region(&self, r: RegionVid) -> bool {
586self.region_classification(r) == Some(RegionClassification::External)
587 }
588589/// Returns the number of universal regions created in any category.
590pub(crate) fn len(&self) -> usize {
591self.num_universals
592 }
593594/// Returns the number of global plus external universal regions.
595 /// For closures, these are the regions that appear free in the
596 /// closure type (versus those bound in the closure
597 /// signature). They are therefore the regions between which the
598 /// closure may impose constraints that its creator must verify.
599pub(crate) fn num_global_and_external_regions(&self) -> usize {
600self.first_local_index
601 }
602603/// Gets an iterator over all early bound regions starting with `'static`.
604pub(crate) fn named_universal_regions_iter(
605&self,
606 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> {
607self.indices.indices.iter().map(|(&r, &v)| (r, v))
608 }
609610/// See [UniversalRegionIndices::to_region_vid].
611pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
612self.indices.to_region_vid(r)
613 }
614615/// As part of the NLL unit tests, you can annotate a function with
616 /// `#[rustc_regions]`, and we will emit information about the region
617 /// inference context and -- in particular -- the external constraints
618 /// that this region imposes on others. The methods in this file
619 /// handle the part about dumping the inference context internal
620 /// state.
621pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_>) {
622match self.defining_ty {
623 DefiningTy::Closure(def_id, args) => {
624let v = {
let _guard = NoTrimmedGuard::new();
args.as_slice()[tcx.generics_of(def_id).parent_count..].iter().map(|arg|
arg.to_string()).collect::<Vec<_>>()
}with_no_trimmed_paths!(
625 args.as_slice()[tcx.generics_of(def_id).parent_count..]
626 .iter()
627 .map(|arg| arg.to_string())
628 .collect::<Vec<_>>()
629 );
630err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining type: {0} with closure args [\n {1},\n]",
tcx.def_path_str_with_args(def_id, args), v.join(",\n ")))
})format!(
631"defining type: {} with closure args [\n {},\n]",
632 tcx.def_path_str_with_args(def_id, args),
633 v.join(",\n "),
634 ));
635636// FIXME: It'd be nice to print the late-bound regions
637 // here, but unfortunately these wind up stored into
638 // tests, and the resulting print-outs include def-ids
639 // and other things that are not stable across tests!
640 // So we just include the region-vid. Annoying.
641for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
642err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("late-bound region is {0:?}",
self.to_region_vid(r)))
})format!("late-bound region is {:?}", self.to_region_vid(r)));
643 });
644 }
645 DefiningTy::CoroutineClosure(..) => {
646::core::panicking::unimplemented_default_msg()unimplemented!()647 }
648 DefiningTy::Coroutine(def_id, args) => {
649let v = {
let _guard = NoTrimmedGuard::new();
args.as_slice()[tcx.generics_of(def_id).parent_count..].iter().map(|arg|
arg.to_string()).collect::<Vec<_>>()
}with_no_trimmed_paths!(
650 args.as_slice()[tcx.generics_of(def_id).parent_count..]
651 .iter()
652 .map(|arg| arg.to_string())
653 .collect::<Vec<_>>()
654 );
655err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining type: {0} with coroutine args [\n {1},\n]",
tcx.def_path_str_with_args(def_id, args), v.join(",\n ")))
})format!(
656"defining type: {} with coroutine args [\n {},\n]",
657 tcx.def_path_str_with_args(def_id, args),
658 v.join(",\n "),
659 ));
660661// FIXME: As above, we'd like to print out the region
662 // `r` but doing so is not stable across architectures
663 // and so forth.
664for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
665err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("late-bound region is {0:?}",
self.to_region_vid(r)))
})format!("late-bound region is {:?}", self.to_region_vid(r)));
666 });
667 }
668 DefiningTy::FnDef(def_id, args) => {
669err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!("defining type: {}", tcx.def_path_str_with_args(def_id, args),));
670 }
671 DefiningTy::Const(def_id, args) => {
672err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining constant type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!(
673"defining constant type: {}",
674 tcx.def_path_str_with_args(def_id, args),
675 ));
676 }
677 DefiningTy::InlineConst(def_id, args) => {
678err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining inline constant type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!(
679"defining inline constant type: {}",
680 tcx.def_path_str_with_args(def_id, args),
681 ));
682 }
683 DefiningTy::GlobalAsm(_) => ::core::panicking::unreachable_default_msg()unreachable!(),
684 }
685 }
686687pub(crate) fn implicit_region_bound(&self) -> RegionVid {
688self.fr_fn_body
689 }
690691pub(crate) fn encountered_re_error(&self) -> Option<ErrorGuaranteed> {
692self.indices.encountered_re_error.get()
693 }
694}
695696struct UniversalRegionsBuilder<'a, 'tcx> {
697 infcx: &'a BorrowckInferCtxt<'tcx>,
698 mir_def: LocalDefId,
699}
700701impl<'tcx> UniversalRegionsBuilder<'_, 'tcx> {
702fn build(self) -> UniversalRegions<'tcx> {
703{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:703",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(703u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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!("build(mir_def={0:?})",
self.mir_def) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build(mir_def={:?})", self.mir_def);
704705let param_env = self.infcx.param_env;
706{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:706",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(706u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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!("build: param_env={0:?}",
param_env) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: param_env={:?}", param_env);
707708{
match (&FIRST_GLOBAL_INDEX, &self.infcx.num_region_vars()) {
(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!(FIRST_GLOBAL_INDEX, self.infcx.num_region_vars());
709710// Create the "global" region that is always free in all contexts: 'static.
711let fr_static = self712 .infcx
713 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
714 RegionCtxt::Free(kw::Static)
715 })
716 .as_var();
717718// We've now added all the global regions. The next ones we
719 // add will be external.
720let first_extern_index = self.infcx.num_region_vars();
721722let defining_ty = self.defining_ty();
723{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:723",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(723u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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!("build: defining_ty={0:?}",
defining_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: defining_ty={:?}", defining_ty);
724725let mut indices = self.compute_indices(fr_static, defining_ty);
726{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:726",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(726u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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!("build: indices={0:?}",
indices) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: indices={:?}", indices);
727728// If this is a 'root' body (not a closure/coroutine/inline const), then
729 // there are no extern regions, so the local regions start at the same
730 // position as the (empty) sub-list of extern regions
731let first_local_index = if !self.infcx.tcx.is_typeck_child(self.mir_def.to_def_id()) {
732first_extern_index733 } else {
734// If this is a closure, coroutine, or inline-const, then the late-bound regions from the enclosing
735 // function/closures are actually external regions to us. For example, here, 'a is not local
736 // to the closure c (although it is local to the fn foo). We need to add them as they could be
737 // explicitly named in this body:
738 //
739 // fn foo<'a>() {
740 // let c = || { let x: &'a u32 = ...; }
741 // }
742for_each_late_bound_region_in_recursive_scope(
743self.infcx.tcx,
744self.infcx.tcx.local_parent(self.mir_def),
745 |r| {
746{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:746",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(746u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("r")
}> =
::tracing::__macro_support::FieldName::new("r");
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(&r)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?r);
747let region_vid = {
748let name = r.get_name_or_anon(self.infcx.tcx);
749self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
750 RegionCtxt::LateBound(name)
751 })
752 };
753754{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:754",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(754u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_vid")
}> =
::tracing::__macro_support::FieldName::new("region_vid");
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(®ion_vid)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?region_vid);
755indices.insert_late_bound_region(r, region_vid.as_var());
756 },
757 );
758759// Any regions created during the execution of `defining_ty` or during the above
760 // late-bound region replacement are all considered 'extern' regions
761self.infcx.num_region_vars()
762 };
763764// Converse of above, if this is a function/closure then the late-bound regions declared
765 // on its signature are local.
766 //
767 // We manually loop over `bound_inputs_and_output` instead of using
768 // `for_each_late_bound_region_in_item` as both closures and function
769 // definitions have implicit late bound regions. Closures have a `'env`
770 // regions while c-variadic function definitions have a `&VaList` argument.
771let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
772for (idx, bound_var) in bound_inputs_and_output.bound_vars().iter().enumerate() {
773if let ty::BoundVariableKind::Region(kind) = bound_var {
774let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
775let r = ty::Region::new_late_param(self.infcx.tcx, self.mir_def.to_def_id(), kind);
776let region_vid = {
777let name = r.get_name_or_anon(self.infcx.tcx);
778self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
779 RegionCtxt::LateBound(name)
780 })
781 };
782783{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:783",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(783u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_vid")
}> =
::tracing::__macro_support::FieldName::new("region_vid");
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(®ion_vid)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?region_vid);
784 indices.insert_late_bound_region(r, region_vid.as_var());
785 }
786 }
787let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
788self.mir_def,
789bound_inputs_and_output,
790&indices,
791 );
792793let (unnormalized_output_ty, unnormalized_input_tys) =
794inputs_and_output.split_last().unwrap();
795796let fr_fn_body = self797 .infcx
798 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
799 RegionCtxt::Free(sym::fn_body)
800 })
801 .as_var();
802803let num_universals = self.infcx.num_region_vars();
804805{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:805",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(805u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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!("build: global regions = {0}..{1}",
FIRST_GLOBAL_INDEX, first_extern_index) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: global regions = {}..{}", FIRST_GLOBAL_INDEX, first_extern_index);
806{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:806",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(806u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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!("build: extern regions = {0}..{1}",
first_extern_index, first_local_index) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: extern regions = {}..{}", first_extern_index, first_local_index);
807{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:807",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(807u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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!("build: local regions = {0}..{1}",
first_local_index, num_universals) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: local regions = {}..{}", first_local_index, num_universals);
808809let (resume_ty, yield_ty) = match defining_ty {
810 DefiningTy::Coroutine(_, args) => {
811let tys = args.as_coroutine();
812 (Some(tys.resume_ty()), Some(tys.yield_ty()))
813 }
814_ => (None, None),
815 };
816817UniversalRegions {
818indices,
819fr_static,
820fr_fn_body,
821first_extern_index,
822first_local_index,
823num_universals,
824defining_ty,
825 unnormalized_output_ty: *unnormalized_output_ty,
826unnormalized_input_tys,
827yield_ty,
828resume_ty,
829 }
830 }
831832/// Returns the "defining type" of the current MIR; see `DefiningTy` for details.
833fn defining_ty(&self) -> DefiningTy<'tcx> {
834let defining_ty = DefiningTy::new(self.infcx.tcx, self.mir_def);
835let f = |args| {
836let fr = NllRegionVariableOrigin::FreeRegion;
837self.infcx.replace_free_regions_with_nll_infer_vars(fr, args)
838 };
839match defining_ty {
840 DefiningTy::Closure(def_id, args) => DefiningTy::Closure(def_id, f(args)),
841 DefiningTy::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, f(args)),
842 DefiningTy::CoroutineClosure(def_id, args) => {
843 DefiningTy::CoroutineClosure(def_id, f(args))
844 }
845 DefiningTy::FnDef(def_id, args) => DefiningTy::FnDef(def_id, f(args)),
846 DefiningTy::Const(def_id, args) => DefiningTy::Const(def_id, f(args)),
847 DefiningTy::InlineConst(def_id, args) => DefiningTy::InlineConst(def_id, f(args)),
848 DefiningTy::GlobalAsm(def_id) => DefiningTy::GlobalAsm(def_id),
849 }
850 }
851852/// Builds a hashmap that maps from the universal regions that are
853 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
854 /// `RegionVid`). The map returned by this function contains only
855 /// the early-bound regions.
856fn compute_indices(
857&self,
858 fr_static: RegionVid,
859 defining_ty: DefiningTy<'tcx>,
860 ) -> UniversalRegionIndices<'tcx> {
861let tcx = self.infcx.tcx;
862let typeck_root_def_id = tcx.typeck_root_def_id_local(self.mir_def);
863let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
864let renumbered_args = defining_ty.args();
865866let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
867// This relies on typeck roots being generics_of parents with their
868 // parameters at the start of nested bodies' generics.
869if !(renumbered_args.len() >= identity_args.len()) {
::core::panicking::panic("assertion failed: renumbered_args.len() >= identity_args.len()")
};assert!(renumbered_args.len() >= identity_args.len());
870let arg_mapping =
871 iter::zip(identity_args.regions(), renumbered_args.regions().map(|r| r.as_var()));
872873UniversalRegionIndices {
874 indices: global_mapping.chain(arg_mapping).collect(),
875fr_static,
876 encountered_re_error: Cell::new(None),
877 }
878 }
879880fn compute_inputs_and_output(
881&self,
882 indices: &UniversalRegionIndices<'tcx>,
883 defining_ty: DefiningTy<'tcx>,
884 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
885let tcx = self.infcx.tcx;
886let inputs_and_output = defining_ty.inputs_and_output(tcx);
887let inputs_and_output = indices.fold_to_region_vids(tcx, inputs_and_output);
888889// FIXME(#129952): We probably want a more principled approach here.
890if let Err(e) = inputs_and_output.error_reported() {
891self.infcx.set_tainted_by_errors(e);
892 }
893894inputs_and_output895 }
896}
897898trait InferCtxtExt<'tcx> {
fn replace_free_regions_with_nll_infer_vars<T>(&self,
origin: NllRegionVariableOrigin<'tcx>, value: T)
-> T
where
T: TypeFoldable<TyCtxt<'tcx>>;
fn replace_bound_regions_with_nll_infer_vars<T>(&self,
all_outlive_scope: LocalDefId, value: ty::Binder<'tcx, T>,
indices: &UniversalRegionIndices<'tcx>)
-> T
where
T: TypeFoldable<TyCtxt<'tcx>>;
}
impl<'tcx> InferCtxtExt<'tcx> for BorrowckInferCtxt<'tcx> {
fn replace_free_regions_with_nll_infer_vars<T>(&self,
origin: NllRegionVariableOrigin<'tcx>, value: T) -> T where
T: TypeFoldable<TyCtxt<'tcx>> {
{}
#[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("replace_free_regions_with_nll_infer_vars",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(900u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("value")
}> =
::tracing::__macro_support::FieldName::new("value");
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(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
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: T = loop {};
return __tracing_attr_fake_return;
}
{
fold_regions(self.infcx.tcx, value,
|region, _depth|
{
let name = region.get_name_or_anon(self.infcx.tcx);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:911",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(911u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region")
}> =
::tracing::__macro_support::FieldName::new("region");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("name")
}> =
::tracing::__macro_support::FieldName::new("name");
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(®ion)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
self.next_nll_region_var(origin, || RegionCtxt::Free(name))
})
}
}
}
}
fn replace_bound_regions_with_nll_infer_vars<T>(&self,
all_outlive_scope: LocalDefId, value: ty::Binder<'tcx, T>,
indices: &UniversalRegionIndices<'tcx>) -> T where
T: TypeFoldable<TyCtxt<'tcx>> {
{}
#[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("replace_bound_regions_with_nll_infer_vars",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(917u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("all_outlive_scope")
}> =
::tracing::__macro_support::FieldName::new("all_outlive_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("value")
}> =
::tracing::__macro_support::FieldName::new("value");
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(&all_outlive_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
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: T = loop {};
return __tracing_attr_fake_return;
}
{
let (value, _map) =
self.tcx.instantiate_bound_regions(value,
|br|
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:928",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(928u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("br")
}> =
::tracing::__macro_support::FieldName::new("br");
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(&br)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let kind =
ty::LateParamRegionKind::from_bound(br.var, br.kind);
let liberated_region =
ty::Region::new_late_param(self.tcx,
all_outlive_scope.to_def_id(), kind);
ty::Region::new_var(self.tcx,
indices.to_region_vid(liberated_region))
});
value
}
}
}
}
}#[extension(trait InferCtxtExt<'tcx>)]899impl<'tcx> BorrowckInferCtxt<'tcx> {
900#[instrument(skip(self), level = "debug")]
901fn replace_free_regions_with_nll_infer_vars<T>(
902&self,
903 origin: NllRegionVariableOrigin<'tcx>,
904 value: T,
905 ) -> T
906where
907T: TypeFoldable<TyCtxt<'tcx>>,
908 {
909 fold_regions(self.infcx.tcx, value, |region, _depth| {
910let name = region.get_name_or_anon(self.infcx.tcx);
911debug!(?region, ?name);
912913self.next_nll_region_var(origin, || RegionCtxt::Free(name))
914 })
915 }
916917#[instrument(level = "debug", skip(self, indices))]
918fn replace_bound_regions_with_nll_infer_vars<T>(
919&self,
920 all_outlive_scope: LocalDefId,
921 value: ty::Binder<'tcx, T>,
922 indices: &UniversalRegionIndices<'tcx>,
923 ) -> T
924where
925T: TypeFoldable<TyCtxt<'tcx>>,
926 {
927let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
928debug!(?br);
929let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
930let liberated_region =
931 ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
932 ty::Region::new_var(self.tcx, indices.to_region_vid(liberated_region))
933 });
934 value
935 }
936}
937938impl<'tcx> UniversalRegionIndices<'tcx> {
939/// Initially, the `UniversalRegionIndices` map contains only the
940 /// early-bound regions in scope. Once that is all setup, we come
941 /// in later and instantiate the late-bound regions, and then we
942 /// insert the `ReLateParam` version of those into the map as
943 /// well. These are used for error reporting.
944fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
945{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs:945",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(945u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::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!("insert_late_bound_region({0:?}, {1:?})",
r, vid) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("insert_late_bound_region({:?}, {:?})", r, vid);
946{
match (&self.indices.insert(r, vid), &None) {
(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!(self.indices.insert(r, vid), None);
947 }
948949/// Converts `r` into a local inference variable: `r` can either
950 /// be a `ReVar` (i.e., already a reference to an inference
951 /// variable) or it can be `'static` or some early-bound
952 /// region. This is useful when taking the results from
953 /// type-checking and trait-matching, which may sometimes
954 /// reference those regions from the `ParamEnv`. It is also used
955 /// during initialization. Relies on the `indices` map having been
956 /// fully initialized.
957 ///
958 /// Panics if `r` is not a registered universal region, most notably
959 /// if it is a placeholder. Handling placeholders requires access to the
960 /// `MirTypeckRegionConstraints`.
961fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
962match r.kind() {
963 ty::ReVar(..) => r.as_var(),
964 ty::ReError(guar) => {
965self.encountered_re_error.set(Some(guar));
966// We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
967 // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
968 // errors are being emitted and 2) it leaves the happy path unaffected.
969self.fr_static
970 }
971_ => *self972 .indices
973 .get(&r)
974 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("cannot convert `{0:?}` to a region vid", r),
Location::caller())bug!("cannot convert `{:?}` to a region vid", r)),
975 }
976 }
977978/// Replaces all free regions in `value` with region vids, as
979 /// returned by `to_region_vid`.
980fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
981where
982T: TypeFoldable<TyCtxt<'tcx>>,
983 {
984fold_regions(tcx, value, |region, _| ty::Region::new_var(tcx, self.to_region_vid(region)))
985 }
986}
987988/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
989/// parents, up to the typeck root, and invokes `f` with the liberated form
990/// of each one.
991fn for_each_late_bound_region_in_recursive_scope<'tcx>(
992 tcx: TyCtxt<'tcx>,
993mut mir_def_id: LocalDefId,
994mut f: impl FnMut(ty::Region<'tcx>),
995) {
996// Walk up the tree, collecting late-bound regions until we hit the typeck root
997loop {
998for_each_late_bound_region_in_item(tcx, mir_def_id, &mut f);
9991000if tcx.is_typeck_child(mir_def_id.to_def_id()) {
1001mir_def_id = tcx.local_parent(mir_def_id);
1002 } else {
1003break;
1004 }
1005 }
1006}
10071008/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
1009/// parents, up to the typeck root, and invokes `f` with the liberated form
1010/// of each one.
1011fn for_each_late_bound_region_in_item<'tcx>(
1012 tcx: TyCtxt<'tcx>,
1013 mir_def_id: LocalDefId,
1014mut f: impl FnMut(ty::Region<'tcx>),
1015) {
1016let bound_vars = match tcx.def_kind(mir_def_id) {
1017 DefKind::Fn | DefKind::AssocFn => {
1018tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id))
1019 }
1020// We extract the bound vars from the deduced closure signature, since we may have
1021 // only deduced that a param in the closure signature is late-bound from a constraint
1022 // that we discover during typeck.
1023DefKind::Closure => {
1024let ty = tcx.type_of(mir_def_id).instantiate_identity().skip_norm_wip();
1025match *ty.kind() {
1026 ty::Closure(_, args) => args.as_closure().sig().bound_vars(),
1027 ty::CoroutineClosure(_, args) => {
1028args.as_coroutine_closure().coroutine_closure_sig().bound_vars()
1029 }
1030 ty::Coroutine(_, _) | ty::Error(_) => return,
1031_ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unexpected type for closure: {0}", ty)));
}unreachable!("unexpected type for closure: {ty}"),
1032 }
1033 }
1034_ => return,
1035 };
10361037for (idx, bound_var) in bound_vars.iter().enumerate() {
1038if let ty::BoundVariableKind::Region(kind) = bound_var {
1039let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
1040let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind);
1041 f(liberated_region);
1042 }
1043 }
1044}