1//! Code to extract the universally quantified regions declared on a
2//! function. For example:
3//!
4//! ```
5//! fn foo<'a, 'b, 'c: 'b>() { }
6//! ```
7//!
8//! here we would return a map assigning each of `{'a, 'b, 'c}`
9//! to an index.
10//!
11//! The code in this file doesn't *do anything* with those results; it
12//! just returns them for other code to use.
1314use std::cell::Cell;
15use std::iter;
1617use rustc_data_structures::fx::FxIndexMap;
18use rustc_errors::Diag;
19use rustc_hir::BodyOwnerKind;
20use rustc_hir::attrs::lang_items::LangItem;
21use rustc_hir::def::DefKind;
22use rustc_hir::def_id::{DefId, LocalDefId};
23use rustc_index::IndexVec;
24use rustc_infer::infer::NllRegionVariableOrigin;
25use rustc_macros::extension;
26use rustc_middle::mir::RETURN_PLACE;
27use rustc_middle::ty::print::with_no_trimmed_paths;
28use rustc_middle::ty::{
29self, BoundVariableKind, GenericArgs, GenericArgsRef, InlineConstArgs, InlineConstArgsParts,
30List, RegionExt, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, fold_regions,
31};
32use rustc_middle::{bug, span_bug};
33use rustc_span::{ErrorGuaranteed, kw, sym};
34use tracing::{debug, instrument};
3536use crate::BorrowckInferCtxt;
37use crate::renumber::RegionCtxt;
3839#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for UniversalRegions<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["indices", "fr_static", "fr_fn_body", "first_extern_index",
"first_local_index", "num_universals", "defining_ty",
"unnormalized_output_ty", "unnormalized_input_tys",
"yield_ty", "resume_ty"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.indices, &self.fr_static, &self.fr_fn_body,
&self.first_extern_index, &self.first_local_index,
&self.num_universals, &self.defining_ty,
&self.unnormalized_output_ty, &self.unnormalized_input_tys,
&self.yield_ty, &&self.resume_ty];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"UniversalRegions", names, values)
}
}Debug)]
40#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for UniversalRegions<'tcx> {
#[inline]
fn clone(&self) -> UniversalRegions<'tcx> {
UniversalRegions {
indices: ::core::clone::Clone::clone(&self.indices),
fr_static: ::core::clone::Clone::clone(&self.fr_static),
fr_fn_body: ::core::clone::Clone::clone(&self.fr_fn_body),
first_extern_index: ::core::clone::Clone::clone(&self.first_extern_index),
first_local_index: ::core::clone::Clone::clone(&self.first_local_index),
num_universals: ::core::clone::Clone::clone(&self.num_universals),
defining_ty: ::core::clone::Clone::clone(&self.defining_ty),
unnormalized_output_ty: ::core::clone::Clone::clone(&self.unnormalized_output_ty),
unnormalized_input_tys: ::core::clone::Clone::clone(&self.unnormalized_input_tys),
yield_ty: ::core::clone::Clone::clone(&self.yield_ty),
resume_ty: ::core::clone::Clone::clone(&self.resume_ty),
}
}
}Clone)] // FIXME(#146079)
41pub(crate) struct UniversalRegions<'tcx> {
42 indices: UniversalRegionIndices<'tcx>,
4344/// The vid assigned to `'static`
45pub fr_static: RegionVid,
4647/// A special region vid created to represent the current MIR fn
48 /// body. It will outlive the entire CFG but it will not outlive
49 /// any other universal regions.
50pub fr_fn_body: RegionVid,
5152/// We create region variables such that they are ordered by their
53 /// `RegionClassification`. The first block are globals, then
54 /// externals, then locals. So, things from:
55 /// - `FIRST_GLOBAL_INDEX..first_extern_index` are global,
56 /// - `first_extern_index..first_local_index` are external,
57 /// - `first_local_index..num_universals` are local.
58first_extern_index: usize,
5960/// See `first_extern_index`.
61first_local_index: usize,
6263/// The total number of universal region variables instantiated.
64num_universals: usize,
6566/// The "defining" type for this function, with all universal
67 /// regions instantiated. For a closure or coroutine, this is the
68 /// closure type, but for a top-level function it's the `FnDef`.
69pub defining_ty: DefiningTy<'tcx>,
7071/// The return type of this function, with all regions replaced by
72 /// their universal `RegionVid` equivalents.
73 ///
74 /// N.B., associated types in this type have not been normalized,
75 /// as the name suggests. =)
76pub unnormalized_output_ty: Ty<'tcx>,
7778/// The fully liberated input types of this function, with all
79 /// regions replaced by their universal `RegionVid` equivalents.
80 ///
81 /// N.B., associated types in these types have not been normalized,
82 /// as the name suggests. =)
83 ///
84 /// N.B., in the case of a closure, index 0 is the implicit self parameter,
85 /// and not the first input as seen by the user.
86pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
8788pub yield_ty: Option<Ty<'tcx>>,
8990pub resume_ty: Option<Ty<'tcx>>,
91}
9293/// The "defining type" for this MIR. The key feature of the "defining
94/// type" is that it contains the information needed to derive all the
95/// universal regions that are in scope as well as the types of the
96/// inputs/output from the MIR. In general, early-bound universal
97/// regions appear free in the defining type and late-bound regions
98/// appear bound in the signature.
99#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for DefiningTy<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for DefiningTy<'tcx> {
#[inline]
fn clone(&self) -> DefiningTy<'tcx> {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for DefiningTy<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DefiningTy::Closure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Closure", __self_0, &__self_1),
DefiningTy::Coroutine(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Coroutine", __self_0, &__self_1),
DefiningTy::CoroutineClosure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"CoroutineClosure", __self_0, &__self_1),
DefiningTy::FnDef(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "FnDef",
__self_0, &__self_1),
DefiningTy::Const(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Const",
__self_0, &__self_1),
DefiningTy::InlineConst(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"InlineConst", __self_0, &__self_1),
DefiningTy::GlobalAsm(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"GlobalAsm", &__self_0),
}
}
}Debug)]
100pub(crate) enum DefiningTy<'tcx> {
101/// The MIR is a closure. The signature is found via
102 /// `ClosureArgs::closure_sig_ty`.
103Closure(DefId, GenericArgsRef<'tcx>),
104105/// The MIR is a coroutine. The signature is that coroutines take
106 /// no parameters and return the result of
107 /// `ClosureArgs::coroutine_return_ty`.
108Coroutine(DefId, GenericArgsRef<'tcx>),
109110/// The MIR is a special kind of closure that returns coroutines.
111 ///
112 /// See the documentation on `CoroutineClosureSignature` for details
113 /// on how to construct the callable signature of the coroutine from
114 /// its args.
115CoroutineClosure(DefId, GenericArgsRef<'tcx>),
116117/// The MIR is a fn item with the given `DefId` and args. The signature
118 /// of the function can be bound then with the `fn_sig` query.
119FnDef(DefId, GenericArgsRef<'tcx>),
120121/// The MIR represents some form of constant. The signature then
122 /// is that it has no inputs and a single return value, which is
123 /// the value of the constant.
124Const(DefId, GenericArgsRef<'tcx>),
125126/// The MIR represents an inline const. The signature has no inputs and a
127 /// single return value found via `InlineConstArgs::ty`.
128InlineConst(DefId, GenericArgsRef<'tcx>),
129130// Fake body for a global asm. Not particularly useful or interesting,
131 // but we need it so we can properly store the typeck results of the asm
132 // operands, which aren't associated with a body otherwise.
133GlobalAsm(DefId),
134}
135136impl<'tcx> DefiningTy<'tcx> {
137x;#[instrument(level = "debug", skip(tcx), ret)]138pub(crate) fn new(tcx: TyCtxt<'tcx>, body_def_id: LocalDefId) -> DefiningTy<'tcx> {
139match tcx.hir_body_owner_kind(body_def_id) {
140 BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
141let defining_ty = tcx.type_of(body_def_id).instantiate_identity().skip_norm_wip();
142match *defining_ty.kind() {
143 ty::Closure(def_id, args) => DefiningTy::Closure(def_id, args),
144 ty::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, args),
145 ty::CoroutineClosure(def_id, args) => {
146 DefiningTy::CoroutineClosure(def_id, args)
147 }
148 ty::FnDef(def_id, args) => {
149 DefiningTy::FnDef(def_id, args.no_bound_vars().unwrap())
150 }
151_ => span_bug!(
152 tcx.def_span(body_def_id),
153"expected defining type for `{body_def_id:?}`: `{defining_ty:?}`",
154 ),
155 }
156 }
157158 BodyOwnerKind::Const { inline: true } => {
159// This is required for `AscribeUserType` canonical query, which will call
160 // `type_of(inline_const_def_id)`. That `type_of` would inject erased lifetimes
161 // into borrowck, which is ICE #78174.
162 //
163 // As a workaround, inline consts have an additional generic param (`ty`
164 // below), so that `type_of(inline_const_def_id).substs(substs)` uses the
165 // proper type with NLL infer vars.
166 //
167 // Fetch the actual type from MIR, as `type_of` returns something useless
168 // like `<const_ty>`.
169let body = tcx.mir_promoted(body_def_id).0.borrow();
170let ty = body.local_decls[RETURN_PLACE].ty;
171let typeck_root_def_id = tcx.typeck_root_def_id(body_def_id.to_def_id());
172let parent_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
173let args = InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty }).args;
174 DefiningTy::InlineConst(body_def_id.to_def_id(), args)
175 }
176177 BodyOwnerKind::Const { inline: false } | BodyOwnerKind::Static(..) => {
178let args = GenericArgs::identity_for_item(tcx, body_def_id.to_def_id());
179 DefiningTy::Const(body_def_id.to_def_id(), args)
180 }
181182 BodyOwnerKind::GlobalAsm => DefiningTy::GlobalAsm(body_def_id.to_def_id()),
183 }
184 }
185186/// The bound variables for a given defining type. This differs from their usual bound vars
187 /// in that closures and coroutine closures have an additional `'env`, while C-variadic
188 /// functions have an additional region for their implicit `VaList` input.
189pub(crate) fn bound_vars(self, tcx: TyCtxt<'tcx>) -> &'tcx List<BoundVariableKind<'tcx>> {
190match self {
191 DefiningTy::Closure(_, args) => {
192let closure_sig = args.as_closure().sig();
193let inputs_and_output = closure_sig.inputs_and_output();
194tcx.mk_bound_variable_kinds_from_iter(inputs_and_output.bound_vars().iter().chain(
195 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
196 ))
197 }
198199 DefiningTy::CoroutineClosure(_, args) => {
200let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
201tcx.mk_bound_variable_kinds_from_iter(closure_sig.bound_vars().iter().chain(
202 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::ClosureEnv)),
203 ))
204 }
205206 DefiningTy::FnDef(def_id, _) => {
207let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
208if sig.skip_binder().c_variadic() {
209// FIXME(#160495): Don't use an anonymous region here
210tcx.mk_bound_variable_kinds_from_iter(sig.bound_vars().iter().chain(
211 iter::once(ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon)),
212 ))
213 } else {
214sig.bound_vars()
215 }
216 }
217218 DefiningTy::Coroutine(..)
219 | DefiningTy::Const(..)
220 | DefiningTy::InlineConst(..)
221 | DefiningTy::GlobalAsm(..) => ty::List::empty(),
222 }
223 }
224225x;#[instrument(level = "debug", skip(tcx), ret)]226pub(crate) fn inputs_and_output(
227self,
228 tcx: TyCtxt<'tcx>,
229 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
230match self {
231 DefiningTy::Closure(def_id, args) => {
232let closure_sig = args.as_closure().sig();
233let inputs_and_output = closure_sig.inputs_and_output();
234let bound_vars = self.bound_vars(tcx);
235let br = ty::BoundRegion {
236 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
237 kind: ty::BoundRegionKind::ClosureEnv,
238 };
239let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
240let closure_ty = tcx.closure_env_ty(
241 Ty::new_closure(tcx, def_id, args),
242 args.as_closure().kind(),
243 env_region,
244 );
245246// The "inputs" of the closure in the
247 // signature appear as a tuple. The MIR side
248 // flattens this tuple.
249let (&output, tuplized_inputs) =
250 inputs_and_output.skip_binder().split_last().unwrap();
251assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
252let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
253bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]);
254 };
255256 ty::Binder::bind_with_vars(
257 tcx.mk_type_list_from_iter(
258 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
259 ),
260 bound_vars,
261 )
262 }
263264 DefiningTy::Coroutine(def_id, args) => {
265let resume_ty = args.as_coroutine().resume_ty();
266let output = args.as_coroutine().return_ty();
267let coroutine_ty = Ty::new_coroutine(tcx, def_id, args);
268let inputs_and_output = tcx.mk_type_list(&[coroutine_ty, resume_ty, output]);
269 ty::Binder::dummy(inputs_and_output)
270 }
271272// Construct the signature of the CoroutineClosure for the purposes of borrowck.
273 // This is pretty straightforward -- we:
274 // 1. first grab the `coroutine_closure_sig`,
275 // 2. compute the self type (`&`/`&mut`/no borrow),
276 // 3. flatten the tupled_input_tys,
277 // 4. construct the correct generator type to return with
278 // `CoroutineClosureSignature::to_coroutine_given_kind_and_upvars`.
279 // Then we wrap it all up into a list of inputs and output.
280DefiningTy::CoroutineClosure(def_id, args) => {
281let closure_sig = args.as_coroutine_closure().coroutine_closure_sig();
282let bound_vars = self.bound_vars(tcx);
283let br = ty::BoundRegion {
284 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
285 kind: ty::BoundRegionKind::ClosureEnv,
286 };
287let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
288let closure_kind = args.as_coroutine_closure().kind();
289290let closure_ty = tcx.closure_env_ty(
291 Ty::new_coroutine_closure(tcx, def_id, args),
292 closure_kind,
293 env_region,
294 );
295296let inputs = closure_sig.skip_binder().tupled_inputs_ty.tuple_fields();
297let output = closure_sig.skip_binder().to_coroutine_given_kind_and_upvars(
298 tcx,
299 args.as_coroutine_closure().parent_args(),
300 tcx.coroutine_for_closure(def_id),
301 closure_kind,
302 env_region,
303 args.as_coroutine_closure().tupled_upvars_ty(),
304 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
305 );
306307 ty::Binder::bind_with_vars(
308 tcx.mk_type_list_from_iter(
309 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
310 ),
311 bound_vars,
312 )
313 }
314315 DefiningTy::FnDef(def_id, _) => {
316let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
317let inputs_and_output = sig.inputs_and_output();
318319// C-variadic fns also have a `VaList` input that's not listed in the signature
320 // (as it's created inside the body itself, not passed in from outside).
321if tcx.fn_sig(def_id).skip_binder().c_variadic() {
322let va_list_did = tcx.require_lang_item(LangItem::VaList, tcx.def_span(def_id));
323324let bound_vars = self.bound_vars(tcx);
325let br = ty::BoundRegion {
326 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
327 kind: ty::BoundRegionKind::Anon,
328 };
329let region = ty::Region::new_bound(tcx, ty::INNERMOST, br);
330let va_list_ty =
331 tcx.type_of(va_list_did).instantiate(tcx, &[region.into()]).skip_norm_wip();
332333// The signature needs to follow the order [input_tys, va_list_ty, output_ty]
334let (output_ty, input_tys) =
335 inputs_and_output.skip_binder().split_last().unwrap();
336return ty::Binder::bind_with_vars(
337 tcx.mk_type_list_from_iter(
338 input_tys.iter().copied().chain([va_list_ty, *output_ty]),
339 ),
340 bound_vars,
341 );
342 }
343344 inputs_and_output
345 }
346347 DefiningTy::Const(def_id, _) => {
348// For a constant body, there are no inputs, and one
349 // "output" (the type of the constant).
350let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
351 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
352 }
353354 DefiningTy::InlineConst(_def_id, args) => {
355let ty = args.as_inline_const().ty();
356 ty::Binder::dummy(tcx.mk_type_list(&[ty]))
357 }
358359 DefiningTy::GlobalAsm(def_id) => ty::Binder::dummy(
360 tcx.mk_type_list(&[tcx.type_of(def_id).instantiate_identity().skip_norm_wip()]),
361 ),
362 }
363 }
364365/// Returns a list of all the upvar types for this MIR. If this is
366 /// not a closure or coroutine, there are no upvars, and hence it
367 /// will be an empty list. The order of types in this list will
368 /// match up with the upvar order in the HIR, typesystem, and MIR.
369pub(crate) fn upvar_tys(self) -> &'tcx ty::List<Ty<'tcx>> {
370match self {
371 DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(),
372 DefiningTy::CoroutineClosure(_, args) => args.as_coroutine_closure().upvar_tys(),
373 DefiningTy::Coroutine(_, args) => args.as_coroutine().upvar_tys(),
374 DefiningTy::FnDef(..)
375 | DefiningTy::Const(..)
376 | DefiningTy::InlineConst(..)
377 | DefiningTy::GlobalAsm(_) => ty::List::empty(),
378 }
379 }
380381/// Number of implicit inputs -- notably the "environment"
382 /// parameter for closures -- that appear in MIR but not in the
383 /// user's code.
384pub(crate) fn implicit_inputs(self) -> usize {
385match self {
386 DefiningTy::Closure(..)
387 | DefiningTy::CoroutineClosure(..)
388 | DefiningTy::Coroutine(..) => 1,
389 DefiningTy::FnDef(..)
390 | DefiningTy::Const(..)
391 | DefiningTy::InlineConst(..)
392 | DefiningTy::GlobalAsm(_) => 0,
393 }
394 }
395396pub(crate) fn is_fn_def(&self) -> bool {
397#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::FnDef(..) => true,
_ => false,
}matches!(*self, DefiningTy::FnDef(..))398 }
399400pub(crate) fn is_const(&self) -> bool {
401#[allow(non_exhaustive_omitted_patterns)] match *self {
DefiningTy::Const(..) | DefiningTy::InlineConst(..) => true,
_ => false,
}matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))402 }
403404pub(crate) fn def_id(&self) -> DefId {
405match *self {
406 DefiningTy::Closure(def_id, ..)
407 | DefiningTy::CoroutineClosure(def_id, ..)
408 | DefiningTy::Coroutine(def_id, ..)
409 | DefiningTy::FnDef(def_id, ..)
410 | DefiningTy::Const(def_id, ..)
411 | DefiningTy::InlineConst(def_id, ..)
412 | DefiningTy::GlobalAsm(def_id) => def_id,
413 }
414 }
415416/// Returns the args of the `DefiningTy`. These are equivalent to the identity
417 /// substs of the body, but replaced with region vids.
418pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> {
419match *self {
420 DefiningTy::Closure(_, args)
421 | DefiningTy::Coroutine(_, args)
422 | DefiningTy::CoroutineClosure(_, args)
423 | DefiningTy::FnDef(_, args)
424 | DefiningTy::Const(_, args)
425 | DefiningTy::InlineConst(_, args) => args,
426 DefiningTy::GlobalAsm(_) => ty::List::empty(),
427 }
428 }
429}
430431#[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)]
432#[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)
433struct UniversalRegionIndices<'tcx> {
434/// For those regions that may appear in the parameter environment
435 /// ('static and early-bound regions), we maintain a map from the
436 /// `ty::Region` to the internal `RegionVid` we are using. This is
437 /// used because trait matching and type-checking will feed us
438 /// region constraints that reference those regions and we need to
439 /// be able to map them to our internal `RegionVid`.
440 ///
441 /// This is similar to just using `GenericArgs`, except that it contains
442 /// an entry for `'static`, and also late bound parameters in scope.
443indices: FxIndexMap<ty::Region<'tcx>, RegionVid>,
444445/// The vid assigned to `'static`. Used only for diagnostics.
446pub fr_static: RegionVid,
447448/// Whether we've encountered an error region. If we have, cancel all
449 /// outlives errors, as they are likely bogus.
450pub encountered_re_error: Cell<Option<ErrorGuaranteed>>,
451}
452453#[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)]
454pub(crate) enum RegionClassification {
455/// A **global** region is one that can be named from
456 /// anywhere. There is only one, `'static`.
457Global,
458459/// An **external** region is only relevant for
460 /// closures, coroutines, and inline consts. In that
461 /// case, it refers to regions that are free in the type
462 /// -- basically, something bound in the surrounding context.
463 ///
464 /// Consider this example:
465 ///
466 /// ```ignore (pseudo-rust)
467 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
468 /// let closure = for<'x> |x: &'x u32| { .. };
469 /// // ^^^^^^^ pretend this were legal syntax
470 /// // for declaring a late-bound region in
471 /// // a closure signature
472 /// }
473 /// ```
474 ///
475 /// Here, the lifetimes `'a` and `'b` would be **external** to the
476 /// closure.
477 ///
478 /// If we are not analyzing a closure/coroutine/inline-const,
479 /// there are no external lifetimes.
480External,
481482/// A **local** lifetime is one about which we know the full set
483 /// of relevant constraints (that is, relationships to other named
484 /// regions). For a closure, this includes any region bound in
485 /// the closure's signature. For a fn item, this includes all
486 /// regions other than global ones.
487 ///
488 /// Continuing with the example from `External`, if we were
489 /// analyzing the closure, then `'x` would be local (and `'a` and
490 /// `'b` are external). If we are analyzing the function item
491 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
492 /// scope).
493Local,
494}
495496const FIRST_GLOBAL_INDEX: usize = 0;
497498impl<'tcx> UniversalRegions<'tcx> {
499/// Creates a new and fully initialized `UniversalRegions` that
500 /// contains indices for all the free regions found in the given
501 /// MIR -- that is, all the regions that appear in the function's
502 /// signature.
503pub(crate) fn new(infcx: &BorrowckInferCtxt<'tcx>, mir_def: LocalDefId) -> Self {
504UniversalRegionsBuilder { infcx, mir_def }.build()
505 }
506507/// Given a reference to a closure type, extracts all the values
508 /// from its free regions and returns a vector with them. This is
509 /// used when the closure's creator checks that the
510 /// `ClosureRegionRequirements` are met. The requirements from
511 /// `ClosureRegionRequirements` are expressed in terms of
512 /// `RegionVid` entries that map into the returned vector `V`: so
513 /// if the `ClosureRegionRequirements` contains something like
514 /// `'1: '2`, then the caller would impose the constraint that
515 /// `V[1]: V[2]`.
516pub(crate) fn closure_mapping(
517 tcx: TyCtxt<'tcx>,
518 closure_args: GenericArgsRef<'tcx>,
519 expected_num_vars: usize,
520 closure_def_id: LocalDefId,
521 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
522let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
523region_mapping.push(tcx.lifetimes.re_static);
524tcx.for_each_free_region(&closure_args, |fr| {
525region_mapping.push(fr);
526 });
527528for_each_late_bound_region_in_recursive_scope(tcx, tcx.local_parent(closure_def_id), |r| {
529region_mapping.push(r);
530 });
531532{
match (®ion_mapping.len(), &expected_num_vars) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("index vec had unexpected number of variables")));
}
}
}
};assert_eq!(
533 region_mapping.len(),
534 expected_num_vars,
535"index vec had unexpected number of variables"
536);
537538region_mapping539 }
540541/// Returns `true` if `r` is a member of this set of universal regions.
542pub(crate) fn is_universal_region(&self, r: RegionVid) -> bool {
543 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
544 }
545546/// Classifies `r` as a universal region, returning `None` if this
547 /// is not a member of this set of universal regions.
548pub(crate) fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
549let index = r.index();
550if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
551Some(RegionClassification::Global)
552 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
553Some(RegionClassification::External)
554 } else if (self.first_local_index..self.num_universals).contains(&index) {
555Some(RegionClassification::Local)
556 } else {
557None558 }
559 }
560561/// Returns an iterator over all the RegionVids corresponding to
562 /// universally quantified free regions.
563pub(crate) fn universal_regions_iter(&self) -> impl Iterator<Item = RegionVid> + 'static {
564 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize)
565 }
566567/// Returns `true` if `r` is classified as a local region.
568pub(crate) fn is_local_free_region(&self, r: RegionVid) -> bool {
569self.region_classification(r) == Some(RegionClassification::Local)
570 }
571572pub(crate) fn is_external_free_region(&self, r: RegionVid) -> bool {
573self.region_classification(r) == Some(RegionClassification::External)
574 }
575576/// Returns the number of universal regions created in any category.
577pub(crate) fn len(&self) -> usize {
578self.num_universals
579 }
580581/// Returns the number of global plus external universal regions.
582 /// For closures, these are the regions that appear free in the
583 /// closure type (versus those bound in the closure
584 /// signature). They are therefore the regions between which the
585 /// closure may impose constraints that its creator must verify.
586pub(crate) fn num_global_and_external_regions(&self) -> usize {
587self.first_local_index
588 }
589590/// Gets an iterator over all early bound regions starting with `'static`.
591pub(crate) fn named_universal_regions_iter(
592&self,
593 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> {
594self.indices.indices.iter().map(|(&r, &v)| (r, v))
595 }
596597/// See [UniversalRegionIndices::to_region_vid].
598pub(crate) fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
599self.indices.to_region_vid(r)
600 }
601602/// As part of the NLL unit tests, you can annotate a function with
603 /// `#[rustc_regions]`, and we will emit information about the region
604 /// inference context and -- in particular -- the external constraints
605 /// that this region imposes on others. The methods in this file
606 /// handle the part about dumping the inference context internal
607 /// state.
608pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diag<'_, ()>) {
609match self.defining_ty {
610 DefiningTy::Closure(def_id, args) => {
611let 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!(
612 args[tcx.generics_of(def_id).parent_count..]
613 .iter()
614 .map(|arg| arg.to_string())
615 .collect::<Vec<_>>()
616 );
617err.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!(
618"defining type: {} with closure args [\n {},\n]",
619 tcx.def_path_str_with_args(def_id, args),
620 v.join(",\n "),
621 ));
622623// FIXME: It'd be nice to print the late-bound regions
624 // here, but unfortunately these wind up stored into
625 // tests, and the resulting print-outs include def-ids
626 // and other things that are not stable across tests!
627 // So we just include the region-vid. Annoying.
628for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
629err.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)));
630 });
631 }
632 DefiningTy::CoroutineClosure(..) => {
633::core::panicking::panic("not implemented")unimplemented!()634 }
635 DefiningTy::Coroutine(def_id, args) => {
636let 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!(
637 args[tcx.generics_of(def_id).parent_count..]
638 .iter()
639 .map(|arg| arg.to_string())
640 .collect::<Vec<_>>()
641 );
642err.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!(
643"defining type: {} with coroutine args [\n {},\n]",
644 tcx.def_path_str_with_args(def_id, args),
645 v.join(",\n "),
646 ));
647648// FIXME: As above, we'd like to print out the region
649 // `r` but doing so is not stable across architectures
650 // and so forth.
651for_each_late_bound_region_in_recursive_scope(tcx, def_id.expect_local(), |r| {
652err.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)));
653 });
654 }
655 DefiningTy::FnDef(def_id, args) => {
656err.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),));
657 }
658 DefiningTy::Const(def_id, args) => {
659err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("defining constant type: {0}",
tcx.def_path_str_with_args(def_id, args)))
})format!(
660"defining constant type: {}",
661 tcx.def_path_str_with_args(def_id, args),
662 ));
663 }
664 DefiningTy::InlineConst(def_id, args) => {
665err.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!(
666"defining inline constant type: {}",
667 tcx.def_path_str_with_args(def_id, args),
668 ));
669 }
670 DefiningTy::GlobalAsm(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
671 }
672 }
673674pub(crate) fn implicit_region_bound(&self) -> RegionVid {
675self.fr_fn_body
676 }
677678pub(crate) fn encountered_re_error(&self) -> Option<ErrorGuaranteed> {
679self.indices.encountered_re_error.get()
680 }
681}
682683struct UniversalRegionsBuilder<'a, 'tcx> {
684 infcx: &'a BorrowckInferCtxt<'tcx>,
685 mir_def: LocalDefId,
686}
687688impl<'tcx> UniversalRegionsBuilder<'_, 'tcx> {
689fn build(self) -> UniversalRegions<'tcx> {
690{
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:690",
"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(690u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build(mir_def={0:?})",
self.mir_def) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build(mir_def={:?})", self.mir_def);
691692let param_env = self.infcx.param_env;
693{
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:693",
"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(693u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build: param_env={0:?}",
param_env) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: param_env={:?}", param_env);
694695{
match (&FIRST_GLOBAL_INDEX, &self.infcx.num_region_vars()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(FIRST_GLOBAL_INDEX, self.infcx.num_region_vars());
696697// Create the "global" region that is always free in all contexts: 'static.
698let fr_static = self699 .infcx
700 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
701 RegionCtxt::Free(kw::Static)
702 })
703 .as_var();
704705// We've now added all the global regions. The next ones we
706 // add will be external.
707let first_extern_index = self.infcx.num_region_vars();
708709let defining_ty = self.defining_ty();
710{
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:710",
"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(710u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build: defining_ty={0:?}",
defining_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: defining_ty={:?}", defining_ty);
711712let mut indices = self.compute_indices(fr_static, defining_ty);
713{
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:713",
"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(713u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build: indices={0:?}",
indices) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: indices={:?}", indices);
714715// If this is a 'root' body (not a closure/coroutine/inline const), then
716 // there are no extern regions, so the local regions start at the same
717 // position as the (empty) sub-list of extern regions
718let first_local_index = if !self.infcx.tcx.is_typeck_child(self.mir_def.to_def_id()) {
719first_extern_index720 } else {
721// If this is a closure, coroutine, or inline-const, then the late-bound regions from the enclosing
722 // function/closures are actually external regions to us. For example, here, 'a is not local
723 // to the closure c (although it is local to the fn foo). We need to add them as they could be
724 // explicitly named in this body:
725 //
726 // fn foo<'a>() {
727 // let c = || { let x: &'a u32 = ...; }
728 // }
729for_each_late_bound_region_in_recursive_scope(
730self.infcx.tcx,
731self.infcx.tcx.local_parent(self.mir_def),
732 |r| {
733{
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:733",
"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(733u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("r")
}> =
::tracing::__macro_support::FieldName::new("r");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&r)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?r);
734let region_vid = {
735let name = r.get_name_or_anon(self.infcx.tcx);
736self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
737 RegionCtxt::LateBound(name)
738 })
739 };
740741{
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:741",
"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(741u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_vid")
}> =
::tracing::__macro_support::FieldName::new("region_vid");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_vid)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?region_vid);
742indices.insert_late_bound_region(r, region_vid.as_var());
743 },
744 );
745746// Any regions created during the execution of `defining_ty` or during the above
747 // late-bound region replacement are all considered 'extern' regions
748self.infcx.num_region_vars()
749 };
750751// Converse of above, if this is a function/closure then the late-bound regions declared
752 // on its signature are local.
753 //
754 // We manually loop over `bound_inputs_and_output` instead of using
755 // `for_each_late_bound_region_in_item` as both closures and function
756 // definitions have implicit late bound regions. Closures have a `'env`
757 // regions while c-variadic function definitions have a `&VaList` argument.
758let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
759for (idx, bound_var) in bound_inputs_and_output.bound_vars().iter().enumerate() {
760if let ty::BoundVariableKind::Region(kind) = bound_var {
761let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
762let r = ty::Region::new_late_param(self.infcx.tcx, self.mir_def.to_def_id(), kind);
763let region_vid = {
764let name = r.get_name_or_anon(self.infcx.tcx);
765self.infcx.next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
766 RegionCtxt::LateBound(name)
767 })
768 };
769770{
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:770",
"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(770u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_vid")
}> =
::tracing::__macro_support::FieldName::new("region_vid");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_vid)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?region_vid);
771 indices.insert_late_bound_region(r, region_vid.as_var());
772 }
773 }
774let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
775self.mir_def,
776bound_inputs_and_output,
777&indices,
778 );
779780let (unnormalized_output_ty, unnormalized_input_tys) =
781inputs_and_output.split_last().unwrap();
782783let fr_fn_body = self784 .infcx
785 .next_nll_region_var(NllRegionVariableOrigin::FreeRegion, || {
786 RegionCtxt::Free(sym::fn_body)
787 })
788 .as_var();
789790let num_universals = self.infcx.num_region_vars();
791792{
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:792",
"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(792u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build: global regions = {0}..{1}",
FIRST_GLOBAL_INDEX, first_extern_index) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: global regions = {}..{}", FIRST_GLOBAL_INDEX, first_extern_index);
793{
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:793",
"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(793u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build: extern regions = {0}..{1}",
first_extern_index, first_local_index) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: extern regions = {}..{}", first_extern_index, first_local_index);
794{
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:794",
"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(794u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build: local regions = {0}..{1}",
first_local_index, num_universals) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("build: local regions = {}..{}", first_local_index, num_universals);
795796let (resume_ty, yield_ty) = match defining_ty {
797 DefiningTy::Coroutine(_, args) => {
798let tys = args.as_coroutine();
799 (Some(tys.resume_ty()), Some(tys.yield_ty()))
800 }
801_ => (None, None),
802 };
803804UniversalRegions {
805indices,
806fr_static,
807fr_fn_body,
808first_extern_index,
809first_local_index,
810num_universals,
811defining_ty,
812 unnormalized_output_ty: *unnormalized_output_ty,
813unnormalized_input_tys,
814yield_ty,
815resume_ty,
816 }
817 }
818819/// Returns the "defining type" of the current MIR; see `DefiningTy` for details.
820fn defining_ty(&self) -> DefiningTy<'tcx> {
821let defining_ty = DefiningTy::new(self.infcx.tcx, self.mir_def);
822let f = |args| {
823let fr = NllRegionVariableOrigin::FreeRegion;
824self.infcx.replace_free_regions_with_nll_infer_vars(fr, args)
825 };
826match defining_ty {
827 DefiningTy::Closure(def_id, args) => DefiningTy::Closure(def_id, f(args)),
828 DefiningTy::Coroutine(def_id, args) => DefiningTy::Coroutine(def_id, f(args)),
829 DefiningTy::CoroutineClosure(def_id, args) => {
830 DefiningTy::CoroutineClosure(def_id, f(args))
831 }
832 DefiningTy::FnDef(def_id, args) => DefiningTy::FnDef(def_id, f(args)),
833 DefiningTy::Const(def_id, args) => DefiningTy::Const(def_id, f(args)),
834 DefiningTy::InlineConst(def_id, args) => DefiningTy::InlineConst(def_id, f(args)),
835 DefiningTy::GlobalAsm(def_id) => DefiningTy::GlobalAsm(def_id),
836 }
837 }
838839/// Builds a hashmap that maps from the universal regions that are
840 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
841 /// `RegionVid`). The map returned by this function contains only
842 /// the early-bound regions.
843fn compute_indices(
844&self,
845 fr_static: RegionVid,
846 defining_ty: DefiningTy<'tcx>,
847 ) -> UniversalRegionIndices<'tcx> {
848let tcx = self.infcx.tcx;
849let typeck_root_def_id = tcx.typeck_root_def_id_local(self.mir_def);
850let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
851let renumbered_args = defining_ty.args();
852853let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
854// This relies on typeck roots being generics_of parents with their
855 // parameters at the start of nested bodies' generics.
856if !(renumbered_args.len() >= identity_args.len()) {
::core::panicking::panic("assertion failed: renumbered_args.len() >= identity_args.len()")
};assert!(renumbered_args.len() >= identity_args.len());
857let arg_mapping =
858 iter::zip(identity_args.regions(), renumbered_args.regions().map(|r| r.as_var()));
859860UniversalRegionIndices {
861 indices: global_mapping.chain(arg_mapping).collect(),
862fr_static,
863 encountered_re_error: Cell::new(None),
864 }
865 }
866867fn compute_inputs_and_output(
868&self,
869 indices: &UniversalRegionIndices<'tcx>,
870 defining_ty: DefiningTy<'tcx>,
871 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
872let tcx = self.infcx.tcx;
873let inputs_and_output = defining_ty.inputs_and_output(tcx);
874let inputs_and_output = indices.fold_to_region_vids(tcx, inputs_and_output);
875876// FIXME(#129952): We probably want a more principled approach here.
877if let Err(e) = inputs_and_output.error_reported() {
878self.infcx.set_tainted_by_errors(e);
879 }
880881inputs_and_output882 }
883}
884885impl<'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(887u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("value")
}> =
::tracing::__macro_support::FieldName::new("value");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: T = loop {};
return __tracing_attr_fake_return;
}
{
fold_regions(self.infcx.tcx, value,
|region, _depth|
{
let name = region.get_name_or_anon(self.infcx.tcx);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:898",
"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(898u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region")
}> =
::tracing::__macro_support::FieldName::new("region");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("name")
}> =
::tracing::__macro_support::FieldName::new("name");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&name)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
self.next_nll_region_var(origin, || RegionCtxt::Free(name))
})
}
}
}
}
fn replace_bound_regions_with_nll_infer_vars<T>(&self,
all_outlive_scope: LocalDefId, value: ty::Binder<'tcx, T>,
indices: &UniversalRegionIndices<'tcx>) -> T where
T: TypeFoldable<TyCtxt<'tcx>> {
{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("replace_bound_regions_with_nll_infer_vars",
"rustc_borrowck::universal_regions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
::tracing_core::__macro_support::Option::Some(904u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("all_outlive_scope")
}> =
::tracing::__macro_support::FieldName::new("all_outlive_scope");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("value")
}> =
::tracing::__macro_support::FieldName::new("value");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&all_outlive_scope)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: T = loop {};
return __tracing_attr_fake_return;
}
{
let (value, _map) =
self.tcx.instantiate_bound_regions(value,
|br|
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:915",
"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(915u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("br")
}> =
::tracing::__macro_support::FieldName::new("br");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&br)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let kind =
ty::LateParamRegionKind::from_bound(br.var, br.kind);
let liberated_region =
ty::Region::new_late_param(self.tcx,
all_outlive_scope.to_def_id(), kind);
ty::Region::new_var(self.tcx,
indices.to_region_vid(liberated_region))
});
value
}
}
}
}
}#[extension(trait InferCtxtExt<'tcx>)]886impl<'tcx> BorrowckInferCtxt<'tcx> {
887#[instrument(skip(self), level = "debug")]
888fn replace_free_regions_with_nll_infer_vars<T>(
889&self,
890 origin: NllRegionVariableOrigin<'tcx>,
891 value: T,
892 ) -> T
893where
894T: TypeFoldable<TyCtxt<'tcx>>,
895 {
896 fold_regions(self.infcx.tcx, value, |region, _depth| {
897let name = region.get_name_or_anon(self.infcx.tcx);
898debug!(?region, ?name);
899900self.next_nll_region_var(origin, || RegionCtxt::Free(name))
901 })
902 }
903904#[instrument(level = "debug", skip(self, indices))]
905fn replace_bound_regions_with_nll_infer_vars<T>(
906&self,
907 all_outlive_scope: LocalDefId,
908 value: ty::Binder<'tcx, T>,
909 indices: &UniversalRegionIndices<'tcx>,
910 ) -> T
911where
912T: TypeFoldable<TyCtxt<'tcx>>,
913 {
914let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
915debug!(?br);
916let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
917let liberated_region =
918 ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
919 ty::Region::new_var(self.tcx, indices.to_region_vid(liberated_region))
920 });
921 value
922 }
923}
924925impl<'tcx> UniversalRegionIndices<'tcx> {
926/// Initially, the `UniversalRegionIndices` map contains only the
927 /// early-bound regions in scope. Once that is all setup, we come
928 /// in later and instantiate the late-bound regions, and then we
929 /// insert the `ReLateParam` version of those into the map as
930 /// well. These are used for error reporting.
931fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
932{
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:932",
"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(932u32),
::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("insert_late_bound_region({0:?}, {1:?})",
r, vid) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("insert_late_bound_region({:?}, {:?})", r, vid);
933{
match (&self.indices.insert(r, vid), &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.indices.insert(r, vid), None);
934 }
935936/// Converts `r` into a local inference variable: `r` can either
937 /// be a `ReVar` (i.e., already a reference to an inference
938 /// variable) or it can be `'static` or some early-bound
939 /// region. This is useful when taking the results from
940 /// type-checking and trait-matching, which may sometimes
941 /// reference those regions from the `ParamEnv`. It is also used
942 /// during initialization. Relies on the `indices` map having been
943 /// fully initialized.
944 ///
945 /// Panics if `r` is not a registered universal region, most notably
946 /// if it is a placeholder. Handling placeholders requires access to the
947 /// `MirTypeckRegionConstraints`.
948fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
949match r.kind() {
950 ty::ReVar(..) => r.as_var(),
951 ty::ReError(guar) => {
952self.encountered_re_error.set(Some(guar));
953// We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
954 // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
955 // errors are being emitted and 2) it leaves the happy path unaffected.
956self.fr_static
957 }
958_ => *self959 .indices
960 .get(&r)
961 .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)),
962 }
963 }
964965/// Replaces all free regions in `value` with region vids, as
966 /// returned by `to_region_vid`.
967fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
968where
969T: TypeFoldable<TyCtxt<'tcx>>,
970 {
971fold_regions(tcx, value, |region, _| ty::Region::new_var(tcx, self.to_region_vid(region)))
972 }
973}
974975/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
976/// parents, up to the typeck root, and invokes `f` with the liberated form
977/// of each one.
978fn for_each_late_bound_region_in_recursive_scope<'tcx>(
979 tcx: TyCtxt<'tcx>,
980mut mir_def_id: LocalDefId,
981mut f: impl FnMut(ty::Region<'tcx>),
982) {
983// Walk up the tree, collecting late-bound regions until we hit the typeck root
984loop {
985for_each_late_bound_region_in_item(tcx, mir_def_id, &mut f);
986987if tcx.is_typeck_child(mir_def_id.to_def_id()) {
988mir_def_id = tcx.local_parent(mir_def_id);
989 } else {
990break;
991 }
992 }
993}
994995/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
996/// parents, up to the typeck root, and invokes `f` with the liberated form
997/// of each one.
998fn for_each_late_bound_region_in_item<'tcx>(
999 tcx: TyCtxt<'tcx>,
1000 mir_def_id: LocalDefId,
1001mut f: impl FnMut(ty::Region<'tcx>),
1002) {
1003let bound_vars = match tcx.def_kind(mir_def_id) {
1004 DefKind::Fn | DefKind::AssocFn => {
1005tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id))
1006 }
1007// We extract the bound vars from the deduced closure signature, since we may have
1008 // only deduced that a param in the closure signature is late-bound from a constraint
1009 // that we discover during typeck.
1010DefKind::Closure => {
1011let ty = tcx.type_of(mir_def_id).instantiate_identity().skip_norm_wip();
1012match *ty.kind() {
1013 ty::Closure(_, args) => args.as_closure().sig().bound_vars(),
1014 ty::CoroutineClosure(_, args) => {
1015args.as_coroutine_closure().coroutine_closure_sig().bound_vars()
1016 }
1017 ty::Coroutine(_, _) | ty::Error(_) => return,
1018_ => {
::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}"),
1019 }
1020 }
1021_ => return,
1022 };
10231024for (idx, bound_var) in bound_vars.iter().enumerate() {
1025if let ty::BoundVariableKind::Region(kind) = bound_var {
1026let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
1027let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind);
1028 f(liberated_region);
1029 }
1030 }
1031}