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::ty::print::with_no_trimmed_paths;
27use rustc_middle::ty::{
28self, GenericArgs, GenericArgsRef, InlineConstArgs, InlineConstArgsParts, RegionVid, Ty,
29TyCtxt, TypeFoldable, TypeVisitableExt, fold_regions,
30};
31use rustc_middle::{bug, span_bug};
32use rustc_span::{ErrorGuaranteed, kw, 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. =)
82pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
8384pub yield_ty: Option<Ty<'tcx>>,
8586pub resume_ty: Option<Ty<'tcx>>,
87}
8889/// The "defining type" for this MIR. The key feature of the "defining
90/// type" is that it contains the information needed to derive all the
91/// universal regions that are in scope as well as the types of the
92/// inputs/output from the MIR. In general, early-bound universal
93/// regions appear free in the defining type and late-bound regions
94/// appear bound in the signature.
95#[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)]
96pub(crate) enum DefiningTy<'tcx> {
97/// The MIR is a closure. The signature is found via
98 /// `ClosureArgs::closure_sig_ty`.
99Closure(DefId, GenericArgsRef<'tcx>),
100101/// The MIR is a coroutine. The signature is that coroutines take
102 /// no parameters and return the result of
103 /// `ClosureArgs::coroutine_return_ty`.
104Coroutine(DefId, GenericArgsRef<'tcx>),
105106/// The MIR is a special kind of closure that returns coroutines.
107 ///
108 /// See the documentation on `CoroutineClosureSignature` for details
109 /// on how to construct the callable signature of the coroutine from
110 /// its args.
111CoroutineClosure(DefId, GenericArgsRef<'tcx>),
112113/// The MIR is a fn item with the given `DefId` and args. The signature
114 /// of the function can be bound then with the `fn_sig` query.
115FnDef(DefId, GenericArgsRef<'tcx>),
116117/// The MIR represents some form of constant. The signature then
118 /// is that it has no inputs and a single return value, which is
119 /// the value of the constant.
120Const(DefId, GenericArgsRef<'tcx>),
121122/// The MIR represents an inline const. The signature has no inputs and a
123 /// single return value found via `InlineConstArgs::ty`.
124InlineConst(DefId, GenericArgsRef<'tcx>),
125126// Fake body for a global asm. Not particularly useful or interesting,
127 // but we need it so we can properly store the typeck results of the asm
128 // operands, which aren't associated with a body otherwise.
129GlobalAsm(DefId),
130}
131132impl<'tcx> DefiningTy<'tcx> {
133/// Returns a list of all the upvar types for this MIR. If this is
134 /// not a closure or coroutine, there are no upvars, and hence it
135 /// will be an empty list. The order of types in this list will
136 /// match up with the upvar order in the HIR, typesystem, and MIR.
137pub(crate) fn upvar_tys(self) -> &'tcx ty::List<Ty<'tcx>> {
138match self {
139 DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(),
140 DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().upvar_tys(),
141 DefiningTy::Coroutine(_, args) => args.as_coroutine().upvar_tys(),
142 DefiningTy::FnDef(..)
143 | DefiningTy::Const(..)
144 | DefiningTy::InlineConst(..)
145 | DefiningTy::GlobalAsm(_) => ty::List::empty(),
146 }
147 }
148149/// Number of implicit inputs -- notably the "environment"
150 /// parameter for closures -- that appear in MIR but not in the
151 /// user's code.
152pub(crate) fn implicit_inputs(self) -> usize {
153match self {
154 DefiningTy::Closure(..)
155 | DefiningTy::CoroutineClosure(..)
156 | DefiningTy::Coroutine(..) => 1,
157 DefiningTy::FnDef(..)
158 | DefiningTy::Const(..)
159 | DefiningTy::InlineConst(..)
160 | DefiningTy::GlobalAsm(_) => 0,
161 }
162 }
163164pub(crate) fn is_fn_def(&self) -> bool {
165#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::FnDef(..) => true,
_ => false,
}matches!(*self, DefiningTy::FnDef(..))166 }
167168pub(crate) fn is_const(&self) -> bool {
169#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::Const(..) | DefiningTy::InlineConst(..) => true,
_ => false,
}matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))170 }
171172pub(crate) fn def_id(&self) -> DefId {
173match *self {
174 DefiningTy::Closure(def_id, ..)
175 | DefiningTy::CoroutineClosure(def_id, ..)
176 | DefiningTy::Coroutine(def_id, ..)
177 | DefiningTy::FnDef(def_id, ..)
178 | DefiningTy::Const(def_id, ..)
179 | DefiningTy::InlineConst(def_id, ..)
180 | DefiningTy::GlobalAsm(def_id) => def_id,
181 }
182 }
183184/// Returns the args of the `DefiningTy`. These are equivalent to the identity
185 /// substs of the body, but replaced with region vids.
186pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> {
187match *self {
188 DefiningTy::Closure(_, args)
189 | DefiningTy::Coroutine(_, args)
190 | DefiningTy::CoroutineClosure(_, args)
191 | DefiningTy::FnDef(_, args)
192 | DefiningTy::Const(_, args)
193 | DefiningTy::InlineConst(_, args) => args,
194 DefiningTy::GlobalAsm(_) => ty::List::empty(),
195 }
196 }
197}
198199#[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)]
200#[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)
201struct UniversalRegionIndices<'tcx> {
202/// For those regions that may appear in the parameter environment
203 /// ('static and early-bound regions), we maintain a map from the
204 /// `ty::Region` to the internal `RegionVid` we are using. This is
205 /// used because trait matching and type-checking will feed us
206 /// region constraints that reference those regions and we need to
207 /// be able to map them to our internal `RegionVid`.
208 ///
209 /// This is similar to just using `GenericArgs`, except that it contains
210 /// an entry for `'static`, and also late bound parameters in scope.
211indices: FxIndexMap<ty::Region<'tcx>, RegionVid>,
212213/// The vid assigned to `'static`. Used only for diagnostics.
214pub fr_static: RegionVid,
215216/// Whether we've encountered an error region. If we have, cancel all
217 /// outlives errors, as they are likely bogus.
218pub encountered_re_error: Cell<Option<ErrorGuaranteed>>,
219}
220221#[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)]
222pub(crate) enum RegionClassification {
223/// A **global** region is one that can be named from
224 /// anywhere. There is only one, `'static`.
225Global,
226227/// An **external** region is only relevant for
228 /// closures, coroutines, and inline consts. In that
229 /// case, it refers to regions that are free in the type
230 /// -- basically, something bound in the surrounding context.
231 ///
232 /// Consider this example:
233 ///
234 /// ```ignore (pseudo-rust)
235 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
236 /// let closure = for<'x> |x: &'x u32| { .. };
237 /// // ^^^^^^^ pretend this were legal syntax
238 /// // for declaring a late-bound region in
239 /// // a closure signature
240 /// }
241 /// ```
242 ///
243 /// Here, the lifetimes `'a` and `'b` would be **external** to the
244 /// closure.
245 ///
246 /// If we are not analyzing a closure/coroutine/inline-const,
247 /// there are no external lifetimes.
248External,
249250/// A **local** lifetime is one about which we know the full set
251 /// of relevant constraints (that is, relationships to other named
252 /// regions). For a closure, this includes any region bound in
253 /// the closure's signature. For a fn item, this includes all
254 /// regions other than global ones.
255 ///
256 /// Continuing with the example from `External`, if we were
257 /// analyzing the closure, then `'x` would be local (and `'a` and
258 /// `'b` are external). If we are analyzing the function item
259 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
260 /// scope).
261Local,
262}
263264const FIRST_GLOBAL_INDEX: usize = 0;
265266impl<'tcx> UniversalRegions<'tcx> {
267/// Creates a new and fully initialized `UniversalRegions` that
268 /// contains indices for all the free regions found in the given
269 /// MIR -- that is, all the regions that appear in the function's
270 /// signature.
271pub(crate) fn new(infcx: &BorrowckInferCtxt<'tcx>, mir_def: LocalDefId) -> Self {
272UniversalRegionsBuilder { infcx, mir_def }.build()
273 }
274275/// Given a reference to a closure type, extracts all the values
276 /// from its free regions and returns a vector with them. This is
277 /// used when the closure's creator checks that the
278 /// `ClosureRegionRequirements` are met. The requirements from
279 /// `ClosureRegionRequirements` are expressed in terms of
280 /// `RegionVid` entries that map into the returned vector `V`: so
281 /// if the `ClosureRegionRequirements` contains something like
282 /// `'1: '2`, then the caller would impose the constraint that
283 /// `V[1]: V[2]`.
284pub(crate) fn closure_mapping(
285 tcx: TyCtxt<'tcx>,
286 closure_args: GenericArgsRef<'tcx>,
287 expected_num_vars: usize,
288 closure_def_id: LocalDefId,
289 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
290let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
291region_mapping.push(tcx.lifetimes.re_static);
292tcx.for_each_free_region(&closure_args, |fr| {
293region_mapping.push(fr);
294 });
295296for_each_late_bound_region_in_recursive_scope(tcx, tcx.local_parent(closure_def_id), |r| {
297region_mapping.push(r);
298 });
299300match (®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!(
301 region_mapping.len(),
302 expected_num_vars,
303"index vec had unexpected number of variables"
304);
305306region_mapping307 }
308309/// Returns `true` if `r` is a member of this set of universal regions.
310pub(crate) fn is_universal_region(&self, r: RegionVid) -> bool {
311 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
312 }
313314/// Classifies `r` as a universal region, returning `None` if this
315 /// is not a member of this set of universal regions.
316pub(crate) fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
317let index = r.index();
318if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
319Some(RegionClassification::Global)
320 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
321Some(RegionClassification::External)
322 } else if (self.first_local_index..self.num_universals).contains(&index) {
323Some(RegionClassification::Local)
324 } else {
325None326 }
327 }
328329/// Returns an iterator over all the RegionVids corresponding to
330 /// universally quantified free regions.
331pub(crate) fn universal_regions_iter(&self) -> impl Iterator<Item = RegionVid> + 'static {
332 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize)
333 }
334335/// Returns `true` if `r` is classified as a local region.
336pub(crate) fn is_local_free_region(&self, r: RegionVid) -> bool {
337self.region_classification(r) == Some(RegionClassification::Local)
338 }
339340/// Returns the number of universal regions created in any category.
341pub(crate) fn len(&self) -> usize {
342self.num_universals
343 }
344345/// Returns the number of global plus external universal regions.
346 /// For closures, these are the regions that appear free in the
347 /// closure type (versus those bound in the closure
348 /// signature). They are therefore the regions between which the
349 /// closure may impose constraints that its creator must verify.
350pub(crate) fn num_global_and_external_regions(&self) -> usize {
351self.first_local_index
352 }
353354/// Gets an iterator over all the early-bound regions that have names.
355pub(crate) fn named_universal_regions_iter(
356&self,
357 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> {
358self.indices.indices.iter().map(|(&r, &v)| (r, v))
359 }
360361/// See [UniversalRegionIndices::to_region_vid].
362pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
363self.indices.to_region_vid(r)
364 }
365366/// As part of the NLL unit tests, you can annotate a function with
367 /// `#[rustc_regions]`, and we will emit information about the region
368 /// inference context and -- in particular -- the external constraints
369 /// that this region imposes on others. The methods in this file
370 /// handle the part about dumping the inference context internal
371 /// state.
372pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
373match self.defining_ty {
374 DefiningTy::Closure(def_id, args) => {
375let 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!(
376 args[tcx.generics_of(def_id).parent_count..]
377 .iter()
378 .map(|arg| arg.to_string())
379 .collect::<Vec<_>>()
380 );
381err.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!(
382"defining type: {} with closure args [\n {},\n]",
383 tcx.def_path_str_with_args(def_id, args),
384 v.join(",\n "),
385 ));
386387// FIXME: It'd be nice to print the late-bound regions
388 // here, but unfortunately these wind up stored into
389 // tests, and the resulting print-outs include def-ids
390 // and other things that are not stable across tests!
391 // So we just include the region-vid. Annoying.
392for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
393err.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)));
394 });
395 }
396 DefiningTy::CoroutineClosure(..) => {
397::core::panicking::panic("not yet implemented")todo!()398 }
399 DefiningTy::Coroutine(def_id, args) => {
400let 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!(
401 args[tcx.generics_of(def_id).parent_count..]
402 .iter()
403 .map(|arg| arg.to_string())
404 .collect::<Vec<_>>()
405 );
406err.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!(
407"defining type: {} with coroutine args [\n {},\n]",
408 tcx.def_path_str_with_args(def_id, args),
409 v.join(",\n "),
410 ));
411412// FIXME: As above, we'd like to print out the region
413 // `r` but doing so is not stable across architectures
414 // and so forth.
415for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
416err.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)));
417 });
418 }
419 DefiningTy::FnDef(def_id, args) => {
420err.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),));
421 }
422 DefiningTy::Const(def_id, args) => {
423err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining constant type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!(
424"defining constant type: {}",
425 tcx.def_path_str_with_args(def_id, args),
426 ));
427 }
428 DefiningTy::InlineConst(def_id, args) => {
429err.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!(
430"defining inline constant type: {}",
431 tcx.def_path_str_with_args(def_id, args),
432 ));
433 }
434 DefiningTy::GlobalAsm(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
435 }
436 }
437438pub(crate) fn implicit_region_bound(&self) -> RegionVid {
439self.fr_fn_body
440 }
441442pub(crate) fn encountered_re_error(&self) -> Option<ErrorGuaranteed> {
443self.indices.encountered_re_error.get()
444 }
445}
446447struct UniversalRegionsBuilder<'infcx, 'tcx> {
448 infcx: &'infcx BorrowckInferCtxt<'tcx>,
449 mir_def: LocalDefId,
450}
451452impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> {
453fn build(self) -> UniversalRegions<'tcx> {
454{
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:454",
"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(454u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("build(mir_def={0:?})",
self.mir_def) as &dyn Value))])
});
} else { ; }
};debug!("build(mir_def={:?})", self.mir_def);
455456let param_env = self.infcx.param_env;
457{
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:457",
"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(457u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("build: param_env={0:?}",
param_env) as &dyn Value))])
});
} else { ; }
};debug!("build: param_env={:?}", param_env);
458459match (&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());
460461// Create the "global" region that is always free in all contexts: 'static.
462let fr_static = self463 .infcx
464 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
465 RegionCtxt::Free(kw::Static)
466 })
467 .as_var();
468469// We've now added all the global regions. The next ones we
470 // add will be external.
471let first_extern_index = self.infcx.num_region_vars();
472473let defining_ty = self.defining_ty();
474{
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:474",
"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(474u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("build: defining_ty={0:?}",
defining_ty) as &dyn Value))])
});
} else { ; }
};debug!("build: defining_ty={:?}", defining_ty);
475476let mut indices = self.compute_indices(fr_static, defining_ty);
477{
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:477",
"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(477u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("build: indices={0:?}",
indices) as &dyn Value))])
});
} else { ; }
};debug!("build: indices={:?}", indices);
478479let typeck_root_def_id = self.infcx.tcx.typeck_root_def_id(self.mir_def.to_def_id());
480481// If this is a 'root' body (not a closure/coroutine/inline const), then
482 // there are no extern regions, so the local regions start at the same
483 // position as the (empty) sub-list of extern regions
484let first_local_index = if self.mir_def.to_def_id() == typeck_root_def_id {
485first_extern_index486 } else {
487// If this is a closure, coroutine, or inline-const, then the late-bound regions from the enclosing
488 // function/closures are actually external regions to us. For example, here, 'a is not local
489 // to the closure c (although it is local to the fn foo):
490 // fn foo<'a>() {
491 // let c = || { let x: &'a u32 = ...; }
492 // }
493for_each_late_bound_region_in_recursive_scope(
494self.infcx.tcx,
495self.infcx.tcx.local_parent(self.mir_def),
496 |r| {
497{
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:497",
"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(497u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["r"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&r) as
&dyn Value))])
});
} else { ; }
};debug!(?r);
498let region_vid = {
499let name = r.get_name_or_anon(self.infcx.tcx);
500self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
501 RegionCtxt::LateBound(name)
502 })
503 };
504505{
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:505",
"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(505u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["region_vid"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(®ion_vid)
as &dyn Value))])
});
} else { ; }
};debug!(?region_vid);
506indices.insert_late_bound_region(r, region_vid.as_var());
507 },
508 );
509510// Any regions created during the execution of `defining_ty` or during the above
511 // late-bound region replacement are all considered 'extern' regions
512self.infcx.num_region_vars()
513 };
514515// Converse of above, if this is a function/closure then the late-bound regions declared
516 // on its signature are local.
517 //
518 // We manually loop over `bound_inputs_and_output` instead of using
519 // `for_each_late_bound_region_in_item` as we may need to add the otherwise
520 // implicit `ClosureEnv` region.
521let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
522for (idx, bound_var) in bound_inputs_and_output.bound_vars().iter().enumerate() {
523if let ty::BoundVariableKind::Region(kind) = bound_var {
524let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
525let r = ty::Region::new_late_param(self.infcx.tcx, self.mir_def.to_def_id(), kind);
526let region_vid = {
527let name = r.get_name_or_anon(self.infcx.tcx);
528self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
529 RegionCtxt::LateBound(name)
530 })
531 };
532533{
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:533",
"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(533u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["region_vid"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(®ion_vid)
as &dyn Value))])
});
} else { ; }
};debug!(?region_vid);
534 indices.insert_late_bound_region(r, region_vid.as_var());
535 }
536 }
537let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
538self.mir_def,
539bound_inputs_and_output,
540&indices,
541 );
542543let (unnormalized_output_ty, unnormalized_input_tys) =
544inputs_and_output.split_last().unwrap();
545546let fr_fn_body = self547 .infcx
548 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
549 RegionCtxt::Free(sym::fn_body)
550 })
551 .as_var();
552553let num_universals = self.infcx.num_region_vars();
554555{
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:555",
"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(555u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("build: global regions = {0}..{1}",
FIRST_GLOBAL_INDEX, first_extern_index) as &dyn Value))])
});
} else { ; }
};debug!("build: global regions = {}..{}", FIRST_GLOBAL_INDEX, first_extern_index);
556{
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:556",
"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(556u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("build: extern regions = {0}..{1}",
first_extern_index, first_local_index) as &dyn Value))])
});
} else { ; }
};debug!("build: extern regions = {}..{}", first_extern_index, first_local_index);
557{
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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("build: local regions = {0}..{1}",
first_local_index, num_universals) as &dyn Value))])
});
} else { ; }
};debug!("build: local regions = {}..{}", first_local_index, num_universals);
558559let (resume_ty, yield_ty) = match defining_ty {
560 DefiningTy::Coroutine(_, args) => {
561let tys = args.as_coroutine();
562 (Some(tys.resume_ty()), Some(tys.yield_ty()))
563 }
564_ => (None, None),
565 };
566567UniversalRegions {
568indices,
569fr_static,
570fr_fn_body,
571first_extern_index,
572first_local_index,
573num_universals,
574defining_ty,
575 unnormalized_output_ty: *unnormalized_output_ty,
576unnormalized_input_tys,
577yield_ty,
578resume_ty,
579 }
580 }
581582/// Returns the "defining type" of the current MIR;
583 /// see `DefiningTy` for details.
584fn defining_ty(&self) -> DefiningTy<'tcx> {
585let tcx = self.infcx.tcx;
586let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.to_def_id());
587588match tcx.hir_body_owner_kind(self.mir_def) {
589 BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
590let defining_ty = tcx.type_of(self.mir_def).instantiate_identity();
591592{
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:592",
"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(592u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("defining_ty (pre-replacement): {0:?}",
defining_ty) as &dyn Value))])
});
} else { ; }
};debug!("defining_ty (pre-replacement): {:?}", defining_ty);
593594let defining_ty = self.infcx.replace_free_regions_with_nll_infer_vars(
595 NllRegionVariableOrigin::FreeRegion,
596defining_ty,
597 );
598599match *defining_ty.kind() {
600 ty::Closure(def_id, args) => DefiningTy::Closure(def_id, args),
601 ty::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, args),
602 ty::CoroutineClosure(def_id, args) => {
603 DefiningTy::CoroutineClosure(def_id, args)
604 }
605 ty::FnDef(def_id, args) => DefiningTy::FnDef(def_id, args),
606_ => ::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!(
607tcx.def_span(self.mir_def),
608"expected defining type for `{:?}`: `{:?}`",
609self.mir_def,
610 defining_ty
611 ),
612 }
613 }
614615 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(..) => {
616let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
617if self.mir_def.to_def_id() == typeck_root_def_id {
618let args = self.infcx.replace_free_regions_with_nll_infer_vars(
619 NllRegionVariableOrigin::FreeRegion,
620identity_args,
621 );
622 DefiningTy::Const(self.mir_def.to_def_id(), args)
623 } else {
624// FIXME: this line creates a query dependency between borrowck and typeck.
625 //
626 // This is required for `AscribeUserType` canonical query, which will call
627 // `type_of(inline_const_def_id)`. That `type_of` would inject erased lifetimes
628 // into borrowck, which is ICE #78174.
629 //
630 // As a workaround, inline consts have an additional generic param (`ty`
631 // below), so that `type_of(inline_const_def_id).args(args)` uses the
632 // proper type with NLL infer vars.
633let ty = tcx634 .typeck(self.mir_def)
635 .node_type(tcx.local_def_id_to_hir_id(self.mir_def));
636let args = InlineConstArgs::new(
637tcx,
638InlineConstArgsParts { parent_args: identity_args, ty },
639 )
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 }
648649 BodyOwnerKind::GlobalAsm => DefiningTy::GlobalAsm(self.mir_def.to_def_id()),
650 }
651 }
652653/// Builds a hashmap that maps from the universal regions that are
654 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
655 /// `RegionVid`). The map returned by this function contains only
656 /// the early-bound regions.
657fn compute_indices(
658&self,
659 fr_static: RegionVid,
660 defining_ty: DefiningTy<'tcx>,
661 ) -> UniversalRegionIndices<'tcx> {
662let tcx = self.infcx.tcx;
663let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.to_def_id());
664let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
665let renumbered_args = defining_ty.args();
666667let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
668// This relies on typeck roots being generics_of parents with their
669 // parameters at the start of nested bodies' generics.
670if !(renumbered_args.len() >= identity_args.len()) {
::core::panicking::panic("assertion failed: renumbered_args.len() >= identity_args.len()")
};assert!(renumbered_args.len() >= identity_args.len());
671let arg_mapping =
672 iter::zip(identity_args.regions(), renumbered_args.regions().map(|r| r.as_var()));
673674UniversalRegionIndices {
675 indices: global_mapping.chain(arg_mapping).collect(),
676fr_static,
677 encountered_re_error: Cell::new(None),
678 }
679 }
680681fn compute_inputs_and_output(
682&self,
683 indices: &UniversalRegionIndices<'tcx>,
684 defining_ty: DefiningTy<'tcx>,
685 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
686let tcx = self.infcx.tcx;
687688let inputs_and_output = match defining_ty {
689 DefiningTy::Closure(def_id, args) => {
690match (&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);
691let closure_sig = args.as_closure().sig();
692let inputs_and_output = closure_sig.inputs_and_output();
693let bound_vars = tcx.mk_bound_variable_kinds_from_iter(
694inputs_and_output.bound_vars().iter().chain(iter::once(
695 ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv),
696 )),
697 );
698let br = ty::BoundRegion {
699 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
700 kind: ty::BoundRegionKind::ClosureEnv,
701 };
702let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
703let closure_ty = tcx.closure_env_ty(
704Ty::new_closure(tcx, def_id, args),
705args.as_closure().kind(),
706env_region,
707 );
708709// The "inputs" of the closure in the
710 // signature appear as a tuple. The MIR side
711 // flattens this tuple.
712let (&output, tuplized_inputs) =
713inputs_and_output.skip_binder().split_last().unwrap();
714match (&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");
715let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
716::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]);
717 };
718719 ty::Binder::bind_with_vars(
720tcx.mk_type_list_from_iter(
721 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
722 ),
723bound_vars,
724 )
725 }
726727 DefiningTy::Coroutine(def_id, args) => {
728match (&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);
729let resume_ty = args.as_coroutine().resume_ty();
730let output = args.as_coroutine().return_ty();
731let coroutine_ty = Ty::new_coroutine(tcx, def_id, args);
732let inputs_and_output =
733self.infcx.tcx.mk_type_list(&[coroutine_ty, resume_ty, output]);
734 ty::Binder::dummy(inputs_and_output)
735 }
736737// Construct the signature of the CoroutineClosure for the purposes of borrowck.
738 // This is pretty straightforward -- we:
739 // 1. first grab the `coroutine_closure_sig`,
740 // 2. compute the self type (`&`/`&mut`/no borrow),
741 // 3. flatten the tupled_input_tys,
742 // 4. construct the correct generator type to return with
743 // `CoroutineClosureSignature::to_coroutine_given_kind_and_upvars`.
744 // Then we wrap it all up into a list of inputs and output.
745DefiningTy::CoroutineClosure(def_id, args) => {
746match (&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);
747let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
748let bound_vars =
749tcx.mk_bound_variable_kinds_from_iter(closure_sig.bound_vars().iter().chain(
750 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
751 ));
752let br = ty::BoundRegion {
753 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
754 kind: ty::BoundRegionKind::ClosureEnv,
755 };
756let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
757let closure_kind = args.as_coroutine_closure().kind();
758759let closure_ty = tcx.closure_env_ty(
760Ty::new_coroutine_closure(tcx, def_id, args),
761closure_kind,
762env_region,
763 );
764765let inputs = closure_sig.skip_binder().tupled_inputs_ty.tuple_fields();
766let output = closure_sig.skip_binder().to_coroutine_given_kind_and_upvars(
767tcx,
768args.as_coroutine_closure().parent_args(),
769tcx.coroutine_for_closure(def_id),
770closure_kind,
771env_region,
772args.as_coroutine_closure().tupled_upvars_ty(),
773args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
774 );
775776 ty::Binder::bind_with_vars(
777tcx.mk_type_list_from_iter(
778 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
779 ),
780bound_vars,
781 )
782 }
783784 DefiningTy::FnDef(def_id, _) => {
785let sig = tcx.fn_sig(def_id).instantiate_identity();
786let sig = indices.fold_to_region_vids(tcx, sig);
787let inputs_and_output = sig.inputs_and_output();
788789// C-variadic fns also have a `VaList` input that's not listed in the signature
790 // (as it's created inside the body itself, not passed in from outside).
791if self.infcx.tcx.fn_sig(def_id).skip_binder().c_variadic() {
792let va_list_did = self793 .infcx
794 .tcx
795 .require_lang_item(LangItem::VaList, self.infcx.tcx.def_span(self.mir_def));
796797let reg_vid = self798 .infcx
799 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
800 RegionCtxt::Free(sym::c_dash_variadic)
801 })
802 .as_var();
803804let region = ty::Region::new_var(self.infcx.tcx, reg_vid);
805let va_list_ty = self806 .infcx
807 .tcx
808 .type_of(va_list_did)
809 .instantiate(self.infcx.tcx, &[region.into()]);
810811// The signature needs to follow the order [input_tys, va_list_ty, output_ty]
812return inputs_and_output.map_bound(|tys| {
813let (output_ty, input_tys) = tys.split_last().unwrap();
814tcx.mk_type_list_from_iter(
815input_tys.iter().copied().chain([va_list_ty, *output_ty]),
816 )
817 });
818 }
819820inputs_and_output821 }
822823 DefiningTy::Const(def_id, _) => {
824// For a constant body, there are no inputs, and one
825 // "output" (the type of the constant).
826match (&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);
827let ty = tcx.type_of(self.mir_def).instantiate_identity();
828829let ty = indices.fold_to_region_vids(tcx, ty);
830 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
831 }
832833 DefiningTy::InlineConst(def_id, args) => {
834match (&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);
835let ty = args.as_inline_const().ty();
836 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
837 }
838839 DefiningTy::GlobalAsm(def_id) => {
840 ty::Binder::dummy(tcx.mk_type_list(&[tcx.type_of(def_id).instantiate_identity()]))
841 }
842 };
843844// FIXME(#129952): We probably want a more principled approach here.
845if let Err(e) = inputs_and_output.error_reported() {
846self.infcx.set_tainted_by_errors(e);
847 }
848849inputs_and_output850 }
851}
852853impl<'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(855u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["origin", "value"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
as &dyn 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:866",
"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(&["region", "name"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(®ion) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&name) as
&dyn 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(872u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["all_outlive_scope",
"value"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&all_outlive_scope)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
as &dyn 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:883",
"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(&["br"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&br) as
&dyn 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>)]854impl<'tcx> BorrowckInferCtxt<'tcx> {
855#[instrument(skip(self), level = "debug")]
856fn replace_free_regions_with_nll_infer_vars<T>(
857&self,
858 origin: NllRegionVariableOrigin<'tcx>,
859 value: T,
860 ) -> T
861where
862T: TypeFoldable<TyCtxt<'tcx>>,
863 {
864 fold_regions(self.infcx.tcx, value, |region, _depth| {
865let name = region.get_name_or_anon(self.infcx.tcx);
866debug!(?region, ?name);
867868self.next_nll_region_var(origin, || RegionCtxt::Free(name))
869 })
870 }
871872#[instrument(level = "debug", skip(self, indices))]
873fn replace_bound_regions_with_nll_infer_vars<T>(
874&self,
875 all_outlive_scope: LocalDefId,
876 value: ty::Binder<'tcx, T>,
877 indices: &UniversalRegionIndices<'tcx>,
878 ) -> T
879where
880T: TypeFoldable<TyCtxt<'tcx>>,
881 {
882let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
883debug!(?br);
884let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
885let liberated_region =
886 ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
887 ty::Region::new_var(self.tcx, indices.to_region_vid(liberated_region))
888 });
889 value
890 }
891}
892893impl<'tcx> UniversalRegionIndices<'tcx> {
894/// Initially, the `UniversalRegionIndices` map contains only the
895 /// early-bound regions in scope. Once that is all setup, we come
896 /// in later and instantiate the late-bound regions, and then we
897 /// insert the `ReLateParam` version of those into the map as
898 /// well. These are used for error reporting.
899fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
900{
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:900",
"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(900u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("insert_late_bound_region({0:?}, {1:?})",
r, vid) as &dyn Value))])
});
} else { ; }
};debug!("insert_late_bound_region({:?}, {:?})", r, vid);
901match (&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);
902 }
903904/// Converts `r` into a local inference variable: `r` can either
905 /// be a `ReVar` (i.e., already a reference to an inference
906 /// variable) or it can be `'static` or some early-bound
907 /// region. This is useful when taking the results from
908 /// type-checking and trait-matching, which may sometimes
909 /// reference those regions from the `ParamEnv`. It is also used
910 /// during initialization. Relies on the `indices` map having been
911 /// fully initialized.
912 ///
913 /// Panics if `r` is not a registered universal region, most notably
914 /// if it is a placeholder. Handling placeholders requires access to the
915 /// `MirTypeckRegionConstraints`.
916fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
917match r.kind() {
918 ty::ReVar(..) => r.as_var(),
919 ty::ReError(guar) => {
920self.encountered_re_error.set(Some(guar));
921// We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
922 // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
923 // errors are being emitted and 2) it leaves the happy path unaffected.
924self.fr_static
925 }
926_ => *self927 .indices
928 .get(&r)
929 .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)),
930 }
931 }
932933/// Replaces all free regions in `value` with region vids, as
934 /// returned by `to_region_vid`.
935fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
936where
937T: TypeFoldable<TyCtxt<'tcx>>,
938 {
939fold_regions(tcx, value, |region, _| ty::Region::new_var(tcx, self.to_region_vid(region)))
940 }
941}
942943/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
944/// parents, up to the typeck root, and invokes `f` with the liberated form
945/// of each one.
946fn for_each_late_bound_region_in_recursive_scope<'tcx>(
947 tcx: TyCtxt<'tcx>,
948mut mir_def_id: LocalDefId,
949mut f: impl FnMut(ty::Region<'tcx>),
950) {
951let typeck_root_def_id = tcx.typeck_root_def_id(mir_def_id.to_def_id());
952953// Walk up the tree, collecting late-bound regions until we hit the typeck root
954loop {
955for_each_late_bound_region_in_item(tcx, mir_def_id, &mut f);
956957if mir_def_id.to_def_id() == typeck_root_def_id {
958break;
959 } else {
960mir_def_id = tcx.local_parent(mir_def_id);
961 }
962 }
963}
964965/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
966/// parents, up to the typeck root, and invokes `f` with the liberated form
967/// of each one.
968fn for_each_late_bound_region_in_item<'tcx>(
969 tcx: TyCtxt<'tcx>,
970 mir_def_id: LocalDefId,
971mut f: impl FnMut(ty::Region<'tcx>),
972) {
973let bound_vars = match tcx.def_kind(mir_def_id) {
974 DefKind::Fn | DefKind::AssocFn => {
975tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id))
976 }
977// We extract the bound vars from the deduced closure signature, since we may have
978 // only deduced that a param in the closure signature is late-bound from a constraint
979 // that we discover during typeck.
980DefKind::Closure => {
981let ty = tcx.type_of(mir_def_id).instantiate_identity();
982match *ty.kind() {
983 ty::Closure(_, args) => args.as_closure().sig().bound_vars(),
984 ty::CoroutineClosure(_, args) => {
985args.as_coroutine_closure().coroutine_closure_sig().bound_vars()
986 }
987 ty::Coroutine(_, _) | ty::Error(_) => return,
988_ => {
::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}"),
989 }
990 }
991_ => return,
992 };
993994for (idx, bound_var) in bound_vars.iter().enumerate() {
995if let ty::BoundVariableKind::Region(kind) = bound_var {
996let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
997let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind);
998 f(liberated_region);
999 }
1000 }
1001}