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_data_structures::fx::FxIndexMap;
18use rustc_errors::Diag;
19use rustc_hir::BodyOwnerKind;
20use rustc_hir::attrs::lang_items::LangItem;
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, GenericArgsRef, InlineConstArgs, InlineConstArgsParts,
30List, RegionExt, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, fold_regions,
31};
32use rustc_middle::{bug, span_bug};
33use rustc_span::{ErrorGuaranteed, kw, sym};
34use tracing::{debug, instrument};
3536use crate::BorrowckInferCtxt;
37use crate::renumber::RegionCtxt;
3839#[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 _ =
&["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,
"UniversalRegions", names, values)
}
}Debug)]
40#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for UniversalRegions<'tcx> {
#[inline]
fn clone(&self) -> UniversalRegions<'tcx> {
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)
41pub(crate) struct UniversalRegions<'tcx> {
42 indices: UniversalRegionIndices<'tcx>,
4344/// The vid assigned to `'static`
45pub fr_static: RegionVid,
4647/// A special region vid created to represent the current MIR fn
48 /// body. It will outlive the entire CFG but it will not outlive
49 /// any other universal regions.
50pub fr_fn_body: RegionVid,
5152/// We create region variables such that they are ordered by their
53 /// `RegionClassification`. The first block are globals, then
54 /// externals, then locals. So, things from:
55 /// - `FIRST_GLOBAL_INDEX..first_extern_index` are global,
56 /// - `first_extern_index..first_local_index` are external,
57 /// - `first_local_index..num_universals` are local.
58first_extern_index: usize,
5960/// See `first_extern_index`.
61first_local_index: usize,
6263/// The total number of universal region variables instantiated.
64num_universals: usize,
6566/// The "defining" type for this function, with all universal
67 /// regions instantiated. For a closure or coroutine, this is the
68 /// closure type, but for a top-level function it's the `FnDef`.
69pub defining_ty: DefiningTy<'tcx>,
7071/// The return type of this function, with all regions replaced by
72 /// their universal `RegionVid` equivalents.
73 ///
74 /// N.B., associated types in this type have not been normalized,
75 /// as the name suggests. =)
76pub unnormalized_output_ty: Ty<'tcx>,
7778/// The fully liberated input types of this function, with all
79 /// regions replaced by their universal `RegionVid` equivalents.
80 ///
81 /// N.B., associated types in these types have not been normalized,
82 /// as the name suggests. =)
83 ///
84 /// N.B., in the case of a closure, index 0 is the implicit self parameter,
85 /// and not the first input as seen by the user.
86pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
8788pub yield_ty: Option<Ty<'tcx>>,
8990pub resume_ty: Option<Ty<'tcx>>,
91}
9293/// The "defining type" for this MIR. The key feature of the "defining
94/// type" is that it contains the information needed to derive all the
95/// universal regions that are in scope as well as the types of the
96/// inputs/output from the MIR. In general, early-bound universal
97/// regions appear free in the defining type and late-bound regions
98/// appear bound in the signature.
99#[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) -> DefiningTy<'tcx> {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'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 {
DefiningTy::Closure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Closure", __self_0, &__self_1),
DefiningTy::Coroutine(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Coroutine", __self_0, &__self_1),
DefiningTy::CoroutineClosure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"CoroutineClosure", __self_0, &__self_1),
DefiningTy::FnDef(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "FnDef",
__self_0, &__self_1),
DefiningTy::Const(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Const",
__self_0, &__self_1),
DefiningTy::InlineConst(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"InlineConst", __self_0, &__self_1),
DefiningTy::GlobalAsm(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"GlobalAsm", &__self_0),
}
}
}Debug)]
100pub(crate) enum DefiningTy<'tcx> {
101/// The MIR is a closure. The signature is found via
102 /// `ClosureArgs::closure_sig_ty`.
103Closure(DefId, GenericArgsRef<'tcx>),
104105/// The MIR is a coroutine. The signature is that coroutines take
106 /// no parameters and return the result of
107 /// `ClosureArgs::coroutine_return_ty`.
108Coroutine(DefId, GenericArgsRef<'tcx>),
109110/// The MIR is a special kind of closure that returns coroutines.
111 ///
112 /// See the documentation on `CoroutineClosureSignature` for details
113 /// on how to construct the callable signature of the coroutine from
114 /// its args.
115CoroutineClosure(DefId, GenericArgsRef<'tcx>),
116117/// The MIR is a fn item with the given `DefId` and args. The signature
118 /// of the function can be bound then with the `fn_sig` query.
119FnDef(DefId, GenericArgsRef<'tcx>),
120121/// The MIR represents some form of constant. The signature then
122 /// is that it has no inputs and a single return value, which is
123 /// the value of the constant.
124Const(DefId, GenericArgsRef<'tcx>),
125126/// The MIR represents an inline const. The signature has no inputs and a
127 /// single return value found via `InlineConstArgs::ty`.
128InlineConst(DefId, GenericArgsRef<'tcx>),
129130// Fake body for a global asm. Not particularly useful or interesting,
131 // but we need it so we can properly store the typeck results of the asm
132 // operands, which aren't associated with a body otherwise.
133GlobalAsm(DefId),
134}
135136impl<'tcx> DefiningTy<'tcx> {
137{}
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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(137u32),
::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_middle::util::bug::span_bug_fmt(tcx.def_span(body_def_id),
format_args!("expected defining type for `{0:?}`: `{1:?}`",
body_def_id, defining_ty)),
}
}
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, 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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:137",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(137u32),
::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)]138pub(crate) fn new(tcx: TyCtxt<'tcx>, body_def_id: LocalDefId) -> DefiningTy<'tcx> {
139match tcx.hir_body_owner_kind(body_def_id) {
140 BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
141let defining_ty =
142 tcx.type_of(body_def_id).instantiate_identity().skip_normalization();
143let defining_ty = if tcx.next_trait_solver_globally() {
144// Closure types come from HIR typeck results, where they were already
145 // normalized during writeback. Wrapping them in an `EarlyBinder`
146 // conservatively makes aliases non-rigid, so restore their rigidness
147 // instead of normalizing them again during borrowck.
148ty::set_aliases_to_rigid(tcx, defining_ty)
149 } else {
150 defining_ty
151 };
152match *defining_ty.kind() {
153 ty::Closure(def_id, args) => DefiningTy::Closure(def_id, args),
154 ty::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, args),
155 ty::CoroutineClosure(def_id, args) => {
156 DefiningTy::CoroutineClosure(def_id, args)
157 }
158 ty::FnDef(def_id, args) => {
159 DefiningTy::FnDef(def_id, args.no_bound_vars().unwrap())
160 }
161_ => span_bug!(
162 tcx.def_span(body_def_id),
163"expected defining type for `{body_def_id:?}`: `{defining_ty:?}`",
164 ),
165 }
166 }
167168 BodyOwnerKind::Const { inline: true } => {
169// This is required for `AscribeUserType` canonical query, which will call
170 // `type_of(inline_const_def_id)`. That `type_of` would inject erased lifetimes
171 // into borrowck, which is ICE #78174.
172 //
173 // As a workaround, inline consts have an additional generic param (`ty`
174 // below), so that `type_of(inline_const_def_id).substs(substs)` uses the
175 // proper type with NLL infer vars.
176 //
177 // Fetch the actual type from MIR, as `type_of` returns something useless
178 // like `<const_ty>`.
179let body = tcx.mir_promoted(body_def_id).0.borrow();
180let ty = body.local_decls[RETURN_PLACE].ty;
181let typeck_root_def_id = tcx.typeck_root_def_id(body_def_id.to_def_id());
182let parent_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
183let args = InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty }).args;
184 DefiningTy::InlineConst(body_def_id.to_def_id(), args)
185 }
186187 BodyOwnerKind::Const { inline: false } | BodyOwnerKind::Static(..) => {
188let args = GenericArgs::identity_for_item(tcx, body_def_id.to_def_id());
189 DefiningTy::Const(body_def_id.to_def_id(), args)
190 }
191192 BodyOwnerKind::GlobalAsm => DefiningTy::GlobalAsm(body_def_id.to_def_id()),
193 }
194 }
195196/// The bound variables for a given defining type. This differs from their usual bound vars
197 /// in that closures and coroutine closures have an additional `'env`, while C-variadic
198 /// functions have an additional region for their implicit `VaList` input.
199pub(crate) fn bound_vars(self, tcx: TyCtxt<'tcx>) -> &'tcx List<BoundVariableKind<'tcx>> {
200match self {
201 DefiningTy::Closure(_, args) => {
202let closure_sig = args.as_closure().sig();
203let inputs_and_output = closure_sig.inputs_and_output();
204tcx.mk_bound_variable_kinds_from_iter(inputs_and_output.bound_vars().iter().chain(
205 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
206 ))
207 }
208209 DefiningTy::CoroutineClosure(_, args) => {
210let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
211tcx.mk_bound_variable_kinds_from_iter(closure_sig.bound_vars().iter().chain(
212 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
213 ))
214 }
215216 DefiningTy::FnDef(def_id, _) => {
217let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
218if sig.skip_binder().c_variadic() {
219// FIXME(#160495): Don't use an anonymous region here
220tcx.mk_bound_variable_kinds_from_iter(sig.bound_vars().iter().chain(
221 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon)),
222 ))
223 } else {
224sig.bound_vars()
225 }
226 }
227228 DefiningTy::Coroutine(..)
229 | DefiningTy::Const(..)
230 | DefiningTy::InlineConst(..)
231 | DefiningTy::GlobalAsm(..) => ty::List::empty(),
232 }
233 }
234235{}
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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(235u32),
::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_middle::util::bug::bug_fmt(format_args!("closure inputs not a tuple: {0:?}",
tuplized_inputs[0]));
};
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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:235",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(235u32),
::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)]236pub(crate) fn inputs_and_output(
237self,
238 tcx: TyCtxt<'tcx>,
239 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
240match self {
241 DefiningTy::Closure(def_id, args) => {
242let closure_sig = args.as_closure().sig();
243let inputs_and_output = closure_sig.inputs_and_output();
244let bound_vars = self.bound_vars(tcx);
245let br = ty::BoundRegion {
246 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
247 kind: ty::BoundRegionKind::ClosureEnv,
248 };
249let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
250let closure_ty = tcx.closure_env_ty(
251 Ty::new_closure(tcx, def_id, args),
252 args.as_closure().kind(),
253 env_region,
254 );
255256// The "inputs" of the closure in the
257 // signature appear as a tuple. The MIR side
258 // flattens this tuple.
259let (&output, tuplized_inputs) =
260 inputs_and_output.skip_binder().split_last().unwrap();
261assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
262let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
263bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]);
264 };
265266 ty::Binder::bind_with_vars(
267 tcx.mk_type_list_from_iter(
268 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
269 ),
270 bound_vars,
271 )
272 }
273274 DefiningTy::Coroutine(def_id, args) => {
275let resume_ty = args.as_coroutine().resume_ty();
276let output = args.as_coroutine().return_ty();
277let coroutine_ty = Ty::new_coroutine(tcx, def_id, args);
278let inputs_and_output = tcx.mk_type_list(&[coroutine_ty, resume_ty, output]);
279 ty::Binder::dummy(inputs_and_output)
280 }
281282// Construct the signature of the CoroutineClosure for the purposes of borrowck.
283 // This is pretty straightforward -- we:
284 // 1. first grab the `coroutine_closure_sig`,
285 // 2. compute the self type (`&`/`&mut`/no borrow),
286 // 3. flatten the tupled_input_tys,
287 // 4. construct the correct generator type to return with
288 // `CoroutineClosureSignature::to_coroutine_given_kind_and_upvars`.
289 // Then we wrap it all up into a list of inputs and output.
290DefiningTy::CoroutineClosure(def_id, args) => {
291let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
292let bound_vars = self.bound_vars(tcx);
293let br = ty::BoundRegion {
294 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
295 kind: ty::BoundRegionKind::ClosureEnv,
296 };
297let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
298let closure_kind = args.as_coroutine_closure().kind();
299300let closure_ty = tcx.closure_env_ty(
301 Ty::new_coroutine_closure(tcx, def_id, args),
302 closure_kind,
303 env_region,
304 );
305306let inputs = closure_sig.skip_binder().tupled_inputs_ty.tuple_fields();
307let output = closure_sig.skip_binder().to_coroutine_given_kind_and_upvars(
308 tcx,
309 args.as_coroutine_closure().parent_args(),
310 tcx.coroutine_for_closure(def_id),
311 closure_kind,
312 env_region,
313 args.as_coroutine_closure().tupled_upvars_ty(),
314 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
315 );
316317 ty::Binder::bind_with_vars(
318 tcx.mk_type_list_from_iter(
319 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
320 ),
321 bound_vars,
322 )
323 }
324325 DefiningTy::FnDef(def_id, _) => {
326let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
327let inputs_and_output = sig.inputs_and_output();
328329// C-variadic fns also have a `VaList` input that's not listed in the signature
330 // (as it's created inside the body itself, not passed in from outside).
331if tcx.fn_sig(def_id).skip_binder().c_variadic() {
332let va_list_did = tcx.require_lang_item(LangItem::VaList, tcx.def_span(def_id));
333334let bound_vars = self.bound_vars(tcx);
335let br = ty::BoundRegion {
336 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
337 kind: ty::BoundRegionKind::Anon,
338 };
339let region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
340let va_list_ty =
341 tcx.type_of(va_list_did).instantiate(tcx, &[region.into()]).skip_norm_wip();
342343// The signature needs to follow the order [input_tys, va_list_ty, output_ty]
344let (output_ty, input_tys) =
345 inputs_and_output.skip_binder().split_last().unwrap();
346return ty::Binder::bind_with_vars(
347 tcx.mk_type_list_from_iter(
348 input_tys.iter().copied().chain([va_list_ty, *output_ty]),
349 ),
350 bound_vars,
351 );
352 }
353354 inputs_and_output
355 }
356357 DefiningTy::Const(def_id, _) => {
358// For a constant body, there are no inputs, and one
359 // "output" (the type of the constant).
360let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
361 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
362 }
363364 DefiningTy::InlineConst(_def_id, args) => {
365let ty = args.as_inline_const().ty();
366 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
367 }
368369 DefiningTy::GlobalAsm(def_id) => ty::Binder::dummy(
370 tcx.mk_type_list(&[tcx.type_of(def_id).instantiate_identity().skip_norm_wip()]),
371 ),
372 }
373 }
374375/// Returns a list of all the upvar types for this MIR. If this is
376 /// not a closure or coroutine, there are no upvars, and hence it
377 /// will be an empty list. The order of types in this list will
378 /// match up with the upvar order in the HIR, typesystem, and MIR.
379pub(crate) fn upvar_tys(self) -> &'tcx ty::List<Ty<'tcx>> {
380match self {
381 DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(),
382 DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().upvar_tys(),
383 DefiningTy::Coroutine(_, args) => args.as_coroutine().upvar_tys(),
384 DefiningTy::FnDef(..)
385 | DefiningTy::Const(..)
386 | DefiningTy::InlineConst(..)
387 | DefiningTy::GlobalAsm(_) => ty::List::empty(),
388 }
389 }
390391/// Number of implicit inputs -- notably the "environment"
392 /// parameter for closures -- that appear in MIR but not in the
393 /// user's code.
394pub(crate) fn implicit_inputs(self) -> usize {
395match self {
396 DefiningTy::Closure(..)
397 | DefiningTy::CoroutineClosure(..)
398 | DefiningTy::Coroutine(..) => 1,
399 DefiningTy::FnDef(..)
400 | DefiningTy::Const(..)
401 | DefiningTy::InlineConst(..)
402 | DefiningTy::GlobalAsm(_) => 0,
403 }
404 }
405406pub(crate) fn is_fn_def(&self) -> bool {
407#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::FnDef(..) => true,
_ => false,
}matches!(*self, DefiningTy::FnDef(..))408 }
409410pub(crate) fn is_const(&self) -> bool {
411#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::Const(..) | DefiningTy::InlineConst(..) => true,
_ => false,
}matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))412 }
413414pub(crate) fn def_id(&self) -> DefId {
415match *self {
416 DefiningTy::Closure(def_id, ..)
417 | DefiningTy::CoroutineClosure(def_id, ..)
418 | DefiningTy::Coroutine(def_id, ..)
419 | DefiningTy::FnDef(def_id, ..)
420 | DefiningTy::Const(def_id, ..)
421 | DefiningTy::InlineConst(def_id, ..)
422 | DefiningTy::GlobalAsm(def_id) => def_id,
423 }
424 }
425426/// Returns the args of the `DefiningTy`. These are equivalent to the identity
427 /// substs of the body, but replaced with region vids.
428pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> {
429match *self {
430 DefiningTy::Closure(_, args)
431 | DefiningTy::Coroutine(_, args)
432 | DefiningTy::CoroutineClosure(_, args)
433 | DefiningTy::FnDef(_, args)
434 | DefiningTy::Const(_, args)
435 | DefiningTy::InlineConst(_, args) => args,
436 DefiningTy::GlobalAsm(_) => ty::List::empty(),
437 }
438 }
439}
440441#[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", &self.indices, "fr_static",
&self.fr_static, "encountered_re_error",
&&self.encountered_re_error)
}
}Debug)]
442#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for UniversalRegionIndices<'tcx> {
#[inline]
fn clone(&self) -> UniversalRegionIndices<'tcx> {
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)
443struct UniversalRegionIndices<'tcx> {
444/// For those regions that may appear in the parameter environment
445 /// ('static and early-bound regions), we maintain a map from the
446 /// `ty::Region` to the internal `RegionVid` we are using. This is
447 /// used because trait matching and type-checking will feed us
448 /// region constraints that reference those regions and we need to
449 /// be able to map them to our internal `RegionVid`.
450 ///
451 /// This is similar to just using `GenericArgs`, except that it contains
452 /// an entry for `'static`, and also late bound parameters in scope.
453indices: FxIndexMap<ty::Region<'tcx>, RegionVid>,
454455/// The vid assigned to `'static`. Used only for diagnostics.
456pub fr_static: RegionVid,
457458/// Whether we've encountered an error region. If we have, cancel all
459 /// outlives errors, as they are likely bogus.
460pub encountered_re_error: Cell<Option<ErrorGuaranteed>>,
461}
462463#[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: &RegionClassification) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
464pub(crate) enum RegionClassification {
465/// A **global** region is one that can be named from
466 /// anywhere. There is only one, `'static`.
467Global,
468469/// An **external** region is only relevant for
470 /// closures, coroutines, and inline consts. In that
471 /// case, it refers to regions that are free in the type
472 /// -- basically, something bound in the surrounding context.
473 ///
474 /// Consider this example:
475 ///
476 /// ```ignore (pseudo-rust)
477 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
478 /// let closure = for<'x> |x: &'x u32| { .. };
479 /// // ^^^^^^^ pretend this were legal syntax
480 /// // for declaring a late-bound region in
481 /// // a closure signature
482 /// }
483 /// ```
484 ///
485 /// Here, the lifetimes `'a` and `'b` would be **external** to the
486 /// closure.
487 ///
488 /// If we are not analyzing a closure/coroutine/inline-const,
489 /// there are no external lifetimes.
490External,
491492/// A **local** lifetime is one about which we know the full set
493 /// of relevant constraints (that is, relationships to other named
494 /// regions). For a closure, this includes any region bound in
495 /// the closure's signature. For a fn item, this includes all
496 /// regions other than global ones.
497 ///
498 /// Continuing with the example from `External`, if we were
499 /// analyzing the closure, then `'x` would be local (and `'a` and
500 /// `'b` are external). If we are analyzing the function item
501 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
502 /// scope).
503Local,
504}
505506const FIRST_GLOBAL_INDEX: usize = 0;
507508impl<'tcx> UniversalRegions<'tcx> {
509/// Creates a new and fully initialized `UniversalRegions` that
510 /// contains indices for all the free regions found in the given
511 /// MIR -- that is, all the regions that appear in the function's
512 /// signature.
513pub(crate) fn new(infcx: &BorrowckInferCtxt<'tcx>, mir_def: LocalDefId) -> Self {
514UniversalRegionsBuilder { infcx, mir_def }.build()
515 }
516517/// Given a reference to a closure type, extracts all the values
518 /// from its free regions and returns a vector with them. This is
519 /// used when the closure's creator checks that the
520 /// `ClosureRegionRequirements` are met. The requirements from
521 /// `ClosureRegionRequirements` are expressed in terms of
522 /// `RegionVid` entries that map into the returned vector `V`: so
523 /// if the `ClosureRegionRequirements` contains something like
524 /// `'1: '2`, then the caller would impose the constraint that
525 /// `V[1]: V[2]`.
526pub(crate) fn closure_mapping(
527 tcx: TyCtxt<'tcx>,
528 closure_args: GenericArgsRef<'tcx>,
529 expected_num_vars: usize,
530 closure_def_id: LocalDefId,
531 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
532let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
533region_mapping.push(tcx.lifetimes.re_static);
534tcx.for_each_free_region(&closure_args, |fr| {
535region_mapping.push(fr);
536 });
537538for_each_late_bound_region_in_recursive_scope(tcx, tcx.local_parent(closure_def_id), |r| {
539region_mapping.push(r);
540 });
541542{
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!(
543 region_mapping.len(),
544 expected_num_vars,
545"index vec had unexpected number of variables"
546);
547548region_mapping549 }
550551/// Returns `true` if `r` is a member of this set of universal regions.
552pub(crate) fn is_universal_region(&self, r: RegionVid) -> bool {
553 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
554 }
555556/// Classifies `r` as a universal region, returning `None` if this
557 /// is not a member of this set of universal regions.
558pub(crate) fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
559let index = r.index();
560if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
561Some(RegionClassification::Global)
562 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
563Some(RegionClassification::External)
564 } else if (self.first_local_index..self.num_universals).contains(&index) {
565Some(RegionClassification::Local)
566 } else {
567None568 }
569 }
570571/// Returns an iterator over all the RegionVids corresponding to
572 /// universally quantified free regions.
573pub(crate) fn universal_regions_iter(&self) -> impl Iterator<Item = RegionVid> + 'static {
574 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize)
575 }
576577/// Returns `true` if `r` is classified as a local region.
578pub(crate) fn is_local_free_region(&self, r: RegionVid) -> bool {
579self.region_classification(r) == Some(RegionClassification::Local)
580 }
581582pub(crate) fn is_external_free_region(&self, r: RegionVid) -> bool {
583self.region_classification(r) == Some(RegionClassification::External)
584 }
585586/// Returns the number of universal regions created in any category.
587pub(crate) fn len(&self) -> usize {
588self.num_universals
589 }
590591/// Returns the number of global plus external universal regions.
592 /// For closures, these are the regions that appear free in the
593 /// closure type (versus those bound in the closure
594 /// signature). They are therefore the regions between which the
595 /// closure may impose constraints that its creator must verify.
596pub(crate) fn num_global_and_external_regions(&self) -> usize {
597self.first_local_index
598 }
599600/// Gets an iterator over all early bound regions starting with `'static`.
601pub(crate) fn named_universal_regions_iter(
602&self,
603 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> {
604self.indices.indices.iter().map(|(&r, &v)| (r, v))
605 }
606607/// See [UniversalRegionIndices::to_region_vid].
608pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
609self.indices.to_region_vid(r)
610 }
611612/// As part of the NLL unit tests, you can annotate a function with
613 /// `#[rustc_regions]`, and we will emit information about the region
614 /// inference context and -- in particular -- the external constraints
615 /// that this region imposes on others. The methods in this file
616 /// handle the part about dumping the inference context internal
617 /// state.
618pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
619match self.defining_ty {
620 DefiningTy::Closure(def_id, args) => {
621let v = {
let _guard = NoTrimmedGuard::new();
args[tcx.generics_of(def_id).parent_count..].iter().map(|arg|
arg.to_string()).collect::<Vec<_>>()
}with_no_trimmed_paths!(
622 args[tcx.generics_of(def_id).parent_count..]
623 .iter()
624 .map(|arg| arg.to_string())
625 .collect::<Vec<_>>()
626 );
627err.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!(
628"defining type: {} with closure args [\n {},\n]",
629 tcx.def_path_str_with_args(def_id, args),
630 v.join(",\n "),
631 ));
632633// FIXME: It'd be nice to print the late-bound regions
634 // here, but unfortunately these wind up stored into
635 // tests, and the resulting print-outs include def-ids
636 // and other things that are not stable across tests!
637 // So we just include the region-vid. Annoying.
638for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
639err.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)));
640 });
641 }
642 DefiningTy::CoroutineClosure(..) => {
643::core::panicking::panic("not implemented")unimplemented!()644 }
645 DefiningTy::Coroutine(def_id, args) => {
646let v = {
let _guard = NoTrimmedGuard::new();
args[tcx.generics_of(def_id).parent_count..].iter().map(|arg|
arg.to_string()).collect::<Vec<_>>()
}with_no_trimmed_paths!(
647 args[tcx.generics_of(def_id).parent_count..]
648 .iter()
649 .map(|arg| arg.to_string())
650 .collect::<Vec<_>>()
651 );
652err.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!(
653"defining type: {} with coroutine args [\n {},\n]",
654 tcx.def_path_str_with_args(def_id, args),
655 v.join(",\n "),
656 ));
657658// FIXME: As above, we'd like to print out the region
659 // `r` but doing so is not stable across architectures
660 // and so forth.
661for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
662err.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)));
663 });
664 }
665 DefiningTy::FnDef(def_id, args) => {
666err.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),));
667 }
668 DefiningTy::Const(def_id, args) => {
669err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining constant type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!(
670"defining constant type: {}",
671 tcx.def_path_str_with_args(def_id, args),
672 ));
673 }
674 DefiningTy::InlineConst(def_id, args) => {
675err.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!(
676"defining inline constant type: {}",
677 tcx.def_path_str_with_args(def_id, args),
678 ));
679 }
680 DefiningTy::GlobalAsm(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
681 }
682 }
683684pub(crate) fn implicit_region_bound(&self) -> RegionVid {
685self.fr_fn_body
686 }
687688pub(crate) fn encountered_re_error(&self) -> Option<ErrorGuaranteed> {
689self.indices.encountered_re_error.get()
690 }
691}
692693struct UniversalRegionsBuilder<'a, 'tcx> {
694 infcx: &'a BorrowckInferCtxt<'tcx>,
695 mir_def: LocalDefId,
696}
697698impl<'tcx> UniversalRegionsBuilder<'_, 'tcx> {
699fn build(self) -> UniversalRegions<'tcx> {
700{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:700",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(700u32),
::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);
701702let param_env = self.infcx.param_env;
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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:703",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/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: param_env={0:?}",
param_env) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: param_env={:?}", param_env);
704705{
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());
706707// Create the "global" region that is always free in all contexts: 'static.
708let fr_static = self709 .infcx
710 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
711 RegionCtxt::Free(kw::Static)
712 })
713 .as_var();
714715// We've now added all the global regions. The next ones we
716 // add will be external.
717let first_extern_index = self.infcx.num_region_vars();
718719let defining_ty = self.defining_ty();
720{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:720",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(720u32),
::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);
721722let mut indices = self.compute_indices(fr_static, 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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:723",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/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: indices={0:?}",
indices) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: indices={:?}", indices);
724725// If this is a 'root' body (not a closure/coroutine/inline const), then
726 // there are no extern regions, so the local regions start at the same
727 // position as the (empty) sub-list of extern regions
728let first_local_index = if !self.infcx.tcx.is_typeck_child(self.mir_def.to_def_id()) {
729first_extern_index730 } else {
731// If this is a closure, coroutine, or inline-const, then the late-bound regions from the enclosing
732 // function/closures are actually external regions to us. For example, here, 'a is not local
733 // to the closure c (although it is local to the fn foo). We need to add them as they could be
734 // explicitly named in this body:
735 //
736 // fn foo<'a>() {
737 // let c = || { let x: &'a u32 = ...; }
738 // }
739for_each_late_bound_region_in_recursive_scope(
740self.infcx.tcx,
741self.infcx.tcx.local_parent(self.mir_def),
742 |r| {
743{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:743",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(743u32),
::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);
744let region_vid = {
745let name = r.get_name_or_anon(self.infcx.tcx);
746self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
747 RegionCtxt::LateBound(name)
748 })
749 };
750751{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:751",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(751u32),
::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);
752indices.insert_late_bound_region(r, region_vid.as_var());
753 },
754 );
755756// Any regions created during the execution of `defining_ty` or during the above
757 // late-bound region replacement are all considered 'extern' regions
758self.infcx.num_region_vars()
759 };
760761// Converse of above, if this is a function/closure then the late-bound regions declared
762 // on its signature are local.
763 //
764 // We manually loop over `bound_inputs_and_output` instead of using
765 // `for_each_late_bound_region_in_item` as both closures and function
766 // definitions have implicit late bound regions. Closures have a `'env`
767 // regions while c-variadic function definitions have a `&VaList` argument.
768let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
769for (idx, bound_var) in bound_inputs_and_output.bound_vars().iter().enumerate() {
770if let ty::BoundVariableKind::Region(kind) = bound_var {
771let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
772let r = ty::Region::new_late_param(self.infcx.tcx, self.mir_def.to_def_id(), kind);
773let region_vid = {
774let name = r.get_name_or_anon(self.infcx.tcx);
775self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
776 RegionCtxt::LateBound(name)
777 })
778 };
779780{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:780",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(780u32),
::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);
781 indices.insert_late_bound_region(r, region_vid.as_var());
782 }
783 }
784let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
785self.mir_def,
786bound_inputs_and_output,
787&indices,
788 );
789790let (unnormalized_output_ty, unnormalized_input_tys) =
791inputs_and_output.split_last().unwrap();
792793let fr_fn_body = self794 .infcx
795 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
796 RegionCtxt::Free(sym::fn_body)
797 })
798 .as_var();
799800let num_universals = self.infcx.num_region_vars();
801802{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:802",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(802u32),
::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);
803{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:803",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(803u32),
::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);
804{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:804",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(804u32),
::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);
805806let (resume_ty, yield_ty) = match defining_ty {
807 DefiningTy::Coroutine(_, args) => {
808let tys = args.as_coroutine();
809 (Some(tys.resume_ty()), Some(tys.yield_ty()))
810 }
811_ => (None, None),
812 };
813814UniversalRegions {
815indices,
816fr_static,
817fr_fn_body,
818first_extern_index,
819first_local_index,
820num_universals,
821defining_ty,
822 unnormalized_output_ty: *unnormalized_output_ty,
823unnormalized_input_tys,
824yield_ty,
825resume_ty,
826 }
827 }
828829/// Returns the "defining type" of the current MIR; see `DefiningTy` for details.
830fn defining_ty(&self) -> DefiningTy<'tcx> {
831let defining_ty = DefiningTy::new(self.infcx.tcx, self.mir_def);
832let f = |args| {
833let fr = NllRegionVariableOrigin::FreeRegion;
834self.infcx.replace_free_regions_with_nll_infer_vars(fr, args)
835 };
836match defining_ty {
837 DefiningTy::Closure(def_id, args) => DefiningTy::Closure(def_id, f(args)),
838 DefiningTy::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, f(args)),
839 DefiningTy::CoroutineClosure(def_id, args) => {
840 DefiningTy::CoroutineClosure(def_id, f(args))
841 }
842 DefiningTy::FnDef(def_id, args) => DefiningTy::FnDef(def_id, f(args)),
843 DefiningTy::Const(def_id, args) => DefiningTy::Const(def_id, f(args)),
844 DefiningTy::InlineConst(def_id, args) => DefiningTy::InlineConst(def_id, f(args)),
845 DefiningTy::GlobalAsm(def_id) => DefiningTy::GlobalAsm(def_id),
846 }
847 }
848849/// Builds a hashmap that maps from the universal regions that are
850 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
851 /// `RegionVid`). The map returned by this function contains only
852 /// the early-bound regions.
853fn compute_indices(
854&self,
855 fr_static: RegionVid,
856 defining_ty: DefiningTy<'tcx>,
857 ) -> UniversalRegionIndices<'tcx> {
858let tcx = self.infcx.tcx;
859let typeck_root_def_id = tcx.typeck_root_def_id_local(self.mir_def);
860let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
861let renumbered_args = defining_ty.args();
862863let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
864// This relies on typeck roots being generics_of parents with their
865 // parameters at the start of nested bodies' generics.
866if !(renumbered_args.len() >= identity_args.len()) {
::core::panicking::panic("assertion failed: renumbered_args.len() >= identity_args.len()")
};assert!(renumbered_args.len() >= identity_args.len());
867let arg_mapping =
868 iter::zip(identity_args.regions(), renumbered_args.regions().map(|r| r.as_var()));
869870UniversalRegionIndices {
871 indices: global_mapping.chain(arg_mapping).collect(),
872fr_static,
873 encountered_re_error: Cell::new(None),
874 }
875 }
876877fn compute_inputs_and_output(
878&self,
879 indices: &UniversalRegionIndices<'tcx>,
880 defining_ty: DefiningTy<'tcx>,
881 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
882let tcx = self.infcx.tcx;
883let inputs_and_output = defining_ty.inputs_and_output(tcx);
884let inputs_and_output = indices.fold_to_region_vids(tcx, inputs_and_output);
885886// FIXME(#129952): We probably want a more principled approach here.
887if let Err(e) = inputs_and_output.error_reported() {
888self.infcx.set_tainted_by_errors(e);
889 }
890891inputs_and_output892 }
893}
894895trait 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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(897u32),
::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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:908",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(908u32),
::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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(914u32),
::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/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:925",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(925u32),
::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>)]896impl<'tcx> BorrowckInferCtxt<'tcx> {
897#[instrument(skip(self), level = "debug")]
898fn replace_free_regions_with_nll_infer_vars<T>(
899&self,
900 origin: NllRegionVariableOrigin<'tcx>,
901 value: T,
902 ) -> T
903where
904T: TypeFoldable<TyCtxt<'tcx>>,
905 {
906 fold_regions(self.infcx.tcx, value, |region, _depth| {
907let name = region.get_name_or_anon(self.infcx.tcx);
908debug!(?region, ?name);
909910self.next_nll_region_var(origin, || RegionCtxt::Free(name))
911 })
912 }
913914#[instrument(level = "debug", skip(self, indices))]
915fn replace_bound_regions_with_nll_infer_vars<T>(
916&self,
917 all_outlive_scope: LocalDefId,
918 value: ty::Binder<'tcx, T>,
919 indices: &UniversalRegionIndices<'tcx>,
920 ) -> T
921where
922T: TypeFoldable<TyCtxt<'tcx>>,
923 {
924let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
925debug!(?br);
926let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
927let liberated_region =
928 ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
929 ty::Region::new_var(self.tcx, indices.to_region_vid(liberated_region))
930 });
931 value
932 }
933}
934935impl<'tcx> UniversalRegionIndices<'tcx> {
936/// Initially, the `UniversalRegionIndices` map contains only the
937 /// early-bound regions in scope. Once that is all setup, we come
938 /// in later and instantiate the late-bound regions, and then we
939 /// insert the `ReLateParam` version of those into the map as
940 /// well. These are used for error reporting.
941fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
942{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs:942",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/2e2b193f8ada105f27608b7be81c293e0d7292cb/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(942u32),
::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);
943{
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);
944 }
945946/// Converts `r` into a local inference variable: `r` can either
947 /// be a `ReVar` (i.e., already a reference to an inference
948 /// variable) or it can be `'static` or some early-bound
949 /// region. This is useful when taking the results from
950 /// type-checking and trait-matching, which may sometimes
951 /// reference those regions from the `ParamEnv`. It is also used
952 /// during initialization. Relies on the `indices` map having been
953 /// fully initialized.
954 ///
955 /// Panics if `r` is not a registered universal region, most notably
956 /// if it is a placeholder. Handling placeholders requires access to the
957 /// `MirTypeckRegionConstraints`.
958fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
959match r.kind() {
960 ty::ReVar(..) => r.as_var(),
961 ty::ReError(guar) => {
962self.encountered_re_error.set(Some(guar));
963// We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
964 // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
965 // errors are being emitted and 2) it leaves the happy path unaffected.
966self.fr_static
967 }
968_ => *self969 .indices
970 .get(&r)
971 .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("cannot convert `{0:?}` to a region vid",
r))bug!("cannot convert `{:?}` to a region vid", r)),
972 }
973 }
974975/// Replaces all free regions in `value` with region vids, as
976 /// returned by `to_region_vid`.
977fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
978where
979T: TypeFoldable<TyCtxt<'tcx>>,
980 {
981fold_regions(tcx, value, |region, _| ty::Region::new_var(tcx, self.to_region_vid(region)))
982 }
983}
984985/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
986/// parents, up to the typeck root, and invokes `f` with the liberated form
987/// of each one.
988fn for_each_late_bound_region_in_recursive_scope<'tcx>(
989 tcx: TyCtxt<'tcx>,
990mut mir_def_id: LocalDefId,
991mut f: impl FnMut(ty::Region<'tcx>),
992) {
993// Walk up the tree, collecting late-bound regions until we hit the typeck root
994loop {
995for_each_late_bound_region_in_item(tcx, mir_def_id, &mut f);
996997if tcx.is_typeck_child(mir_def_id.to_def_id()) {
998mir_def_id = tcx.local_parent(mir_def_id);
999 } else {
1000break;
1001 }
1002 }
1003}
10041005/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
1006/// parents, up to the typeck root, and invokes `f` with the liberated form
1007/// of each one.
1008fn for_each_late_bound_region_in_item<'tcx>(
1009 tcx: TyCtxt<'tcx>,
1010 mir_def_id: LocalDefId,
1011mut f: impl FnMut(ty::Region<'tcx>),
1012) {
1013let bound_vars = match tcx.def_kind(mir_def_id) {
1014 DefKind::Fn | DefKind::AssocFn => {
1015tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id))
1016 }
1017// We extract the bound vars from the deduced closure signature, since we may have
1018 // only deduced that a param in the closure signature is late-bound from a constraint
1019 // that we discover during typeck.
1020DefKind::Closure => {
1021let ty = tcx.type_of(mir_def_id).instantiate_identity().skip_norm_wip();
1022match *ty.kind() {
1023 ty::Closure(_, args) => args.as_closure().sig().bound_vars(),
1024 ty::CoroutineClosure(_, args) => {
1025args.as_coroutine_closure().coroutine_closure_sig().bound_vars()
1026 }
1027 ty::Coroutine(_, _) | ty::Error(_) => return,
1028_ => {
::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}"),
1029 }
1030 }
1031_ => return,
1032 };
10331034for (idx, bound_var) in bound_vars.iter().enumerate() {
1035if let ty::BoundVariableKind::Region(kind) = bound_var {
1036let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
1037let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind);
1038 f(liberated_region);
1039 }
1040 }
1041}