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, RegionVid, Ty, 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 _ =
&["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)]
39#[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)
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) -> 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)]
99pub(crate) enum DefiningTy<'tcx> {
100/// The MIR is a closure. The signature is found via
101 /// `ClosureArgs::closure_sig_ty`.
102Closure(DefId, GenericArgsRef<'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, GenericArgsRef<'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, GenericArgsRef<'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, GenericArgsRef<'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, GenericArgsRef<'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, GenericArgsRef<'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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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())
}
_ =>
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, 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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:136",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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(tcx, InlineConstArgsParts { parent_args, ty }).args;
183 DefiningTy::InlineConst(body_def_id.to_def_id(), args)
184 }
185186 BodyOwnerKind::Const { inline: false } | BodyOwnerKind::Static(..) => {
187let args = GenericArgs::identity_for_item(tcx, body_def_id.to_def_id());
188 DefiningTy::Const(body_def_id.to_def_id(), args)
189 }
190191 BodyOwnerKind::GlobalAsm => DefiningTy::GlobalAsm(body_def_id.to_def_id()),
192 }
193 }
194195/// The bound variables for a given defining type. This differs from their usual bound vars
196 /// in that closures and coroutine closures have an additional `'env`, while C-variadic
197 /// functions have an additional region for their implicit `VaList` input.
198pub(crate) fn bound_vars(self, tcx: TyCtxt<'tcx>) -> &'tcx List<BoundVariableKind<'tcx>> {
199match self {
200 DefiningTy::Closure(_, args) => {
201let closure_sig = args.as_closure().sig();
202let inputs_and_output = closure_sig.inputs_and_output();
203tcx.mk_bound_variable_kinds_from_iter(inputs_and_output.bound_vars().iter().chain(
204 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
205 ))
206 }
207208 DefiningTy::CoroutineClosure(_, args) => {
209let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
210tcx.mk_bound_variable_kinds_from_iter(closure_sig.bound_vars().iter().chain(
211 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
212 ))
213 }
214215 DefiningTy::FnDef(def_id, _) => {
216let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
217if sig.skip_binder().c_variadic() {
218// FIXME(#160495): Don't use an anonymous region here
219tcx.mk_bound_variable_kinds_from_iter(sig.bound_vars().iter().chain(
220 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon)),
221 ))
222 } else {
223sig.bound_vars()
224 }
225 }
226227 DefiningTy::Coroutine(..)
228 | DefiningTy::Const(..)
229 | DefiningTy::InlineConst(..)
230 | DefiningTy::GlobalAsm(..) => ty::List::empty(),
231 }
232 }
233234{}
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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(234u32),
::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 {
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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:234",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(234u32),
::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)]235pub(crate) fn inputs_and_output(
236self,
237 tcx: TyCtxt<'tcx>,
238 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
239match self {
240 DefiningTy::Closure(def_id, args) => {
241let closure_sig = args.as_closure().sig();
242let inputs_and_output = closure_sig.inputs_and_output();
243let bound_vars = self.bound_vars(tcx);
244let br = ty::BoundRegion {
245 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
246 kind: ty::BoundRegionKind::ClosureEnv,
247 };
248let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
249let closure_ty = tcx.closure_env_ty(
250 Ty::new_closure(tcx, def_id, args),
251 args.as_closure().kind(),
252 env_region,
253 );
254255// The "inputs" of the closure in the
256 // signature appear as a tuple. The MIR side
257 // flattens this tuple.
258let (&output, tuplized_inputs) =
259 inputs_and_output.skip_binder().split_last().unwrap();
260assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
261let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
262bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]);
263 };
264265 ty::Binder::bind_with_vars(
266 tcx.mk_type_list_from_iter(
267 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
268 ),
269 bound_vars,
270 )
271 }
272273 DefiningTy::Coroutine(def_id, args) => {
274let resume_ty = args.as_coroutine().resume_ty();
275let output = args.as_coroutine().return_ty();
276let coroutine_ty = Ty::new_coroutine(tcx, def_id, args);
277let inputs_and_output = tcx.mk_type_list(&[coroutine_ty, resume_ty, output]);
278 ty::Binder::dummy(inputs_and_output)
279 }
280281// Construct the signature of the CoroutineClosure for the purposes of borrowck.
282 // This is pretty straightforward -- we:
283 // 1. first grab the `coroutine_closure_sig`,
284 // 2. compute the self type (`&`/`&mut`/no borrow),
285 // 3. flatten the tupled_input_tys,
286 // 4. construct the correct generator type to return with
287 // `CoroutineClosureSignature::to_coroutine_given_kind_and_upvars`.
288 // Then we wrap it all up into a list of inputs and output.
289DefiningTy::CoroutineClosure(def_id, args) => {
290let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
291let bound_vars = self.bound_vars(tcx);
292let br = ty::BoundRegion {
293 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
294 kind: ty::BoundRegionKind::ClosureEnv,
295 };
296let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
297let closure_kind = args.as_coroutine_closure().kind();
298299let closure_ty = tcx.closure_env_ty(
300 Ty::new_coroutine_closure(tcx, def_id, args),
301 closure_kind,
302 env_region,
303 );
304305let inputs = closure_sig.skip_binder().tupled_inputs_ty.tuple_fields();
306let output = closure_sig.skip_binder().to_coroutine_given_kind_and_upvars(
307 tcx,
308 args.as_coroutine_closure().parent_args(),
309 tcx.coroutine_for_closure(def_id),
310 closure_kind,
311 env_region,
312 args.as_coroutine_closure().tupled_upvars_ty(),
313 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
314 );
315316 ty::Binder::bind_with_vars(
317 tcx.mk_type_list_from_iter(
318 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
319 ),
320 bound_vars,
321 )
322 }
323324 DefiningTy::FnDef(def_id, _) => {
325let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
326let inputs_and_output = sig.inputs_and_output();
327328// C-variadic fns also have a `VaList` input that's not listed in the signature
329 // (as it's created inside the body itself, not passed in from outside).
330if tcx.fn_sig(def_id).skip_binder().c_variadic() {
331let va_list_did = tcx.require_lang_item(LangItem::VaList, tcx.def_span(def_id));
332333let bound_vars = self.bound_vars(tcx);
334let br = ty::BoundRegion {
335 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
336 kind: ty::BoundRegionKind::Anon,
337 };
338let region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
339let va_list_ty =
340 tcx.type_of(va_list_did).instantiate(tcx, &[region.into()]).skip_norm_wip();
341342// The signature needs to follow the order [input_tys, va_list_ty, output_ty]
343let (output_ty, input_tys) =
344 inputs_and_output.skip_binder().split_last().unwrap();
345return ty::Binder::bind_with_vars(
346 tcx.mk_type_list_from_iter(
347 input_tys.iter().copied().chain([va_list_ty, *output_ty]),
348 ),
349 bound_vars,
350 );
351 }
352353 inputs_and_output
354 }
355356 DefiningTy::Const(def_id, _) => {
357// For a constant body, there are no inputs, and one
358 // "output" (the type of the constant).
359let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
360 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
361 }
362363 DefiningTy::InlineConst(_def_id, args) => {
364let ty = args.as_inline_const().ty();
365 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
366 }
367368 DefiningTy::GlobalAsm(def_id) => ty::Binder::dummy(
369 tcx.mk_type_list(&[tcx.type_of(def_id).instantiate_identity().skip_norm_wip()]),
370 ),
371 }
372 }
373374/// Returns a list of all the upvar types for this MIR. If this is
375 /// not a closure or coroutine, there are no upvars, and hence it
376 /// will be an empty list. The order of types in this list will
377 /// match up with the upvar order in the HIR, typesystem, and MIR.
378pub(crate) fn upvar_tys(self) -> &'tcx ty::List<Ty<'tcx>> {
379match self {
380 DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(),
381 DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().upvar_tys(),
382 DefiningTy::Coroutine(_, args) => args.as_coroutine().upvar_tys(),
383 DefiningTy::FnDef(..)
384 | DefiningTy::Const(..)
385 | DefiningTy::InlineConst(..)
386 | DefiningTy::GlobalAsm(_) => ty::List::empty(),
387 }
388 }
389390/// Number of implicit inputs -- notably the "environment"
391 /// parameter for closures -- that appear in MIR but not in the
392 /// user's code.
393pub(crate) fn implicit_inputs(self) -> usize {
394match self {
395 DefiningTy::Closure(..)
396 | DefiningTy::CoroutineClosure(..)
397 | DefiningTy::Coroutine(..) => 1,
398 DefiningTy::FnDef(..)
399 | DefiningTy::Const(..)
400 | DefiningTy::InlineConst(..)
401 | DefiningTy::GlobalAsm(_) => 0,
402 }
403 }
404405pub(crate) fn is_fn_def(&self) -> bool {
406#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::FnDef(..) => true,
_ => false,
}matches!(*self, DefiningTy::FnDef(..))407 }
408409pub(crate) fn is_const(&self) -> bool {
410#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::Const(..) | DefiningTy::InlineConst(..) => true,
_ => false,
}matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))411 }
412413pub(crate) fn def_id(&self) -> DefId {
414match *self {
415 DefiningTy::Closure(def_id, ..)
416 | DefiningTy::CoroutineClosure(def_id, ..)
417 | DefiningTy::Coroutine(def_id, ..)
418 | DefiningTy::FnDef(def_id, ..)
419 | DefiningTy::Const(def_id, ..)
420 | DefiningTy::InlineConst(def_id, ..)
421 | DefiningTy::GlobalAsm(def_id) => def_id,
422 }
423 }
424425/// Returns the args of the `DefiningTy`. These are equivalent to the identity
426 /// substs of the body, but replaced with region vids.
427pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> {
428match *self {
429 DefiningTy::Closure(_, args)
430 | DefiningTy::Coroutine(_, args)
431 | DefiningTy::CoroutineClosure(_, args)
432 | DefiningTy::FnDef(_, args)
433 | DefiningTy::Const(_, args)
434 | DefiningTy::InlineConst(_, args) => args,
435 DefiningTy::GlobalAsm(_) => ty::List::empty(),
436 }
437 }
438}
439440#[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)]
441#[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)
442struct UniversalRegionIndices<'tcx> {
443/// For those regions that may appear in the parameter environment
444 /// ('static and early-bound regions), we maintain a map from the
445 /// `ty::Region` to the internal `RegionVid` we are using. This is
446 /// used because trait matching and type-checking will feed us
447 /// region constraints that reference those regions and we need to
448 /// be able to map them to our internal `RegionVid`.
449 ///
450 /// This is similar to just using `GenericArgs`, except that it contains
451 /// an entry for `'static`, and also late bound parameters in scope.
452indices: FxIndexMap<ty::Region<'tcx>, RegionVid>,
453454/// The vid assigned to `'static`. Used only for diagnostics.
455pub fr_static: RegionVid,
456457/// Whether we've encountered an error region. If we have, cancel all
458 /// outlives errors, as they are likely bogus.
459pub encountered_re_error: Cell<Option<ErrorGuaranteed>>,
460}
461462#[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)]
463pub(crate) enum RegionClassification {
464/// A **global** region is one that can be named from
465 /// anywhere. There is only one, `'static`.
466Global,
467468/// An **external** region is only relevant for
469 /// closures, coroutines, and inline consts. In that
470 /// case, it refers to regions that are free in the type
471 /// -- basically, something bound in the surrounding context.
472 ///
473 /// Consider this example:
474 ///
475 /// ```ignore (pseudo-rust)
476 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
477 /// let closure = for<'x> |x: &'x u32| { .. };
478 /// // ^^^^^^^ pretend this were legal syntax
479 /// // for declaring a late-bound region in
480 /// // a closure signature
481 /// }
482 /// ```
483 ///
484 /// Here, the lifetimes `'a` and `'b` would be **external** to the
485 /// closure.
486 ///
487 /// If we are not analyzing a closure/coroutine/inline-const,
488 /// there are no external lifetimes.
489External,
490491/// A **local** lifetime is one about which we know the full set
492 /// of relevant constraints (that is, relationships to other named
493 /// regions). For a closure, this includes any region bound in
494 /// the closure's signature. For a fn item, this includes all
495 /// regions other than global ones.
496 ///
497 /// Continuing with the example from `External`, if we were
498 /// analyzing the closure, then `'x` would be local (and `'a` and
499 /// `'b` are external). If we are analyzing the function item
500 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
501 /// scope).
502Local,
503}
504505const FIRST_GLOBAL_INDEX: usize = 0;
506507impl<'tcx> UniversalRegions<'tcx> {
508/// Creates a new and fully initialized `UniversalRegions` that
509 /// contains indices for all the free regions found in the given
510 /// MIR -- that is, all the regions that appear in the function's
511 /// signature.
512pub(crate) fn new(infcx: &BorrowckInferCtxt<'tcx>, mir_def: LocalDefId) -> Self {
513UniversalRegionsBuilder { infcx, mir_def }.build()
514 }
515516/// Given a reference to a closure type, extracts all the values
517 /// from its free regions and returns a vector with them. This is
518 /// used when the closure's creator checks that the
519 /// `ClosureRegionRequirements` are met. The requirements from
520 /// `ClosureRegionRequirements` are expressed in terms of
521 /// `RegionVid` entries that map into the returned vector `V`: so
522 /// if the `ClosureRegionRequirements` contains something like
523 /// `'1: '2`, then the caller would impose the constraint that
524 /// `V[1]: V[2]`.
525pub(crate) fn closure_mapping(
526 tcx: TyCtxt<'tcx>,
527 closure_args: GenericArgsRef<'tcx>,
528 expected_num_vars: usize,
529 closure_def_id: LocalDefId,
530 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
531let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
532region_mapping.push(tcx.lifetimes.re_static);
533tcx.for_each_free_region(&closure_args, |fr| {
534region_mapping.push(fr);
535 });
536537for_each_late_bound_region_in_recursive_scope(tcx, tcx.local_parent(closure_def_id), |r| {
538region_mapping.push(r);
539 });
540541{
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!(
542 region_mapping.len(),
543 expected_num_vars,
544"index vec had unexpected number of variables"
545);
546547region_mapping548 }
549550/// Returns `true` if `r` is a member of this set of universal regions.
551pub(crate) fn is_universal_region(&self, r: RegionVid) -> bool {
552 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
553 }
554555/// Classifies `r` as a universal region, returning `None` if this
556 /// is not a member of this set of universal regions.
557pub(crate) fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
558let index = r.index();
559if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
560Some(RegionClassification::Global)
561 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
562Some(RegionClassification::External)
563 } else if (self.first_local_index..self.num_universals).contains(&index) {
564Some(RegionClassification::Local)
565 } else {
566None567 }
568 }
569570/// Returns an iterator over all the RegionVids corresponding to
571 /// universally quantified free regions.
572pub(crate) fn universal_regions_iter(&self) -> impl Iterator<Item = RegionVid> + 'static {
573 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize)
574 }
575576/// Returns `true` if `r` is classified as a local region.
577pub(crate) fn is_local_free_region(&self, r: RegionVid) -> bool {
578self.region_classification(r) == Some(RegionClassification::Local)
579 }
580581pub(crate) fn is_external_free_region(&self, r: RegionVid) -> bool {
582self.region_classification(r) == Some(RegionClassification::External)
583 }
584585/// Returns the number of universal regions created in any category.
586pub(crate) fn len(&self) -> usize {
587self.num_universals
588 }
589590/// Returns the number of global plus external universal regions.
591 /// For closures, these are the regions that appear free in the
592 /// closure type (versus those bound in the closure
593 /// signature). They are therefore the regions between which the
594 /// closure may impose constraints that its creator must verify.
595pub(crate) fn num_global_and_external_regions(&self) -> usize {
596self.first_local_index
597 }
598599/// Gets an iterator over all early bound regions starting with `'static`.
600pub(crate) fn named_universal_regions_iter(
601&self,
602 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> {
603self.indices.indices.iter().map(|(&r, &v)| (r, v))
604 }
605606/// See [UniversalRegionIndices::to_region_vid].
607pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
608self.indices.to_region_vid(r)
609 }
610611/// As part of the NLL unit tests, you can annotate a function with
612 /// `#[rustc_regions]`, and we will emit information about the region
613 /// inference context and -- in particular -- the external constraints
614 /// that this region imposes on others. The methods in this file
615 /// handle the part about dumping the inference context internal
616 /// state.
617pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
618match self.defining_ty {
619 DefiningTy::Closure(def_id, args) => {
620let 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!(
621 args[tcx.generics_of(def_id).parent_count..]
622 .iter()
623 .map(|arg| arg.to_string())
624 .collect::<Vec<_>>()
625 );
626err.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!(
627"defining type: {} with closure args [\n {},\n]",
628 tcx.def_path_str_with_args(def_id, args),
629 v.join(",\n "),
630 ));
631632// FIXME: It'd be nice to print the late-bound regions
633 // here, but unfortunately these wind up stored into
634 // tests, and the resulting print-outs include def-ids
635 // and other things that are not stable across tests!
636 // So we just include the region-vid. Annoying.
637for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
638err.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)));
639 });
640 }
641 DefiningTy::CoroutineClosure(..) => {
642::core::panicking::panic("not implemented")unimplemented!()643 }
644 DefiningTy::Coroutine(def_id, args) => {
645let 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!(
646 args[tcx.generics_of(def_id).parent_count..]
647 .iter()
648 .map(|arg| arg.to_string())
649 .collect::<Vec<_>>()
650 );
651err.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!(
652"defining type: {} with coroutine args [\n {},\n]",
653 tcx.def_path_str_with_args(def_id, args),
654 v.join(",\n "),
655 ));
656657// FIXME: As above, we'd like to print out the region
658 // `r` but doing so is not stable across architectures
659 // and so forth.
660for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
661err.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)));
662 });
663 }
664 DefiningTy::FnDef(def_id, args) => {
665err.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),));
666 }
667 DefiningTy::Const(def_id, args) => {
668err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining constant type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!(
669"defining constant type: {}",
670 tcx.def_path_str_with_args(def_id, args),
671 ));
672 }
673 DefiningTy::InlineConst(def_id, args) => {
674err.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!(
675"defining inline constant type: {}",
676 tcx.def_path_str_with_args(def_id, args),
677 ));
678 }
679 DefiningTy::GlobalAsm(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
680 }
681 }
682683pub(crate) fn implicit_region_bound(&self) -> RegionVid {
684self.fr_fn_body
685 }
686687pub(crate) fn encountered_re_error(&self) -> Option<ErrorGuaranteed> {
688self.indices.encountered_re_error.get()
689 }
690}
691692struct UniversalRegionsBuilder<'a, 'tcx> {
693 infcx: &'a BorrowckInferCtxt<'tcx>,
694 mir_def: LocalDefId,
695}
696697impl<'tcx> UniversalRegionsBuilder<'_, 'tcx> {
698fn build(self) -> UniversalRegions<'tcx> {
699{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:699",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(699u32),
::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);
700701let param_env = self.infcx.param_env;
702{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:702",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(702u32),
::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);
703704{
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());
705706// Create the "global" region that is always free in all contexts: 'static.
707let fr_static = self708 .infcx
709 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
710 RegionCtxt::Free(kw::Static)
711 })
712 .as_var();
713714// We've now added all the global regions. The next ones we
715 // add will be external.
716let first_extern_index = self.infcx.num_region_vars();
717718let defining_ty = self.defining_ty();
719{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:719",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(719u32),
::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);
720721let mut indices = self.compute_indices(fr_static, defining_ty);
722{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:722",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(722u32),
::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);
723724// If this is a 'root' body (not a closure/coroutine/inline const), then
725 // there are no extern regions, so the local regions start at the same
726 // position as the (empty) sub-list of extern regions
727let first_local_index = if !self.infcx.tcx.is_typeck_child(self.mir_def.to_def_id()) {
728first_extern_index729 } else {
730// If this is a closure, coroutine, or inline-const, then the late-bound regions from the enclosing
731 // function/closures are actually external regions to us. For example, here, 'a is not local
732 // to the closure c (although it is local to the fn foo). We need to add them as they could be
733 // explicitly named in this body:
734 //
735 // fn foo<'a>() {
736 // let c = || { let x: &'a u32 = ...; }
737 // }
738for_each_late_bound_region_in_recursive_scope(
739self.infcx.tcx,
740self.infcx.tcx.local_parent(self.mir_def),
741 |r| {
742{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:742",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(742u32),
::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);
743let region_vid = {
744let name = r.get_name_or_anon(self.infcx.tcx);
745self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
746 RegionCtxt::LateBound(name)
747 })
748 };
749750{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:750",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(750u32),
::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);
751indices.insert_late_bound_region(r, region_vid.as_var());
752 },
753 );
754755// Any regions created during the execution of `defining_ty` or during the above
756 // late-bound region replacement are all considered 'extern' regions
757self.infcx.num_region_vars()
758 };
759760// Converse of above, if this is a function/closure then the late-bound regions declared
761 // on its signature are local.
762 //
763 // We manually loop over `bound_inputs_and_output` instead of using
764 // `for_each_late_bound_region_in_item` as both closures and function
765 // definitions have implicit late bound regions. Closures have a `'env`
766 // regions while c-variadic function definitions have a `&VaList` argument.
767let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
768for (idx, bound_var) in bound_inputs_and_output.bound_vars().iter().enumerate() {
769if let ty::BoundVariableKind::Region(kind) = bound_var {
770let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
771let r = ty::Region::new_late_param(self.infcx.tcx, self.mir_def.to_def_id(), kind);
772let region_vid = {
773let name = r.get_name_or_anon(self.infcx.tcx);
774self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
775 RegionCtxt::LateBound(name)
776 })
777 };
778779{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:779",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(779u32),
::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);
780 indices.insert_late_bound_region(r, region_vid.as_var());
781 }
782 }
783let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
784self.mir_def,
785bound_inputs_and_output,
786&indices,
787 );
788789let (unnormalized_output_ty, unnormalized_input_tys) =
790inputs_and_output.split_last().unwrap();
791792let fr_fn_body = self793 .infcx
794 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
795 RegionCtxt::Free(sym::fn_body)
796 })
797 .as_var();
798799let num_universals = self.infcx.num_region_vars();
800801{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:801",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(801u32),
::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);
802{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:802",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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: 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);
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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:803",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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: local regions = {0}..{1}",
first_local_index, num_universals) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: local regions = {}..{}", first_local_index, num_universals);
804805let (resume_ty, yield_ty) = match defining_ty {
806 DefiningTy::Coroutine(_, args) => {
807let tys = args.as_coroutine();
808 (Some(tys.resume_ty()), Some(tys.yield_ty()))
809 }
810_ => (None, None),
811 };
812813UniversalRegions {
814indices,
815fr_static,
816fr_fn_body,
817first_extern_index,
818first_local_index,
819num_universals,
820defining_ty,
821 unnormalized_output_ty: *unnormalized_output_ty,
822unnormalized_input_tys,
823yield_ty,
824resume_ty,
825 }
826 }
827828/// Returns the "defining type" of the current MIR; see `DefiningTy` for details.
829fn defining_ty(&self) -> DefiningTy<'tcx> {
830let defining_ty = DefiningTy::new(self.infcx.tcx, self.mir_def);
831let f = |args| {
832let fr = NllRegionVariableOrigin::FreeRegion;
833self.infcx.replace_free_regions_with_nll_infer_vars(fr, args)
834 };
835match defining_ty {
836 DefiningTy::Closure(def_id, args) => DefiningTy::Closure(def_id, f(args)),
837 DefiningTy::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, f(args)),
838 DefiningTy::CoroutineClosure(def_id, args) => {
839 DefiningTy::CoroutineClosure(def_id, f(args))
840 }
841 DefiningTy::FnDef(def_id, args) => DefiningTy::FnDef(def_id, f(args)),
842 DefiningTy::Const(def_id, args) => DefiningTy::Const(def_id, f(args)),
843 DefiningTy::InlineConst(def_id, args) => DefiningTy::InlineConst(def_id, f(args)),
844 DefiningTy::GlobalAsm(def_id) => DefiningTy::GlobalAsm(def_id),
845 }
846 }
847848/// Builds a hashmap that maps from the universal regions that are
849 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
850 /// `RegionVid`). The map returned by this function contains only
851 /// the early-bound regions.
852fn compute_indices(
853&self,
854 fr_static: RegionVid,
855 defining_ty: DefiningTy<'tcx>,
856 ) -> UniversalRegionIndices<'tcx> {
857let tcx = self.infcx.tcx;
858let typeck_root_def_id = tcx.typeck_root_def_id_local(self.mir_def);
859let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
860let renumbered_args = defining_ty.args();
861862let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
863// This relies on typeck roots being generics_of parents with their
864 // parameters at the start of nested bodies' generics.
865if !(renumbered_args.len() >= identity_args.len()) {
::core::panicking::panic("assertion failed: renumbered_args.len() >= identity_args.len()")
};assert!(renumbered_args.len() >= identity_args.len());
866let arg_mapping =
867 iter::zip(identity_args.regions(), renumbered_args.regions().map(|r| r.as_var()));
868869UniversalRegionIndices {
870 indices: global_mapping.chain(arg_mapping).collect(),
871fr_static,
872 encountered_re_error: Cell::new(None),
873 }
874 }
875876fn compute_inputs_and_output(
877&self,
878 indices: &UniversalRegionIndices<'tcx>,
879 defining_ty: DefiningTy<'tcx>,
880 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
881let tcx = self.infcx.tcx;
882let inputs_and_output = defining_ty.inputs_and_output(tcx);
883let inputs_and_output = indices.fold_to_region_vids(tcx, inputs_and_output);
884885// FIXME(#129952): We probably want a more principled approach here.
886if let Err(e) = inputs_and_output.error_reported() {
887self.infcx.set_tainted_by_errors(e);
888 }
889890inputs_and_output891 }
892}
893894trait 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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(896u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:907",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(907u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(913u32),
::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/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:924",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(924u32),
::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>)]895impl<'tcx> BorrowckInferCtxt<'tcx> {
896#[instrument(skip(self), level = "debug")]
897fn replace_free_regions_with_nll_infer_vars<T>(
898&self,
899 origin: NllRegionVariableOrigin<'tcx>,
900 value: T,
901 ) -> T
902where
903T: TypeFoldable<TyCtxt<'tcx>>,
904 {
905 fold_regions(self.infcx.tcx, value, |region, _depth| {
906let name = region.get_name_or_anon(self.infcx.tcx);
907debug!(?region, ?name);
908909self.next_nll_region_var(origin, || RegionCtxt::Free(name))
910 })
911 }
912913#[instrument(level = "debug", skip(self, indices))]
914fn replace_bound_regions_with_nll_infer_vars<T>(
915&self,
916 all_outlive_scope: LocalDefId,
917 value: ty::Binder<'tcx, T>,
918 indices: &UniversalRegionIndices<'tcx>,
919 ) -> T
920where
921T: TypeFoldable<TyCtxt<'tcx>>,
922 {
923let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
924debug!(?br);
925let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
926let liberated_region =
927 ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
928 ty::Region::new_var(self.tcx, indices.to_region_vid(liberated_region))
929 });
930 value
931 }
932}
933934impl<'tcx> UniversalRegionIndices<'tcx> {
935/// Initially, the `UniversalRegionIndices` map contains only the
936 /// early-bound regions in scope. Once that is all setup, we come
937 /// in later and instantiate the late-bound regions, and then we
938 /// insert the `ReLateParam` version of those into the map as
939 /// well. These are used for error reporting.
940fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
941{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs:941",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(941u32),
::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);
942{
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);
943 }
944945/// Converts `r` into a local inference variable: `r` can either
946 /// be a `ReVar` (i.e., already a reference to an inference
947 /// variable) or it can be `'static` or some early-bound
948 /// region. This is useful when taking the results from
949 /// type-checking and trait-matching, which may sometimes
950 /// reference those regions from the `ParamEnv`. It is also used
951 /// during initialization. Relies on the `indices` map having been
952 /// fully initialized.
953 ///
954 /// Panics if `r` is not a registered universal region, most notably
955 /// if it is a placeholder. Handling placeholders requires access to the
956 /// `MirTypeckRegionConstraints`.
957fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
958match r.kind() {
959 ty::ReVar(..) => r.as_var(),
960 ty::ReError(guar) => {
961self.encountered_re_error.set(Some(guar));
962// We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
963 // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
964 // errors are being emitted and 2) it leaves the happy path unaffected.
965self.fr_static
966 }
967_ => *self968 .indices
969 .get(&r)
970 .unwrap_or_else(|| bug_impl(None, format_args!("cannot convert `{0:?}` to a region vid", r),
Location::caller())bug!("cannot convert `{:?}` to a region vid", r)),
971 }
972 }
973974/// Replaces all free regions in `value` with region vids, as
975 /// returned by `to_region_vid`.
976fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
977where
978T: TypeFoldable<TyCtxt<'tcx>>,
979 {
980fold_regions(tcx, value, |region, _| ty::Region::new_var(tcx, self.to_region_vid(region)))
981 }
982}
983984/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
985/// parents, up to the typeck root, and invokes `f` with the liberated form
986/// of each one.
987fn for_each_late_bound_region_in_recursive_scope<'tcx>(
988 tcx: TyCtxt<'tcx>,
989mut mir_def_id: LocalDefId,
990mut f: impl FnMut(ty::Region<'tcx>),
991) {
992// Walk up the tree, collecting late-bound regions until we hit the typeck root
993loop {
994for_each_late_bound_region_in_item(tcx, mir_def_id, &mut f);
995996if tcx.is_typeck_child(mir_def_id.to_def_id()) {
997mir_def_id = tcx.local_parent(mir_def_id);
998 } else {
999break;
1000 }
1001 }
1002}
10031004/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
1005/// parents, up to the typeck root, and invokes `f` with the liberated form
1006/// of each one.
1007fn for_each_late_bound_region_in_item<'tcx>(
1008 tcx: TyCtxt<'tcx>,
1009 mir_def_id: LocalDefId,
1010mut f: impl FnMut(ty::Region<'tcx>),
1011) {
1012let bound_vars = match tcx.def_kind(mir_def_id) {
1013 DefKind::Fn | DefKind::AssocFn => {
1014tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id))
1015 }
1016// We extract the bound vars from the deduced closure signature, since we may have
1017 // only deduced that a param in the closure signature is late-bound from a constraint
1018 // that we discover during typeck.
1019DefKind::Closure => {
1020let ty = tcx.type_of(mir_def_id).instantiate_identity().skip_norm_wip();
1021match *ty.kind() {
1022 ty::Closure(_, args) => args.as_closure().sig().bound_vars(),
1023 ty::CoroutineClosure(_, args) => {
1024args.as_coroutine_closure().coroutine_closure_sig().bound_vars()
1025 }
1026 ty::Coroutine(_, _) | ty::Error(_) => return,
1027_ => {
::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}"),
1028 }
1029 }
1030_ => return,
1031 };
10321033for (idx, bound_var) in bound_vars.iter().enumerate() {
1034if let ty::BoundVariableKind::Region(kind) = bound_var {
1035let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
1036let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind);
1037 f(liberated_region);
1038 }
1039 }
1040}