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. =)
82 ///
83 /// N.B., in the case of a closure, index 0 is the implicit self parameter,
84 /// and not the first input as seen by the user.
85pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
8687pub yield_ty: Option<Ty<'tcx>>,
8889pub resume_ty: Option<Ty<'tcx>>,
90}
9192/// The "defining type" for this MIR. The key feature of the "defining
93/// type" is that it contains the information needed to derive all the
94/// universal regions that are in scope as well as the types of the
95/// inputs/output from the MIR. In general, early-bound universal
96/// regions appear free in the defining type and late-bound regions
97/// appear bound in the signature.
98#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for DefiningTy<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for DefiningTy<'tcx> {
#[inline]
fn clone(&self) -> DefiningTy<'tcx> {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for DefiningTy<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DefiningTy::Closure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Closure", __self_0, &__self_1),
DefiningTy::Coroutine(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Coroutine", __self_0, &__self_1),
DefiningTy::CoroutineClosure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"CoroutineClosure", __self_0, &__self_1),
DefiningTy::FnDef(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "FnDef",
__self_0, &__self_1),
DefiningTy::Const(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Const",
__self_0, &__self_1),
DefiningTy::InlineConst(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"InlineConst", __self_0, &__self_1),
DefiningTy::GlobalAsm(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"GlobalAsm", &__self_0),
}
}
}Debug)]
99pub(crate) enum DefiningTy<'tcx> {
100/// The MIR is a closure. The signature is found via
101 /// `ClosureArgs::closure_sig_ty`.
102Closure(DefId, GenericArgsRef<'tcx>),
103104/// The MIR is a coroutine. The signature is that coroutines take
105 /// no parameters and return the result of
106 /// `ClosureArgs::coroutine_return_ty`.
107Coroutine(DefId, GenericArgsRef<'tcx>),
108109/// The MIR is a special kind of closure that returns coroutines.
110 ///
111 /// See the documentation on `CoroutineClosureSignature` for details
112 /// on how to construct the callable signature of the coroutine from
113 /// its args.
114CoroutineClosure(DefId, GenericArgsRef<'tcx>),
115116/// The MIR is a fn item with the given `DefId` and args. The signature
117 /// of the function can be bound then with the `fn_sig` query.
118FnDef(DefId, GenericArgsRef<'tcx>),
119120/// The MIR represents some form of constant. The signature then
121 /// is that it has no inputs and a single return value, which is
122 /// the value of the constant.
123Const(DefId, GenericArgsRef<'tcx>),
124125/// The MIR represents an inline const. The signature has no inputs and a
126 /// single return value found via `InlineConstArgs::ty`.
127InlineConst(DefId, GenericArgsRef<'tcx>),
128129// Fake body for a global asm. Not particularly useful or interesting,
130 // but we need it so we can properly store the typeck results of the asm
131 // operands, which aren't associated with a body otherwise.
132GlobalAsm(DefId),
133}
134135impl<'tcx> DefiningTy<'tcx> {
136/// Returns a list of all the upvar types for this MIR. If this is
137 /// not a closure or coroutine, there are no upvars, and hence it
138 /// will be an empty list. The order of types in this list will
139 /// match up with the upvar order in the HIR, typesystem, and MIR.
140pub(crate) fn upvar_tys(self) -> &'tcx ty::List<Ty<'tcx>> {
141match self {
142 DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(),
143 DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().upvar_tys(),
144 DefiningTy::Coroutine(_, args) => args.as_coroutine().upvar_tys(),
145 DefiningTy::FnDef(..)
146 | DefiningTy::Const(..)
147 | DefiningTy::InlineConst(..)
148 | DefiningTy::GlobalAsm(_) => ty::List::empty(),
149 }
150 }
151152/// Number of implicit inputs -- notably the "environment"
153 /// parameter for closures -- that appear in MIR but not in the
154 /// user's code.
155pub(crate) fn implicit_inputs(self) -> usize {
156match self {
157 DefiningTy::Closure(..)
158 | DefiningTy::CoroutineClosure(..)
159 | DefiningTy::Coroutine(..) => 1,
160 DefiningTy::FnDef(..)
161 | DefiningTy::Const(..)
162 | DefiningTy::InlineConst(..)
163 | DefiningTy::GlobalAsm(_) => 0,
164 }
165 }
166167pub(crate) fn is_fn_def(&self) -> bool {
168#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::FnDef(..) => true,
_ => false,
}matches!(*self, DefiningTy::FnDef(..))169 }
170171pub(crate) fn is_const(&self) -> bool {
172#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::Const(..) | DefiningTy::InlineConst(..) => true,
_ => false,
}matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))173 }
174175pub(crate) fn def_id(&self) -> DefId {
176match *self {
177 DefiningTy::Closure(def_id, ..)
178 | DefiningTy::CoroutineClosure(def_id, ..)
179 | DefiningTy::Coroutine(def_id, ..)
180 | DefiningTy::FnDef(def_id, ..)
181 | DefiningTy::Const(def_id, ..)
182 | DefiningTy::InlineConst(def_id, ..)
183 | DefiningTy::GlobalAsm(def_id) => def_id,
184 }
185 }
186187/// Returns the args of the `DefiningTy`. These are equivalent to the identity
188 /// substs of the body, but replaced with region vids.
189pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> {
190match *self {
191 DefiningTy::Closure(_, args)
192 | DefiningTy::Coroutine(_, args)
193 | DefiningTy::CoroutineClosure(_, args)
194 | DefiningTy::FnDef(_, args)
195 | DefiningTy::Const(_, args)
196 | DefiningTy::InlineConst(_, args) => args,
197 DefiningTy::GlobalAsm(_) => ty::List::empty(),
198 }
199 }
200}
201202#[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)]
203#[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)
204struct UniversalRegionIndices<'tcx> {
205/// For those regions that may appear in the parameter environment
206 /// ('static and early-bound regions), we maintain a map from the
207 /// `ty::Region` to the internal `RegionVid` we are using. This is
208 /// used because trait matching and type-checking will feed us
209 /// region constraints that reference those regions and we need to
210 /// be able to map them to our internal `RegionVid`.
211 ///
212 /// This is similar to just using `GenericArgs`, except that it contains
213 /// an entry for `'static`, and also late bound parameters in scope.
214indices: FxIndexMap<ty::Region<'tcx>, RegionVid>,
215216/// The vid assigned to `'static`. Used only for diagnostics.
217pub fr_static: RegionVid,
218219/// Whether we've encountered an error region. If we have, cancel all
220 /// outlives errors, as they are likely bogus.
221pub encountered_re_error: Cell<Option<ErrorGuaranteed>>,
222}
223224#[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)]
225pub(crate) enum RegionClassification {
226/// A **global** region is one that can be named from
227 /// anywhere. There is only one, `'static`.
228Global,
229230/// An **external** region is only relevant for
231 /// closures, coroutines, and inline consts. In that
232 /// case, it refers to regions that are free in the type
233 /// -- basically, something bound in the surrounding context.
234 ///
235 /// Consider this example:
236 ///
237 /// ```ignore (pseudo-rust)
238 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
239 /// let closure = for<'x> |x: &'x u32| { .. };
240 /// // ^^^^^^^ pretend this were legal syntax
241 /// // for declaring a late-bound region in
242 /// // a closure signature
243 /// }
244 /// ```
245 ///
246 /// Here, the lifetimes `'a` and `'b` would be **external** to the
247 /// closure.
248 ///
249 /// If we are not analyzing a closure/coroutine/inline-const,
250 /// there are no external lifetimes.
251External,
252253/// A **local** lifetime is one about which we know the full set
254 /// of relevant constraints (that is, relationships to other named
255 /// regions). For a closure, this includes any region bound in
256 /// the closure's signature. For a fn item, this includes all
257 /// regions other than global ones.
258 ///
259 /// Continuing with the example from `External`, if we were
260 /// analyzing the closure, then `'x` would be local (and `'a` and
261 /// `'b` are external). If we are analyzing the function item
262 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
263 /// scope).
264Local,
265}
266267const FIRST_GLOBAL_INDEX: usize = 0;
268269impl<'tcx> UniversalRegions<'tcx> {
270/// Creates a new and fully initialized `UniversalRegions` that
271 /// contains indices for all the free regions found in the given
272 /// MIR -- that is, all the regions that appear in the function's
273 /// signature.
274pub(crate) fn new(infcx: &BorrowckInferCtxt<'tcx>, mir_def: LocalDefId) -> Self {
275UniversalRegionsBuilder { infcx, mir_def }.build()
276 }
277278/// Given a reference to a closure type, extracts all the values
279 /// from its free regions and returns a vector with them. This is
280 /// used when the closure's creator checks that the
281 /// `ClosureRegionRequirements` are met. The requirements from
282 /// `ClosureRegionRequirements` are expressed in terms of
283 /// `RegionVid` entries that map into the returned vector `V`: so
284 /// if the `ClosureRegionRequirements` contains something like
285 /// `'1: '2`, then the caller would impose the constraint that
286 /// `V[1]: V[2]`.
287pub(crate) fn closure_mapping(
288 tcx: TyCtxt<'tcx>,
289 closure_args: GenericArgsRef<'tcx>,
290 expected_num_vars: usize,
291 closure_def_id: LocalDefId,
292 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
293let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
294region_mapping.push(tcx.lifetimes.re_static);
295tcx.for_each_free_region(&closure_args, |fr| {
296region_mapping.push(fr);
297 });
298299for_each_late_bound_region_in_recursive_scope(tcx, tcx.local_parent(closure_def_id), |r| {
300region_mapping.push(r);
301 });
302303match (®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!(
304 region_mapping.len(),
305 expected_num_vars,
306"index vec had unexpected number of variables"
307);
308309region_mapping310 }
311312/// Returns `true` if `r` is a member of this set of universal regions.
313pub(crate) fn is_universal_region(&self, r: RegionVid) -> bool {
314 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
315 }
316317/// Classifies `r` as a universal region, returning `None` if this
318 /// is not a member of this set of universal regions.
319pub(crate) fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
320let index = r.index();
321if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
322Some(RegionClassification::Global)
323 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
324Some(RegionClassification::External)
325 } else if (self.first_local_index..self.num_universals).contains(&index) {
326Some(RegionClassification::Local)
327 } else {
328None329 }
330 }
331332/// Returns an iterator over all the RegionVids corresponding to
333 /// universally quantified free regions.
334pub(crate) fn universal_regions_iter(&self) -> impl Iterator<Item = RegionVid> + 'static {
335 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize)
336 }
337338/// Returns `true` if `r` is classified as a local region.
339pub(crate) fn is_local_free_region(&self, r: RegionVid) -> bool {
340self.region_classification(r) == Some(RegionClassification::Local)
341 }
342343/// Returns the number of universal regions created in any category.
344pub(crate) fn len(&self) -> usize {
345self.num_universals
346 }
347348/// Returns the number of global plus external universal regions.
349 /// For closures, these are the regions that appear free in the
350 /// closure type (versus those bound in the closure
351 /// signature). They are therefore the regions between which the
352 /// closure may impose constraints that its creator must verify.
353pub(crate) fn num_global_and_external_regions(&self) -> usize {
354self.first_local_index
355 }
356357/// Gets an iterator over all the early-bound regions that have names.
358pub(crate) fn named_universal_regions_iter(
359&self,
360 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> {
361self.indices.indices.iter().map(|(&r, &v)| (r, v))
362 }
363364/// See [UniversalRegionIndices::to_region_vid].
365pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
366self.indices.to_region_vid(r)
367 }
368369/// As part of the NLL unit tests, you can annotate a function with
370 /// `#[rustc_regions]`, and we will emit information about the region
371 /// inference context and -- in particular -- the external constraints
372 /// that this region imposes on others. The methods in this file
373 /// handle the part about dumping the inference context internal
374 /// state.
375pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
376match self.defining_ty {
377 DefiningTy::Closure(def_id, args) => {
378let 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!(
379 args[tcx.generics_of(def_id).parent_count..]
380 .iter()
381 .map(|arg| arg.to_string())
382 .collect::<Vec<_>>()
383 );
384err.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!(
385"defining type: {} with closure args [\n {},\n]",
386 tcx.def_path_str_with_args(def_id, args),
387 v.join(",\n "),
388 ));
389390// FIXME: It'd be nice to print the late-bound regions
391 // here, but unfortunately these wind up stored into
392 // tests, and the resulting print-outs include def-ids
393 // and other things that are not stable across tests!
394 // So we just include the region-vid. Annoying.
395for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
396err.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)));
397 });
398 }
399 DefiningTy::CoroutineClosure(..) => {
400::core::panicking::panic("not yet implemented")todo!()401 }
402 DefiningTy::Coroutine(def_id, args) => {
403let 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!(
404 args[tcx.generics_of(def_id).parent_count..]
405 .iter()
406 .map(|arg| arg.to_string())
407 .collect::<Vec<_>>()
408 );
409err.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!(
410"defining type: {} with coroutine args [\n {},\n]",
411 tcx.def_path_str_with_args(def_id, args),
412 v.join(",\n "),
413 ));
414415// FIXME: As above, we'd like to print out the region
416 // `r` but doing so is not stable across architectures
417 // and so forth.
418for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
419err.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)));
420 });
421 }
422 DefiningTy::FnDef(def_id, args) => {
423err.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),));
424 }
425 DefiningTy::Const(def_id, args) => {
426err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining constant type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!(
427"defining constant type: {}",
428 tcx.def_path_str_with_args(def_id, args),
429 ));
430 }
431 DefiningTy::InlineConst(def_id, args) => {
432err.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!(
433"defining inline constant type: {}",
434 tcx.def_path_str_with_args(def_id, args),
435 ));
436 }
437 DefiningTy::GlobalAsm(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
438 }
439 }
440441pub(crate) fn implicit_region_bound(&self) -> RegionVid {
442self.fr_fn_body
443 }
444445pub(crate) fn encountered_re_error(&self) -> Option<ErrorGuaranteed> {
446self.indices.encountered_re_error.get()
447 }
448}
449450struct UniversalRegionsBuilder<'infcx, 'tcx> {
451 infcx: &'infcx BorrowckInferCtxt<'tcx>,
452 mir_def: LocalDefId,
453}
454455impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> {
456fn build(self) -> UniversalRegions<'tcx> {
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(mir_def={0:?})",
self.mir_def) as &dyn Value))])
});
} else { ; }
};debug!("build(mir_def={:?})", self.mir_def);
458459let param_env = self.infcx.param_env;
460{
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:460",
"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(460u32),
::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);
461462match (&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());
463464// Create the "global" region that is always free in all contexts: 'static.
465let fr_static = self466 .infcx
467 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
468 RegionCtxt::Free(kw::Static)
469 })
470 .as_var();
471472// We've now added all the global regions. The next ones we
473 // add will be external.
474let first_extern_index = self.infcx.num_region_vars();
475476let defining_ty = self.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: defining_ty={0:?}",
defining_ty) as &dyn Value))])
});
} else { ; }
};debug!("build: defining_ty={:?}", defining_ty);
478479let mut indices = self.compute_indices(fr_static, defining_ty);
480{
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:480",
"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(480u32),
::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);
481482// If this is a 'root' body (not a closure/coroutine/inline const), then
483 // there are no extern regions, so the local regions start at the same
484 // position as the (empty) sub-list of extern regions
485let first_local_index = if !self.infcx.tcx.is_typeck_child(self.mir_def.to_def_id()) {
486first_extern_index487 } else {
488// If this is a closure, coroutine, or inline-const, then the late-bound regions from the enclosing
489 // function/closures are actually external regions to us. For example, here, 'a is not local
490 // to the closure c (although it is local to the fn foo):
491 // fn foo<'a>() {
492 // let c = || { let x: &'a u32 = ...; }
493 // }
494for_each_late_bound_region_in_recursive_scope(
495self.infcx.tcx,
496self.infcx.tcx.local_parent(self.mir_def),
497 |r| {
498{
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:498",
"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(498u32),
::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);
499let region_vid = {
500let name = r.get_name_or_anon(self.infcx.tcx);
501self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
502 RegionCtxt::LateBound(name)
503 })
504 };
505506{
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:506",
"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(506u32),
::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);
507indices.insert_late_bound_region(r, region_vid.as_var());
508 },
509 );
510511// Any regions created during the execution of `defining_ty` or during the above
512 // late-bound region replacement are all considered 'extern' regions
513self.infcx.num_region_vars()
514 };
515516// Converse of above, if this is a function/closure then the late-bound regions declared
517 // on its signature are local.
518 //
519 // We manually loop over `bound_inputs_and_output` instead of using
520 // `for_each_late_bound_region_in_item` as we may need to add the otherwise
521 // implicit `ClosureEnv` region.
522let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
523for (idx, bound_var) in bound_inputs_and_output.bound_vars().iter().enumerate() {
524if let ty::BoundVariableKind::Region(kind) = bound_var {
525let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
526let r = ty::Region::new_late_param(self.infcx.tcx, self.mir_def.to_def_id(), kind);
527let region_vid = {
528let name = r.get_name_or_anon(self.infcx.tcx);
529self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
530 RegionCtxt::LateBound(name)
531 })
532 };
533534{
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:534",
"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(534u32),
::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);
535 indices.insert_late_bound_region(r, region_vid.as_var());
536 }
537 }
538let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
539self.mir_def,
540bound_inputs_and_output,
541&indices,
542 );
543544let (unnormalized_output_ty, unnormalized_input_tys) =
545inputs_and_output.split_last().unwrap();
546547let fr_fn_body = self548 .infcx
549 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
550 RegionCtxt::Free(sym::fn_body)
551 })
552 .as_var();
553554let num_universals = self.infcx.num_region_vars();
555556{
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: global regions = {0}..{1}",
FIRST_GLOBAL_INDEX, first_extern_index) as &dyn Value))])
});
} else { ; }
};debug!("build: global regions = {}..{}", FIRST_GLOBAL_INDEX, first_extern_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: extern regions = {0}..{1}",
first_extern_index, first_local_index) as &dyn Value))])
});
} else { ; }
};debug!("build: extern regions = {}..{}", first_extern_index, first_local_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};
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);
559560let (resume_ty, yield_ty) = match defining_ty {
561 DefiningTy::Coroutine(_, args) => {
562let tys = args.as_coroutine();
563 (Some(tys.resume_ty()), Some(tys.yield_ty()))
564 }
565_ => (None, None),
566 };
567568UniversalRegions {
569indices,
570fr_static,
571fr_fn_body,
572first_extern_index,
573first_local_index,
574num_universals,
575defining_ty,
576 unnormalized_output_ty: *unnormalized_output_ty,
577unnormalized_input_tys,
578yield_ty,
579resume_ty,
580 }
581 }
582583/// Returns the "defining type" of the current MIR;
584 /// see `DefiningTy` for details.
585fn defining_ty(&self) -> DefiningTy<'tcx> {
586let tcx = self.infcx.tcx;
587let typeck_root_def_id = tcx.typeck_root_def_id_local(self.mir_def);
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};
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);
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) => DefiningTy::FnDef(def_id, args),
607_ => ::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!(
608tcx.def_span(self.mir_def),
609"expected defining type for `{:?}`: `{:?}`",
610self.mir_def,
611 defining_ty
612 ),
613 }
614 }
615616 BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(..) => {
617let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
618if self.mir_def == typeck_root_def_id {
619let args = self.infcx.replace_free_regions_with_nll_infer_vars(
620 NllRegionVariableOrigin::FreeRegion,
621identity_args,
622 );
623 DefiningTy::Const(self.mir_def.to_def_id(), args)
624 } else {
625// FIXME: this line creates a query dependency between borrowck and typeck.
626 //
627 // This is required for `AscribeUserType` canonical query, which will call
628 // `type_of(inline_const_def_id)`. That `type_of` would inject erased lifetimes
629 // into borrowck, which is ICE #78174.
630 //
631 // As a workaround, inline consts have an additional generic param (`ty`
632 // below), so that `type_of(inline_const_def_id).args(args)` uses the
633 // proper type with NLL infer vars.
634let ty = tcx635 .typeck(self.mir_def)
636 .node_type(tcx.local_def_id_to_hir_id(self.mir_def));
637let args = InlineConstArgs::new(
638tcx,
639InlineConstArgsParts { parent_args: identity_args, ty },
640 )
641 .args;
642let args = self.infcx.replace_free_regions_with_nll_infer_vars(
643 NllRegionVariableOrigin::FreeRegion,
644args,
645 );
646 DefiningTy::InlineConst(self.mir_def.to_def_id(), args)
647 }
648 }
649650 BodyOwnerKind::GlobalAsm => DefiningTy::GlobalAsm(self.mir_def.to_def_id()),
651 }
652 }
653654/// Builds a hashmap that maps from the universal regions that are
655 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
656 /// `RegionVid`). The map returned by this function contains only
657 /// the early-bound regions.
658fn compute_indices(
659&self,
660 fr_static: RegionVid,
661 defining_ty: DefiningTy<'tcx>,
662 ) -> UniversalRegionIndices<'tcx> {
663let tcx = self.infcx.tcx;
664let typeck_root_def_id = tcx.typeck_root_def_id_local(self.mir_def);
665let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
666let renumbered_args = defining_ty.args();
667668let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
669// This relies on typeck roots being generics_of parents with their
670 // parameters at the start of nested bodies' generics.
671if !(renumbered_args.len() >= identity_args.len()) {
::core::panicking::panic("assertion failed: renumbered_args.len() >= identity_args.len()")
};assert!(renumbered_args.len() >= identity_args.len());
672let arg_mapping =
673 iter::zip(identity_args.regions(), renumbered_args.regions().map(|r| r.as_var()));
674675UniversalRegionIndices {
676 indices: global_mapping.chain(arg_mapping).collect(),
677fr_static,
678 encountered_re_error: Cell::new(None),
679 }
680 }
681682fn compute_inputs_and_output(
683&self,
684 indices: &UniversalRegionIndices<'tcx>,
685 defining_ty: DefiningTy<'tcx>,
686 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
687let tcx = self.infcx.tcx;
688689let inputs_and_output = match defining_ty {
690 DefiningTy::Closure(def_id, args) => {
691match (&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);
692let closure_sig = args.as_closure().sig();
693let inputs_and_output = closure_sig.inputs_and_output();
694let bound_vars = tcx.mk_bound_variable_kinds_from_iter(
695inputs_and_output.bound_vars().iter().chain(iter::once(
696 ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv),
697 )),
698 );
699let br = ty::BoundRegion {
700 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
701 kind: ty::BoundRegionKind::ClosureEnv,
702 };
703let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
704let closure_ty = tcx.closure_env_ty(
705Ty::new_closure(tcx, def_id, args),
706args.as_closure().kind(),
707env_region,
708 );
709710// The "inputs" of the closure in the
711 // signature appear as a tuple. The MIR side
712 // flattens this tuple.
713let (&output, tuplized_inputs) =
714inputs_and_output.skip_binder().split_last().unwrap();
715match (&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");
716let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
717::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]);
718 };
719720 ty::Binder::bind_with_vars(
721tcx.mk_type_list_from_iter(
722 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
723 ),
724bound_vars,
725 )
726 }
727728 DefiningTy::Coroutine(def_id, args) => {
729match (&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);
730let resume_ty = args.as_coroutine().resume_ty();
731let output = args.as_coroutine().return_ty();
732let coroutine_ty = Ty::new_coroutine(tcx, def_id, args);
733let inputs_and_output =
734self.infcx.tcx.mk_type_list(&[coroutine_ty, resume_ty, output]);
735 ty::Binder::dummy(inputs_and_output)
736 }
737738// Construct the signature of the CoroutineClosure for the purposes of borrowck.
739 // This is pretty straightforward -- we:
740 // 1. first grab the `coroutine_closure_sig`,
741 // 2. compute the self type (`&`/`&mut`/no borrow),
742 // 3. flatten the tupled_input_tys,
743 // 4. construct the correct generator type to return with
744 // `CoroutineClosureSignature::to_coroutine_given_kind_and_upvars`.
745 // Then we wrap it all up into a list of inputs and output.
746DefiningTy::CoroutineClosure(def_id, args) => {
747match (&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);
748let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
749let bound_vars =
750tcx.mk_bound_variable_kinds_from_iter(closure_sig.bound_vars().iter().chain(
751 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
752 ));
753let br = ty::BoundRegion {
754 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
755 kind: ty::BoundRegionKind::ClosureEnv,
756 };
757let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
758let closure_kind = args.as_coroutine_closure().kind();
759760let closure_ty = tcx.closure_env_ty(
761Ty::new_coroutine_closure(tcx, def_id, args),
762closure_kind,
763env_region,
764 );
765766let inputs = closure_sig.skip_binder().tupled_inputs_ty.tuple_fields();
767let output = closure_sig.skip_binder().to_coroutine_given_kind_and_upvars(
768tcx,
769args.as_coroutine_closure().parent_args(),
770tcx.coroutine_for_closure(def_id),
771closure_kind,
772env_region,
773args.as_coroutine_closure().tupled_upvars_ty(),
774args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
775 );
776777 ty::Binder::bind_with_vars(
778tcx.mk_type_list_from_iter(
779 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
780 ),
781bound_vars,
782 )
783 }
784785 DefiningTy::FnDef(def_id, _) => {
786let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
787let sig = indices.fold_to_region_vids(tcx, sig);
788let inputs_and_output = sig.inputs_and_output();
789790// C-variadic fns also have a `VaList` input that's not listed in the signature
791 // (as it's created inside the body itself, not passed in from outside).
792if self.infcx.tcx.fn_sig(def_id).skip_binder().c_variadic() {
793let va_list_did = self794 .infcx
795 .tcx
796 .require_lang_item(LangItem::VaList, self.infcx.tcx.def_span(self.mir_def));
797798let reg_vid = self799 .infcx
800 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
801 RegionCtxt::Free(sym::c_dash_variadic)
802 })
803 .as_var();
804805let region = ty::Region::new_var(self.infcx.tcx, reg_vid);
806let va_list_ty = self807 .infcx
808 .tcx
809 .type_of(va_list_did)
810 .instantiate(self.infcx.tcx, &[region.into()])
811 .skip_norm_wip();
812813// The signature needs to follow the order [input_tys, va_list_ty, output_ty]
814return inputs_and_output.map_bound(|tys| {
815let (output_ty, input_tys) = tys.split_last().unwrap();
816tcx.mk_type_list_from_iter(
817input_tys.iter().copied().chain([va_list_ty, *output_ty]),
818 )
819 });
820 }
821822inputs_and_output823 }
824825 DefiningTy::Const(def_id, _) => {
826// For a constant body, there are no inputs, and one
827 // "output" (the type of the constant).
828match (&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);
829let ty = tcx.type_of(self.mir_def).instantiate_identity().skip_norm_wip();
830831let ty = indices.fold_to_region_vids(tcx, ty);
832 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
833 }
834835 DefiningTy::InlineConst(def_id, args) => {
836match (&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);
837let ty = args.as_inline_const().ty();
838 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
839 }
840841 DefiningTy::GlobalAsm(def_id) => ty::Binder::dummy(
842tcx.mk_type_list(&[tcx.type_of(def_id).instantiate_identity().skip_norm_wip()]),
843 ),
844 };
845846// FIXME(#129952): We probably want a more principled approach here.
847if let Err(e) = inputs_and_output.error_reported() {
848self.infcx.set_tainted_by_errors(e);
849 }
850851inputs_and_output852 }
853}
854855impl<'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(857u32),
::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:868",
"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(868u32),
::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(874u32),
::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:885",
"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(885u32),
::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>)]856impl<'tcx> BorrowckInferCtxt<'tcx> {
857#[instrument(skip(self), level = "debug")]
858fn replace_free_regions_with_nll_infer_vars<T>(
859&self,
860 origin: NllRegionVariableOrigin<'tcx>,
861 value: T,
862 ) -> T
863where
864T: TypeFoldable<TyCtxt<'tcx>>,
865 {
866 fold_regions(self.infcx.tcx, value, |region, _depth| {
867let name = region.get_name_or_anon(self.infcx.tcx);
868debug!(?region, ?name);
869870self.next_nll_region_var(origin, || RegionCtxt::Free(name))
871 })
872 }
873874#[instrument(level = "debug", skip(self, indices))]
875fn replace_bound_regions_with_nll_infer_vars<T>(
876&self,
877 all_outlive_scope: LocalDefId,
878 value: ty::Binder<'tcx, T>,
879 indices: &UniversalRegionIndices<'tcx>,
880 ) -> T
881where
882T: TypeFoldable<TyCtxt<'tcx>>,
883 {
884let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
885debug!(?br);
886let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
887let liberated_region =
888 ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
889 ty::Region::new_var(self.tcx, indices.to_region_vid(liberated_region))
890 });
891 value
892 }
893}
894895impl<'tcx> UniversalRegionIndices<'tcx> {
896/// Initially, the `UniversalRegionIndices` map contains only the
897 /// early-bound regions in scope. Once that is all setup, we come
898 /// in later and instantiate the late-bound regions, and then we
899 /// insert the `ReLateParam` version of those into the map as
900 /// well. These are used for error reporting.
901fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
902{
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:902",
"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(902u32),
::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);
903match (&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);
904 }
905906/// Converts `r` into a local inference variable: `r` can either
907 /// be a `ReVar` (i.e., already a reference to an inference
908 /// variable) or it can be `'static` or some early-bound
909 /// region. This is useful when taking the results from
910 /// type-checking and trait-matching, which may sometimes
911 /// reference those regions from the `ParamEnv`. It is also used
912 /// during initialization. Relies on the `indices` map having been
913 /// fully initialized.
914 ///
915 /// Panics if `r` is not a registered universal region, most notably
916 /// if it is a placeholder. Handling placeholders requires access to the
917 /// `MirTypeckRegionConstraints`.
918fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
919match r.kind() {
920 ty::ReVar(..) => r.as_var(),
921 ty::ReError(guar) => {
922self.encountered_re_error.set(Some(guar));
923// We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
924 // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
925 // errors are being emitted and 2) it leaves the happy path unaffected.
926self.fr_static
927 }
928_ => *self929 .indices
930 .get(&r)
931 .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)),
932 }
933 }
934935/// Replaces all free regions in `value` with region vids, as
936 /// returned by `to_region_vid`.
937fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
938where
939T: TypeFoldable<TyCtxt<'tcx>>,
940 {
941fold_regions(tcx, value, |region, _| ty::Region::new_var(tcx, self.to_region_vid(region)))
942 }
943}
944945/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
946/// parents, up to the typeck root, and invokes `f` with the liberated form
947/// of each one.
948fn for_each_late_bound_region_in_recursive_scope<'tcx>(
949 tcx: TyCtxt<'tcx>,
950mut mir_def_id: LocalDefId,
951mut f: impl FnMut(ty::Region<'tcx>),
952) {
953// 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 tcx.is_typeck_child(mir_def_id.to_def_id()) {
958mir_def_id = tcx.local_parent(mir_def_id);
959 } else {
960break;
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().skip_norm_wip();
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}