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::def::DefKind;
21use rustc_hir::def_id::{DefId, LocalDefId};
22use rustc_hir::lang_items::LangItem;
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, GenericArgs, GenericArgsRef, InlineConstArgs, InlineConstArgsParts, RegionExt,
30RegionUtilitiesExt, 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]
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/// Returns a list of all the upvar types for this MIR. If this is
138 /// not a closure or coroutine, there are no upvars, and hence it
139 /// will be an empty list. The order of types in this list will
140 /// match up with the upvar order in the HIR, typesystem, and MIR.
141pub(crate) fn upvar_tys(self) -> &'tcx ty::List<Ty<'tcx>> {
142match self {
143 DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(),
144 DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().upvar_tys(),
145 DefiningTy::Coroutine(_, args) => args.as_coroutine().upvar_tys(),
146 DefiningTy::FnDef(..)
147 | DefiningTy::Const(..)
148 | DefiningTy::InlineConst(..)
149 | DefiningTy::GlobalAsm(_) => ty::List::empty(),
150 }
151 }
152153/// Number of implicit inputs -- notably the "environment"
154 /// parameter for closures -- that appear in MIR but not in the
155 /// user's code.
156pub(crate) fn implicit_inputs(self) -> usize {
157match self {
158 DefiningTy::Closure(..)
159 | DefiningTy::CoroutineClosure(..)
160 | DefiningTy::Coroutine(..) => 1,
161 DefiningTy::FnDef(..)
162 | DefiningTy::Const(..)
163 | DefiningTy::InlineConst(..)
164 | DefiningTy::GlobalAsm(_) => 0,
165 }
166 }
167168pub(crate) fn is_fn_def(&self) -> bool {
169#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::FnDef(..) => true,
_ => false,
}matches!(*self, DefiningTy::FnDef(..))170 }
171172pub(crate) fn is_const(&self) -> bool {
173#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::Const(..) | DefiningTy::InlineConst(..) => true,
_ => false,
}matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))174 }
175176pub(crate) fn def_id(&self) -> DefId {
177match *self {
178 DefiningTy::Closure(def_id, ..)
179 | DefiningTy::CoroutineClosure(def_id, ..)
180 | DefiningTy::Coroutine(def_id, ..)
181 | DefiningTy::FnDef(def_id, ..)
182 | DefiningTy::Const(def_id, ..)
183 | DefiningTy::InlineConst(def_id, ..)
184 | DefiningTy::GlobalAsm(def_id) => def_id,
185 }
186 }
187188/// Returns the args of the `DefiningTy`. These are equivalent to the identity
189 /// substs of the body, but replaced with region vids.
190pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> {
191match *self {
192 DefiningTy::Closure(_, args)
193 | DefiningTy::Coroutine(_, args)
194 | DefiningTy::CoroutineClosure(_, args)
195 | DefiningTy::FnDef(_, args)
196 | DefiningTy::Const(_, args)
197 | DefiningTy::InlineConst(_, args) => args,
198 DefiningTy::GlobalAsm(_) => ty::List::empty(),
199 }
200 }
201}
202203#[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)]
204#[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)
205struct UniversalRegionIndices<'tcx> {
206/// For those regions that may appear in the parameter environment
207 /// ('static and early-bound regions), we maintain a map from the
208 /// `ty::Region` to the internal `RegionVid` we are using. This is
209 /// used because trait matching and type-checking will feed us
210 /// region constraints that reference those regions and we need to
211 /// be able to map them to our internal `RegionVid`.
212 ///
213 /// This is similar to just using `GenericArgs`, except that it contains
214 /// an entry for `'static`, and also late bound parameters in scope.
215indices: FxIndexMap<ty::Region<'tcx>, RegionVid>,
216217/// The vid assigned to `'static`. Used only for diagnostics.
218pub fr_static: RegionVid,
219220/// Whether we've encountered an error region. If we have, cancel all
221 /// outlives errors, as they are likely bogus.
222pub encountered_re_error: Cell<Option<ErrorGuaranteed>>,
223}
224225#[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::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)]
226pub(crate) enum RegionClassification {
227/// A **global** region is one that can be named from
228 /// anywhere. There is only one, `'static`.
229Global,
230231/// An **external** region is only relevant for
232 /// closures, coroutines, and inline consts. In that
233 /// case, it refers to regions that are free in the type
234 /// -- basically, something bound in the surrounding context.
235 ///
236 /// Consider this example:
237 ///
238 /// ```ignore (pseudo-rust)
239 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
240 /// let closure = for<'x> |x: &'x u32| { .. };
241 /// // ^^^^^^^ pretend this were legal syntax
242 /// // for declaring a late-bound region in
243 /// // a closure signature
244 /// }
245 /// ```
246 ///
247 /// Here, the lifetimes `'a` and `'b` would be **external** to the
248 /// closure.
249 ///
250 /// If we are not analyzing a closure/coroutine/inline-const,
251 /// there are no external lifetimes.
252External,
253254/// A **local** lifetime is one about which we know the full set
255 /// of relevant constraints (that is, relationships to other named
256 /// regions). For a closure, this includes any region bound in
257 /// the closure's signature. For a fn item, this includes all
258 /// regions other than global ones.
259 ///
260 /// Continuing with the example from `External`, if we were
261 /// analyzing the closure, then `'x` would be local (and `'a` and
262 /// `'b` are external). If we are analyzing the function item
263 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
264 /// scope).
265Local,
266}
267268const FIRST_GLOBAL_INDEX: usize = 0;
269270impl<'tcx> UniversalRegions<'tcx> {
271/// Creates a new and fully initialized `UniversalRegions` that
272 /// contains indices for all the free regions found in the given
273 /// MIR -- that is, all the regions that appear in the function's
274 /// signature.
275pub(crate) fn new(infcx: &BorrowckInferCtxt<'tcx>, mir_def: LocalDefId) -> Self {
276UniversalRegionsBuilder { infcx, mir_def }.build()
277 }
278279/// Given a reference to a closure type, extracts all the values
280 /// from its free regions and returns a vector with them. This is
281 /// used when the closure's creator checks that the
282 /// `ClosureRegionRequirements` are met. The requirements from
283 /// `ClosureRegionRequirements` are expressed in terms of
284 /// `RegionVid` entries that map into the returned vector `V`: so
285 /// if the `ClosureRegionRequirements` contains something like
286 /// `'1: '2`, then the caller would impose the constraint that
287 /// `V[1]: V[2]`.
288pub(crate) fn closure_mapping(
289 tcx: TyCtxt<'tcx>,
290 closure_args: GenericArgsRef<'tcx>,
291 expected_num_vars: usize,
292 closure_def_id: LocalDefId,
293 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
294let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
295region_mapping.push(tcx.lifetimes.re_static);
296tcx.for_each_free_region(&closure_args, |fr| {
297region_mapping.push(fr);
298 });
299300for_each_late_bound_region_in_recursive_scope(tcx, tcx.local_parent(closure_def_id), |r| {
301region_mapping.push(r);
302 });
303304{
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!(
305 region_mapping.len(),
306 expected_num_vars,
307"index vec had unexpected number of variables"
308);
309310region_mapping311 }
312313/// Returns `true` if `r` is a member of this set of universal regions.
314pub(crate) fn is_universal_region(&self, r: RegionVid) -> bool {
315 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
316 }
317318/// Classifies `r` as a universal region, returning `None` if this
319 /// is not a member of this set of universal regions.
320pub(crate) fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
321let index = r.index();
322if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
323Some(RegionClassification::Global)
324 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
325Some(RegionClassification::External)
326 } else if (self.first_local_index..self.num_universals).contains(&index) {
327Some(RegionClassification::Local)
328 } else {
329None330 }
331 }
332333/// Returns an iterator over all the RegionVids corresponding to
334 /// universally quantified free regions.
335pub(crate) fn universal_regions_iter(&self) -> impl Iterator<Item = RegionVid> + 'static {
336 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize)
337 }
338339/// Returns `true` if `r` is classified as a local region.
340pub(crate) fn is_local_free_region(&self, r: RegionVid) -> bool {
341self.region_classification(r) == Some(RegionClassification::Local)
342 }
343344/// Returns the number of universal regions created in any category.
345pub(crate) fn len(&self) -> usize {
346self.num_universals
347 }
348349/// Returns the number of global plus external universal regions.
350 /// For closures, these are the regions that appear free in the
351 /// closure type (versus those bound in the closure
352 /// signature). They are therefore the regions between which the
353 /// closure may impose constraints that its creator must verify.
354pub(crate) fn num_global_and_external_regions(&self) -> usize {
355self.first_local_index
356 }
357358/// Gets an iterator over all the early-bound regions that have names.
359pub(crate) fn named_universal_regions_iter(
360&self,
361 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> {
362self.indices.indices.iter().map(|(&r, &v)| (r, v))
363 }
364365/// See [UniversalRegionIndices::to_region_vid].
366pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
367self.indices.to_region_vid(r)
368 }
369370/// As part of the NLL unit tests, you can annotate a function with
371 /// `#[rustc_regions]`, and we will emit information about the region
372 /// inference context and -- in particular -- the external constraints
373 /// that this region imposes on others. The methods in this file
374 /// handle the part about dumping the inference context internal
375 /// state.
376pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
377match self.defining_ty {
378 DefiningTy::Closure(def_id, args) => {
379let 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!(
380 args[tcx.generics_of(def_id).parent_count..]
381 .iter()
382 .map(|arg| arg.to_string())
383 .collect::<Vec<_>>()
384 );
385err.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!(
386"defining type: {} with closure args [\n {},\n]",
387 tcx.def_path_str_with_args(def_id, args),
388 v.join(",\n "),
389 ));
390391// FIXME: It'd be nice to print the late-bound regions
392 // here, but unfortunately these wind up stored into
393 // tests, and the resulting print-outs include def-ids
394 // and other things that are not stable across tests!
395 // So we just include the region-vid. Annoying.
396for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
397err.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)));
398 });
399 }
400 DefiningTy::CoroutineClosure(..) => {
401::core::panicking::panic("not implemented")unimplemented!()402 }
403 DefiningTy::Coroutine(def_id, args) => {
404let 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!(
405 args[tcx.generics_of(def_id).parent_count..]
406 .iter()
407 .map(|arg| arg.to_string())
408 .collect::<Vec<_>>()
409 );
410err.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!(
411"defining type: {} with coroutine args [\n {},\n]",
412 tcx.def_path_str_with_args(def_id, args),
413 v.join(",\n "),
414 ));
415416// FIXME: As above, we'd like to print out the region
417 // `r` but doing so is not stable across architectures
418 // and so forth.
419for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
420err.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)));
421 });
422 }
423 DefiningTy::FnDef(def_id, args) => {
424err.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),));
425 }
426 DefiningTy::Const(def_id, args) => {
427err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining constant type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!(
428"defining constant type: {}",
429 tcx.def_path_str_with_args(def_id, args),
430 ));
431 }
432 DefiningTy::InlineConst(def_id, args) => {
433err.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!(
434"defining inline constant type: {}",
435 tcx.def_path_str_with_args(def_id, args),
436 ));
437 }
438 DefiningTy::GlobalAsm(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
439 }
440 }
441442pub(crate) fn implicit_region_bound(&self) -> RegionVid {
443self.fr_fn_body
444 }
445446pub(crate) fn encountered_re_error(&self) -> Option<ErrorGuaranteed> {
447self.indices.encountered_re_error.get()
448 }
449}
450451struct UniversalRegionsBuilder<'a, 'tcx> {
452 infcx: &'a BorrowckInferCtxt<'tcx>,
453 mir_def: LocalDefId,
454}
455456impl<'tcx> UniversalRegionsBuilder<'_, 'tcx> {
457fn build(self) -> UniversalRegions<'tcx> {
458{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:458",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(458u32),
::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);
459460let param_env = self.infcx.param_env;
461{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:461",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(461u32),
::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);
462463{
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());
464465// Create the "global" region that is always free in all contexts: 'static.
466let fr_static = self467 .infcx
468 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
469 RegionCtxt::Free(kw::Static)
470 })
471 .as_var();
472473// We've now added all the global regions. The next ones we
474 // add will be external.
475let first_extern_index = self.infcx.num_region_vars();
476477let defining_ty = self.defining_ty();
478{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:478",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(478u32),
::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);
479480let mut indices = self.compute_indices(fr_static, defining_ty);
481{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:481",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(481u32),
::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);
482483// If this is a 'root' body (not a closure/coroutine/inline const), then
484 // there are no extern regions, so the local regions start at the same
485 // position as the (empty) sub-list of extern regions
486let first_local_index = if !self.infcx.tcx.is_typeck_child(self.mir_def.to_def_id()) {
487first_extern_index488 } else {
489// If this is a closure, coroutine, or inline-const, then the late-bound regions from the enclosing
490 // function/closures are actually external regions to us. For example, here, 'a is not local
491 // to the closure c (although it is local to the fn foo):
492 // fn foo<'a>() {
493 // let c = || { let x: &'a u32 = ...; }
494 // }
495for_each_late_bound_region_in_recursive_scope(
496self.infcx.tcx,
497self.infcx.tcx.local_parent(self.mir_def),
498 |r| {
499{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:499",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(499u32),
::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);
500let region_vid = {
501let name = r.get_name_or_anon(self.infcx.tcx);
502self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
503 RegionCtxt::LateBound(name)
504 })
505 };
506507{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:507",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(507u32),
::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);
508indices.insert_late_bound_region(r, region_vid.as_var());
509 },
510 );
511512// Any regions created during the execution of `defining_ty` or during the above
513 // late-bound region replacement are all considered 'extern' regions
514self.infcx.num_region_vars()
515 };
516517// Converse of above, if this is a function/closure then the late-bound regions declared
518 // on its signature are local.
519 //
520 // We manually loop over `bound_inputs_and_output` instead of using
521 // `for_each_late_bound_region_in_item` as we may need to add the otherwise
522 // implicit `ClosureEnv` region.
523let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
524for (idx, bound_var) in bound_inputs_and_output.bound_vars().iter().enumerate() {
525if let ty::BoundVariableKind::Region(kind) = bound_var {
526let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
527let r = ty::Region::new_late_param(self.infcx.tcx, self.mir_def.to_def_id(), kind);
528let region_vid = {
529let name = r.get_name_or_anon(self.infcx.tcx);
530self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
531 RegionCtxt::LateBound(name)
532 })
533 };
534535{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:535",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(535u32),
::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);
536 indices.insert_late_bound_region(r, region_vid.as_var());
537 }
538 }
539let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
540self.mir_def,
541bound_inputs_and_output,
542&indices,
543 );
544545let (unnormalized_output_ty, unnormalized_input_tys) =
546inputs_and_output.split_last().unwrap();
547548let fr_fn_body = self549 .infcx
550 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
551 RegionCtxt::Free(sym::fn_body)
552 })
553 .as_var();
554555let num_universals = self.infcx.num_region_vars();
556557{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:557",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(557u32),
::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);
558{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:558",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(558u32),
::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);
559{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:559",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(559u32),
::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);
560561let (resume_ty, yield_ty) = match defining_ty {
562 DefiningTy::Coroutine(_, args) => {
563let tys = args.as_coroutine();
564 (Some(tys.resume_ty()), Some(tys.yield_ty()))
565 }
566_ => (None, None),
567 };
568569UniversalRegions {
570indices,
571fr_static,
572fr_fn_body,
573first_extern_index,
574first_local_index,
575num_universals,
576defining_ty,
577 unnormalized_output_ty: *unnormalized_output_ty,
578unnormalized_input_tys,
579yield_ty,
580resume_ty,
581 }
582 }
583584/// Returns the "defining type" of the current MIR;
585 /// see `DefiningTy` for details.
586fn defining_ty(&self) -> DefiningTy<'tcx> {
587let tcx = self.infcx.tcx;
588589match tcx.hir_body_owner_kind(self.mir_def) {
590 BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
591let defining_ty = tcx.type_of(self.mir_def).instantiate_identity().skip_norm_wip();
592593{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:593",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(593u32),
::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!("defining_ty (pre-replacement): {0:?}",
defining_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("defining_ty (pre-replacement): {:?}", defining_ty);
594595let defining_ty = self.infcx.replace_free_regions_with_nll_infer_vars(
596 NllRegionVariableOrigin::FreeRegion,
597defining_ty,
598 );
599600match *defining_ty.kind() {
601 ty::Closure(def_id, args) => DefiningTy::Closure(def_id, args),
602 ty::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, args),
603 ty::CoroutineClosure(def_id, args) => {
604 DefiningTy::CoroutineClosure(def_id, args)
605 }
606 ty::FnDef(def_id, args) => {
607 DefiningTy::FnDef(def_id, args.no_bound_vars().unwrap())
608 }
609_ => ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(self.mir_def),
format_args!("expected defining type for `{0:?}`: `{1:?}`", self.mir_def,
defining_ty))span_bug!(
610 tcx.def_span(self.mir_def),
611"expected defining type for `{:?}`: `{:?}`",
612self.mir_def,
613 defining_ty
614 ),
615 }
616 }
617618 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(..) => {
619match tcx.def_kind(self.mir_def) {
620 DefKind::AnonConst621if tcx.anon_const_kind(self.mir_def)
622 == ty::AnonConstKind::NonTypeSystemInline =>
623 {
624// This is required for `AscribeUserType` canonical query, which will call
625 // `type_of(inline_const_def_id)`. That `type_of` would inject erased lifetimes
626 // into borrowck, which is ICE #78174.
627 //
628 // As a workaround, inline consts have an additional generic param (`ty`
629 // below), so that `type_of(inline_const_def_id).substs(substs)` uses the
630 // proper type with NLL infer vars.
631 //
632 // Fetch the actual type from MIR, as `type_of` returns something useless
633 // like `<const_ty>`.
634let body = tcx.mir_promoted(self.mir_def).0.borrow();
635let ty = body.local_decls[RETURN_PLACE].ty;
636let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.to_def_id());
637let parent_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
638let args =
639InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty })
640 .args;
641let args = self.infcx.replace_free_regions_with_nll_infer_vars(
642 NllRegionVariableOrigin::FreeRegion,
643args,
644 );
645 DefiningTy::InlineConst(self.mir_def.to_def_id(), args)
646 }
647_ => {
648let identity_args =
649GenericArgs::identity_for_item(tcx, self.mir_def.to_def_id());
650let args = self.infcx.replace_free_regions_with_nll_infer_vars(
651 NllRegionVariableOrigin::FreeRegion,
652identity_args,
653 );
654 DefiningTy::Const(self.mir_def.to_def_id(), args)
655 }
656 }
657 }
658659 BodyOwnerKind::GlobalAsm => DefiningTy::GlobalAsm(self.mir_def.to_def_id()),
660 }
661 }
662663/// Builds a hashmap that maps from the universal regions that are
664 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
665 /// `RegionVid`). The map returned by this function contains only
666 /// the early-bound regions.
667fn compute_indices(
668&self,
669 fr_static: RegionVid,
670 defining_ty: DefiningTy<'tcx>,
671 ) -> UniversalRegionIndices<'tcx> {
672let tcx = self.infcx.tcx;
673let typeck_root_def_id = tcx.typeck_root_def_id_local(self.mir_def);
674let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
675let renumbered_args = defining_ty.args();
676677let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
678// This relies on typeck roots being generics_of parents with their
679 // parameters at the start of nested bodies' generics.
680if !(renumbered_args.len() >= identity_args.len()) {
::core::panicking::panic("assertion failed: renumbered_args.len() >= identity_args.len()")
};assert!(renumbered_args.len() >= identity_args.len());
681let arg_mapping =
682 iter::zip(identity_args.regions(), renumbered_args.regions().map(|r| r.as_var()));
683684UniversalRegionIndices {
685 indices: global_mapping.chain(arg_mapping).collect(),
686fr_static,
687 encountered_re_error: Cell::new(None),
688 }
689 }
690691fn compute_inputs_and_output(
692&self,
693 indices: &UniversalRegionIndices<'tcx>,
694 defining_ty: DefiningTy<'tcx>,
695 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
696let tcx = self.infcx.tcx;
697698let inputs_and_output = match defining_ty {
699 DefiningTy::Closure(def_id, args) => {
700{
match (&self.mir_def.to_def_id(), &def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.mir_def.to_def_id(), def_id);
701let closure_sig = args.as_closure().sig();
702let inputs_and_output = closure_sig.inputs_and_output();
703let bound_vars = tcx.mk_bound_variable_kinds_from_iter(
704inputs_and_output.bound_vars().iter().chain(iter::once(
705 ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv),
706 )),
707 );
708let br = ty::BoundRegion {
709 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
710 kind: ty::BoundRegionKind::ClosureEnv,
711 };
712let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
713let closure_ty = tcx.closure_env_ty(
714Ty::new_closure(tcx, def_id, args),
715args.as_closure().kind(),
716env_region,
717 );
718719// The "inputs" of the closure in the
720 // signature appear as a tuple. The MIR side
721 // flattens this tuple.
722let (&output, tuplized_inputs) =
723inputs_and_output.skip_binder().split_last().unwrap();
724{
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")));
}
}
}
};assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
725let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
726::rustc_middle::util::bug::bug_fmt(format_args!("closure inputs not a tuple: {0:?}",
tuplized_inputs[0]));bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]);
727 };
728729 ty::Binder::bind_with_vars(
730tcx.mk_type_list_from_iter(
731 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
732 ),
733bound_vars,
734 )
735 }
736737 DefiningTy::Coroutine(def_id, args) => {
738{
match (&self.mir_def.to_def_id(), &def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.mir_def.to_def_id(), def_id);
739let resume_ty = args.as_coroutine().resume_ty();
740let output = args.as_coroutine().return_ty();
741let coroutine_ty = Ty::new_coroutine(tcx, def_id, args);
742let inputs_and_output =
743self.infcx.tcx.mk_type_list(&[coroutine_ty, resume_ty, output]);
744 ty::Binder::dummy(inputs_and_output)
745 }
746747// Construct the signature of the CoroutineClosure for the purposes of borrowck.
748 // This is pretty straightforward -- we:
749 // 1. first grab the `coroutine_closure_sig`,
750 // 2. compute the self type (`&`/`&mut`/no borrow),
751 // 3. flatten the tupled_input_tys,
752 // 4. construct the correct generator type to return with
753 // `CoroutineClosureSignature::to_coroutine_given_kind_and_upvars`.
754 // Then we wrap it all up into a list of inputs and output.
755DefiningTy::CoroutineClosure(def_id, args) => {
756{
match (&self.mir_def.to_def_id(), &def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.mir_def.to_def_id(), def_id);
757let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
758let bound_vars =
759tcx.mk_bound_variable_kinds_from_iter(closure_sig.bound_vars().iter().chain(
760 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
761 ));
762let br = ty::BoundRegion {
763 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
764 kind: ty::BoundRegionKind::ClosureEnv,
765 };
766let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
767let closure_kind = args.as_coroutine_closure().kind();
768769let closure_ty = tcx.closure_env_ty(
770Ty::new_coroutine_closure(tcx, def_id, args),
771closure_kind,
772env_region,
773 );
774775let inputs = closure_sig.skip_binder().tupled_inputs_ty.tuple_fields();
776let output = closure_sig.skip_binder().to_coroutine_given_kind_and_upvars(
777tcx,
778args.as_coroutine_closure().parent_args(),
779tcx.coroutine_for_closure(def_id),
780closure_kind,
781env_region,
782args.as_coroutine_closure().tupled_upvars_ty(),
783args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
784 );
785786 ty::Binder::bind_with_vars(
787tcx.mk_type_list_from_iter(
788 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
789 ),
790bound_vars,
791 )
792 }
793794 DefiningTy::FnDef(def_id, _) => {
795let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
796let sig = indices.fold_to_region_vids(tcx, sig);
797let inputs_and_output = sig.inputs_and_output();
798799// C-variadic fns also have a `VaList` input that's not listed in the signature
800 // (as it's created inside the body itself, not passed in from outside).
801if self.infcx.tcx.fn_sig(def_id).skip_binder().c_variadic() {
802let va_list_did = self803 .infcx
804 .tcx
805 .require_lang_item(LangItem::VaList, self.infcx.tcx.def_span(self.mir_def));
806807let reg_vid = self808 .infcx
809 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
810 RegionCtxt::Free(sym::c_dash_variadic)
811 })
812 .as_var();
813814let region = ty::Region::new_var(self.infcx.tcx, reg_vid);
815let va_list_ty = self816 .infcx
817 .tcx
818 .type_of(va_list_did)
819 .instantiate(self.infcx.tcx, &[region.into()])
820 .skip_norm_wip();
821822// The signature needs to follow the order [input_tys, va_list_ty, output_ty]
823return inputs_and_output.map_bound(|tys| {
824let (output_ty, input_tys) = tys.split_last().unwrap();
825tcx.mk_type_list_from_iter(
826input_tys.iter().copied().chain([va_list_ty, *output_ty]),
827 )
828 });
829 }
830831inputs_and_output832 }
833834 DefiningTy::Const(def_id, _) => {
835// For a constant body, there are no inputs, and one
836 // "output" (the type of the constant).
837{
match (&self.mir_def.to_def_id(), &def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.mir_def.to_def_id(), def_id);
838let ty = tcx.type_of(self.mir_def).instantiate_identity().skip_norm_wip();
839840let ty = indices.fold_to_region_vids(tcx, ty);
841 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
842 }
843844 DefiningTy::InlineConst(def_id, args) => {
845{
match (&self.mir_def.to_def_id(), &def_id) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.mir_def.to_def_id(), def_id);
846let ty = args.as_inline_const().ty();
847 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
848 }
849850 DefiningTy::GlobalAsm(def_id) => ty::Binder::dummy(
851tcx.mk_type_list(&[tcx.type_of(def_id).instantiate_identity().skip_norm_wip()]),
852 ),
853 };
854855// FIXME(#129952): We probably want a more principled approach here.
856if let Err(e) = inputs_and_output.error_reported() {
857self.infcx.set_tainted_by_errors(e);
858 }
859860inputs_and_output861 }
862}
863864impl<'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("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(866u32),
::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 compiler/rustc_borrowck/src/universal_regions.rs:877",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(877u32),
::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("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(883u32),
::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 compiler/rustc_borrowck/src/universal_regions.rs:894",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(894u32),
::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>)]865impl<'tcx> BorrowckInferCtxt<'tcx> {
866#[instrument(skip(self), level = "debug")]
867fn replace_free_regions_with_nll_infer_vars<T>(
868&self,
869 origin: NllRegionVariableOrigin<'tcx>,
870 value: T,
871 ) -> T
872where
873T: TypeFoldable<TyCtxt<'tcx>>,
874 {
875 fold_regions(self.infcx.tcx, value, |region, _depth| {
876let name = region.get_name_or_anon(self.infcx.tcx);
877debug!(?region, ?name);
878879self.next_nll_region_var(origin, || RegionCtxt::Free(name))
880 })
881 }
882883#[instrument(level = "debug", skip(self, indices))]
884fn replace_bound_regions_with_nll_infer_vars<T>(
885&self,
886 all_outlive_scope: LocalDefId,
887 value: ty::Binder<'tcx, T>,
888 indices: &UniversalRegionIndices<'tcx>,
889 ) -> T
890where
891T: TypeFoldable<TyCtxt<'tcx>>,
892 {
893let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
894debug!(?br);
895let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
896let liberated_region =
897 ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
898 ty::Region::new_var(self.tcx, indices.to_region_vid(liberated_region))
899 });
900 value
901 }
902}
903904impl<'tcx> UniversalRegionIndices<'tcx> {
905/// Initially, the `UniversalRegionIndices` map contains only the
906 /// early-bound regions in scope. Once that is all setup, we come
907 /// in later and instantiate the late-bound regions, and then we
908 /// insert the `ReLateParam` version of those into the map as
909 /// well. These are used for error reporting.
910fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
911{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:911",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(911u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["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);
912{
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);
913 }
914915/// Converts `r` into a local inference variable: `r` can either
916 /// be a `ReVar` (i.e., already a reference to an inference
917 /// variable) or it can be `'static` or some early-bound
918 /// region. This is useful when taking the results from
919 /// type-checking and trait-matching, which may sometimes
920 /// reference those regions from the `ParamEnv`. It is also used
921 /// during initialization. Relies on the `indices` map having been
922 /// fully initialized.
923 ///
924 /// Panics if `r` is not a registered universal region, most notably
925 /// if it is a placeholder. Handling placeholders requires access to the
926 /// `MirTypeckRegionConstraints`.
927fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
928match r.kind() {
929 ty::ReVar(..) => r.as_var(),
930 ty::ReError(guar) => {
931self.encountered_re_error.set(Some(guar));
932// We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
933 // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
934 // errors are being emitted and 2) it leaves the happy path unaffected.
935self.fr_static
936 }
937_ => *self938 .indices
939 .get(&r)
940 .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)),
941 }
942 }
943944/// Replaces all free regions in `value` with region vids, as
945 /// returned by `to_region_vid`.
946fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
947where
948T: TypeFoldable<TyCtxt<'tcx>>,
949 {
950fold_regions(tcx, value, |region, _| ty::Region::new_var(tcx, self.to_region_vid(region)))
951 }
952}
953954/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
955/// parents, up to the typeck root, and invokes `f` with the liberated form
956/// of each one.
957fn for_each_late_bound_region_in_recursive_scope<'tcx>(
958 tcx: TyCtxt<'tcx>,
959mut mir_def_id: LocalDefId,
960mut f: impl FnMut(ty::Region<'tcx>),
961) {
962// Walk up the tree, collecting late-bound regions until we hit the typeck root
963loop {
964for_each_late_bound_region_in_item(tcx, mir_def_id, &mut f);
965966if tcx.is_typeck_child(mir_def_id.to_def_id()) {
967mir_def_id = tcx.local_parent(mir_def_id);
968 } else {
969break;
970 }
971 }
972}
973974/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
975/// parents, up to the typeck root, and invokes `f` with the liberated form
976/// of each one.
977fn for_each_late_bound_region_in_item<'tcx>(
978 tcx: TyCtxt<'tcx>,
979 mir_def_id: LocalDefId,
980mut f: impl FnMut(ty::Region<'tcx>),
981) {
982let bound_vars = match tcx.def_kind(mir_def_id) {
983 DefKind::Fn | DefKind::AssocFn => {
984tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id))
985 }
986// We extract the bound vars from the deduced closure signature, since we may have
987 // only deduced that a param in the closure signature is late-bound from a constraint
988 // that we discover during typeck.
989DefKind::Closure => {
990let ty = tcx.type_of(mir_def_id).instantiate_identity().skip_norm_wip();
991match *ty.kind() {
992 ty::Closure(_, args) => args.as_closure().sig().bound_vars(),
993 ty::CoroutineClosure(_, args) => {
994args.as_coroutine_closure().coroutine_closure_sig().bound_vars()
995 }
996 ty::Coroutine(_, _) | ty::Error(_) => return,
997_ => {
::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}"),
998 }
999 }
1000_ => return,
1001 };
10021003for (idx, bound_var) in bound_vars.iter().enumerate() {
1004if let ty::BoundVariableKind::Region(kind) = bound_var {
1005let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
1006let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind);
1007 f(liberated_region);
1008 }
1009 }
1010}