1 //! Code to extract the universally quantified regions declared on a
2 //! function and the relationships between them. For example:
5 //! fn foo<'a, 'b, 'c: 'b>() { }
8 //! here we would return a map assigning each of `{'a, 'b, 'c}`
9 //! to an index, as well as the `FreeRegionMap` which can compute
10 //! relationships between them.
12 //! The code in this file doesn't *do anything* with those results; it
13 //! just returns them for other code to use.
16 use rustc_data_structures
::fx
::FxHashMap
;
17 use rustc_errors
::Diagnostic
;
19 use rustc_hir
::def_id
::{DefId, LocalDefId}
;
20 use rustc_hir
::lang_items
::LangItem
;
21 use rustc_hir
::BodyOwnerKind
;
22 use rustc_index
::vec
::{Idx, IndexVec}
;
23 use rustc_infer
::infer
::NllRegionVariableOrigin
;
24 use rustc_middle
::ty
::fold
::TypeFoldable
;
25 use rustc_middle
::ty
::{
26 self, DefIdTree
, InlineConstSubsts
, InlineConstSubstsParts
, RegionVid
, Ty
, TyCtxt
,
28 use rustc_middle
::ty
::{InternalSubsts, SubstsRef}
;
29 use rustc_span
::Symbol
;
32 use crate::nll
::ToRegionVid
;
33 use crate::renumber
::{BoundRegionInfo, RegionCtxt}
;
34 use crate::BorrowckInferCtxt
;
37 pub struct UniversalRegions
<'tcx
> {
38 indices
: UniversalRegionIndices
<'tcx
>,
40 /// The vid assigned to `'static`
41 pub fr_static
: RegionVid
,
43 /// A special region vid created to represent the current MIR fn
44 /// body. It will outlive the entire CFG but it will not outlive
45 /// any other universal regions.
46 pub fr_fn_body
: RegionVid
,
48 /// We create region variables such that they are ordered by their
49 /// `RegionClassification`. The first block are globals, then
50 /// externals, then locals. So, things from:
51 /// - `FIRST_GLOBAL_INDEX..first_extern_index` are global,
52 /// - `first_extern_index..first_local_index` are external,
53 /// - `first_local_index..num_universals` are local.
54 first_extern_index
: usize,
56 /// See `first_extern_index`.
57 first_local_index
: usize,
59 /// The total number of universal region variables instantiated.
60 num_universals
: usize,
62 /// The "defining" type for this function, with all universal
63 /// regions instantiated. For a closure or generator, this is the
64 /// closure type, but for a top-level function it's the `FnDef`.
65 pub defining_ty
: DefiningTy
<'tcx
>,
67 /// The return type of this function, with all regions replaced by
68 /// their universal `RegionVid` equivalents.
70 /// N.B., associated types in this type have not been normalized,
71 /// as the name suggests. =)
72 pub unnormalized_output_ty
: Ty
<'tcx
>,
74 /// The fully liberated input types of this function, with all
75 /// regions replaced by their universal `RegionVid` equivalents.
77 /// N.B., associated types in these types have not been normalized,
78 /// as the name suggests. =)
79 pub unnormalized_input_tys
: &'tcx
[Ty
<'tcx
>],
81 pub yield_ty
: Option
<Ty
<'tcx
>>,
84 /// The "defining type" for this MIR. The key feature of the "defining
85 /// type" is that it contains the information needed to derive all the
86 /// universal regions that are in scope as well as the types of the
87 /// inputs/output from the MIR. In general, early-bound universal
88 /// regions appear free in the defining type and late-bound regions
89 /// appear bound in the signature.
90 #[derive(Copy, Clone, Debug)]
91 pub enum DefiningTy
<'tcx
> {
92 /// The MIR is a closure. The signature is found via
93 /// `ClosureSubsts::closure_sig_ty`.
94 Closure(DefId
, SubstsRef
<'tcx
>),
96 /// The MIR is a generator. The signature is that generators take
97 /// no parameters and return the result of
98 /// `ClosureSubsts::generator_return_ty`.
99 Generator(DefId
, SubstsRef
<'tcx
>, hir
::Movability
),
101 /// The MIR is a fn item with the given `DefId` and substs. The signature
102 /// of the function can be bound then with the `fn_sig` query.
103 FnDef(DefId
, SubstsRef
<'tcx
>),
105 /// The MIR represents some form of constant. The signature then
106 /// is that it has no inputs and a single return value, which is
107 /// the value of the constant.
108 Const(DefId
, SubstsRef
<'tcx
>),
110 /// The MIR represents an inline const. The signature has no inputs and a
111 /// single return value found via `InlineConstSubsts::ty`.
112 InlineConst(DefId
, SubstsRef
<'tcx
>),
115 impl<'tcx
> DefiningTy
<'tcx
> {
116 /// Returns a list of all the upvar types for this MIR. If this is
117 /// not a closure or generator, there are no upvars, and hence it
118 /// will be an empty list. The order of types in this list will
119 /// match up with the upvar order in the HIR, typesystem, and MIR.
120 pub fn upvar_tys(self) -> impl Iterator
<Item
= Ty
<'tcx
>> + 'tcx
{
122 DefiningTy
::Closure(_
, substs
) => Either
::Left(substs
.as_closure().upvar_tys()),
123 DefiningTy
::Generator(_
, substs
, _
) => {
124 Either
::Right(Either
::Left(substs
.as_generator().upvar_tys()))
126 DefiningTy
::FnDef(..) | DefiningTy
::Const(..) | DefiningTy
::InlineConst(..) => {
127 Either
::Right(Either
::Right(iter
::empty()))
132 /// Number of implicit inputs -- notably the "environment"
133 /// parameter for closures -- that appear in MIR but not in the
135 pub fn implicit_inputs(self) -> usize {
137 DefiningTy
::Closure(..) | DefiningTy
::Generator(..) => 1,
138 DefiningTy
::FnDef(..) | DefiningTy
::Const(..) | DefiningTy
::InlineConst(..) => 0,
142 pub fn is_fn_def(&self) -> bool
{
143 matches
!(*self, DefiningTy
::FnDef(..))
146 pub fn is_const(&self) -> bool
{
147 matches
!(*self, DefiningTy
::Const(..) | DefiningTy
::InlineConst(..))
150 pub fn def_id(&self) -> DefId
{
152 DefiningTy
::Closure(def_id
, ..)
153 | DefiningTy
::Generator(def_id
, ..)
154 | DefiningTy
::FnDef(def_id
, ..)
155 | DefiningTy
::Const(def_id
, ..)
156 | DefiningTy
::InlineConst(def_id
, ..) => def_id
,
162 struct UniversalRegionIndices
<'tcx
> {
163 /// For those regions that may appear in the parameter environment
164 /// ('static and early-bound regions), we maintain a map from the
165 /// `ty::Region` to the internal `RegionVid` we are using. This is
166 /// used because trait matching and type-checking will feed us
167 /// region constraints that reference those regions and we need to
168 /// be able to map them to our internal `RegionVid`. This is
169 /// basically equivalent to an `InternalSubsts`, except that it also
170 /// contains an entry for `ReStatic` -- it might be nice to just
171 /// use a substs, and then handle `ReStatic` another way.
172 indices
: FxHashMap
<ty
::Region
<'tcx
>, RegionVid
>,
174 /// The vid assigned to `'static`. Used only for diagnostics.
175 pub fr_static
: RegionVid
,
178 #[derive(Debug, PartialEq)]
179 pub enum RegionClassification
{
180 /// A **global** region is one that can be named from
181 /// anywhere. There is only one, `'static`.
184 /// An **external** region is only relevant for
185 /// closures, generators, and inline consts. In that
186 /// case, it refers to regions that are free in the type
187 /// -- basically, something bound in the surrounding context.
189 /// Consider this example:
191 /// ```ignore (pseudo-rust)
192 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
193 /// let closure = for<'x> |x: &'x u32| { .. };
194 /// // ^^^^^^^ pretend this were legal syntax
195 /// // for declaring a late-bound region in
196 /// // a closure signature
200 /// Here, the lifetimes `'a` and `'b` would be **external** to the
203 /// If we are not analyzing a closure/generator/inline-const,
204 /// there are no external lifetimes.
207 /// A **local** lifetime is one about which we know the full set
208 /// of relevant constraints (that is, relationships to other named
209 /// regions). For a closure, this includes any region bound in
210 /// the closure's signature. For a fn item, this includes all
211 /// regions other than global ones.
213 /// Continuing with the example from `External`, if we were
214 /// analyzing the closure, then `'x` would be local (and `'a` and
215 /// `'b` are external). If we are analyzing the function item
216 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
221 const FIRST_GLOBAL_INDEX
: usize = 0;
223 impl<'tcx
> UniversalRegions
<'tcx
> {
224 /// Creates a new and fully initialized `UniversalRegions` that
225 /// contains indices for all the free regions found in the given
226 /// MIR -- that is, all the regions that appear in the function's
227 /// signature. This will also compute the relationships that are
228 /// known between those regions.
230 infcx
: &BorrowckInferCtxt
<'_
, 'tcx
>,
231 mir_def
: ty
::WithOptConstParam
<LocalDefId
>,
232 param_env
: ty
::ParamEnv
<'tcx
>,
234 UniversalRegionsBuilder { infcx, mir_def, param_env }
.build()
237 /// Given a reference to a closure type, extracts all the values
238 /// from its free regions and returns a vector with them. This is
239 /// used when the closure's creator checks that the
240 /// `ClosureRegionRequirements` are met. The requirements from
241 /// `ClosureRegionRequirements` are expressed in terms of
242 /// `RegionVid` entries that map into the returned vector `V`: so
243 /// if the `ClosureRegionRequirements` contains something like
244 /// `'1: '2`, then the caller would impose the constraint that
246 pub fn closure_mapping(
248 closure_substs
: SubstsRef
<'tcx
>,
249 expected_num_vars
: usize,
250 closure_def_id
: LocalDefId
,
251 ) -> IndexVec
<RegionVid
, ty
::Region
<'tcx
>> {
252 let mut region_mapping
= IndexVec
::with_capacity(expected_num_vars
);
253 region_mapping
.push(tcx
.lifetimes
.re_static
);
254 tcx
.for_each_free_region(&closure_substs
, |fr
| {
255 region_mapping
.push(fr
);
258 for_each_late_bound_region_in_recursive_scope(tcx
, tcx
.local_parent(closure_def_id
), |r
| {
259 region_mapping
.push(r
);
263 region_mapping
.len(),
265 "index vec had unexpected number of variables"
271 /// Returns `true` if `r` is a member of this set of universal regions.
272 pub fn is_universal_region(&self, r
: RegionVid
) -> bool
{
273 (FIRST_GLOBAL_INDEX
..self.num_universals
).contains(&r
.index())
276 /// Classifies `r` as a universal region, returning `None` if this
277 /// is not a member of this set of universal regions.
278 pub fn region_classification(&self, r
: RegionVid
) -> Option
<RegionClassification
> {
279 let index
= r
.index();
280 if (FIRST_GLOBAL_INDEX
..self.first_extern_index
).contains(&index
) {
281 Some(RegionClassification
::Global
)
282 } else if (self.first_extern_index
..self.first_local_index
).contains(&index
) {
283 Some(RegionClassification
::External
)
284 } else if (self.first_local_index
..self.num_universals
).contains(&index
) {
285 Some(RegionClassification
::Local
)
291 /// Returns an iterator over all the RegionVids corresponding to
292 /// universally quantified free regions.
293 pub fn universal_regions(&self) -> impl Iterator
<Item
= RegionVid
> {
294 (FIRST_GLOBAL_INDEX
..self.num_universals
).map(RegionVid
::new
)
297 /// Returns `true` if `r` is classified as an local region.
298 pub fn is_local_free_region(&self, r
: RegionVid
) -> bool
{
299 self.region_classification(r
) == Some(RegionClassification
::Local
)
302 /// Returns the number of universal regions created in any category.
303 pub fn len(&self) -> usize {
307 /// Returns the number of global plus external universal regions.
308 /// For closures, these are the regions that appear free in the
309 /// closure type (versus those bound in the closure
310 /// signature). They are therefore the regions between which the
311 /// closure may impose constraints that its creator must verify.
312 pub fn num_global_and_external_regions(&self) -> usize {
313 self.first_local_index
316 /// Gets an iterator over all the early-bound regions that have names.
317 pub fn named_universal_regions
<'s
>(
319 ) -> impl Iterator
<Item
= (ty
::Region
<'tcx
>, ty
::RegionVid
)> + 's
{
320 self.indices
.indices
.iter().map(|(&r
, &v
)| (r
, v
))
323 /// See `UniversalRegionIndices::to_region_vid`.
324 pub fn to_region_vid(&self, r
: ty
::Region
<'tcx
>) -> RegionVid
{
325 self.indices
.to_region_vid(r
)
328 /// As part of the NLL unit tests, you can annotate a function with
329 /// `#[rustc_regions]`, and we will emit information about the region
330 /// inference context and -- in particular -- the external constraints
331 /// that this region imposes on others. The methods in this file
332 /// handle the part about dumping the inference context internal
334 pub(crate) fn annotate(&self, tcx
: TyCtxt
<'tcx
>, err
: &mut Diagnostic
) {
335 match self.defining_ty
{
336 DefiningTy
::Closure(def_id
, substs
) => {
338 "defining type: {} with closure substs {:#?}",
339 tcx
.def_path_str_with_substs(def_id
, substs
),
340 &substs
[tcx
.generics_of(def_id
).parent_count
..],
343 // FIXME: It'd be nice to print the late-bound regions
344 // here, but unfortunately these wind up stored into
345 // tests, and the resulting print-outs include def-ids
346 // and other things that are not stable across tests!
347 // So we just include the region-vid. Annoying.
348 for_each_late_bound_region_in_recursive_scope(tcx
, def_id
.expect_local(), |r
| {
349 err
.note(&format
!("late-bound region is {:?}", self.to_region_vid(r
)));
352 DefiningTy
::Generator(def_id
, substs
, _
) => {
354 "defining type: {} with generator substs {:#?}",
355 tcx
.def_path_str_with_substs(def_id
, substs
),
356 &substs
[tcx
.generics_of(def_id
).parent_count
..],
359 // FIXME: As above, we'd like to print out the region
360 // `r` but doing so is not stable across architectures
362 for_each_late_bound_region_in_recursive_scope(tcx
, def_id
.expect_local(), |r
| {
363 err
.note(&format
!("late-bound region is {:?}", self.to_region_vid(r
)));
366 DefiningTy
::FnDef(def_id
, substs
) => {
369 tcx
.def_path_str_with_substs(def_id
, substs
),
372 DefiningTy
::Const(def_id
, substs
) => {
374 "defining constant type: {}",
375 tcx
.def_path_str_with_substs(def_id
, substs
),
378 DefiningTy
::InlineConst(def_id
, substs
) => {
380 "defining inline constant type: {}",
381 tcx
.def_path_str_with_substs(def_id
, substs
),
388 struct UniversalRegionsBuilder
<'cx
, 'tcx
> {
389 infcx
: &'cx BorrowckInferCtxt
<'cx
, 'tcx
>,
390 mir_def
: ty
::WithOptConstParam
<LocalDefId
>,
391 param_env
: ty
::ParamEnv
<'tcx
>,
394 const FR
: NllRegionVariableOrigin
= NllRegionVariableOrigin
::FreeRegion
;
396 impl<'cx
, 'tcx
> UniversalRegionsBuilder
<'cx
, 'tcx
> {
397 fn build(self) -> UniversalRegions
<'tcx
> {
398 debug
!("build(mir_def={:?})", self.mir_def
);
400 let param_env
= self.param_env
;
401 debug
!("build: param_env={:?}", param_env
);
403 assert_eq
!(FIRST_GLOBAL_INDEX
, self.infcx
.num_region_vars());
405 // Create the "global" region that is always free in all contexts: 'static.
408 .next_nll_region_var(FR
, || RegionCtxt
::Free(Symbol
::intern("static")))
411 // We've now added all the global regions. The next ones we
412 // add will be external.
413 let first_extern_index
= self.infcx
.num_region_vars();
415 let defining_ty
= self.defining_ty();
416 debug
!("build: defining_ty={:?}", defining_ty
);
418 let mut indices
= self.compute_indices(fr_static
, defining_ty
);
419 debug
!("build: indices={:?}", indices
);
421 let typeck_root_def_id
= self.infcx
.tcx
.typeck_root_def_id(self.mir_def
.did
.to_def_id());
423 // If this is a 'root' body (not a closure/generator/inline const), then
424 // there are no extern regions, so the local regions start at the same
425 // position as the (empty) sub-list of extern regions
426 let first_local_index
= if self.mir_def
.did
.to_def_id() == typeck_root_def_id
{
429 // If this is a closure, generator, or inline-const, then the late-bound regions from the enclosing
430 // function/closures are actually external regions to us. For example, here, 'a is not local
431 // to the closure c (although it is local to the fn foo):
433 // let c = || { let x: &'a u32 = ...; }
435 for_each_late_bound_region_in_recursive_scope(
437 self.infcx
.tcx
.local_parent(self.mir_def
.did
),
440 if !indices
.indices
.contains_key(&r
) {
442 let name
= match r
.get_name() {
444 _
=> Symbol
::intern("anon"),
447 self.infcx
.next_nll_region_var(FR
, || {
448 RegionCtxt
::LateBound(BoundRegionInfo
::Name(name
))
453 indices
.insert_late_bound_region(r
, region_vid
.to_region_vid());
458 // Any regions created during the execution of `defining_ty` or during the above
459 // late-bound region replacement are all considered 'extern' regions
460 self.infcx
.num_region_vars()
463 // "Liberate" the late-bound regions. These correspond to
464 // "local" free regions.
466 let bound_inputs_and_output
= self.compute_inputs_and_output(&indices
, defining_ty
);
468 let inputs_and_output
= self.infcx
.replace_bound_regions_with_nll_infer_vars(
471 bound_inputs_and_output
,
474 // Converse of above, if this is a function/closure then the late-bound regions declared on its
475 // signature are local.
476 for_each_late_bound_region_in_item(self.infcx
.tcx
, self.mir_def
.did
, |r
| {
478 if !indices
.indices
.contains_key(&r
) {
480 let name
= match r
.get_name() {
482 _
=> Symbol
::intern("anon"),
485 self.infcx
.next_nll_region_var(FR
, || {
486 RegionCtxt
::LateBound(BoundRegionInfo
::Name(name
))
491 indices
.insert_late_bound_region(r
, region_vid
.to_region_vid());
495 let (unnormalized_output_ty
, mut unnormalized_input_tys
) =
496 inputs_and_output
.split_last().unwrap();
498 // C-variadic fns also have a `VaList` input that's not listed in the signature
499 // (as it's created inside the body itself, not passed in from outside).
500 if let DefiningTy
::FnDef(def_id
, _
) = defining_ty
{
501 if self.infcx
.tcx
.fn_sig(def_id
).skip_binder().c_variadic() {
502 let va_list_did
= self.infcx
.tcx
.require_lang_item(
504 Some(self.infcx
.tcx
.def_span(self.mir_def
.did
)),
509 .next_nll_region_var(FR
, || RegionCtxt
::Free(Symbol
::intern("c-variadic")))
512 let region
= self.infcx
.tcx
.mk_re_var(reg_vid
);
514 self.infcx
.tcx
.type_of(va_list_did
).subst(self.infcx
.tcx
, &[region
.into()]);
516 unnormalized_input_tys
= self.infcx
.tcx
.mk_type_list_from_iter(
517 unnormalized_input_tys
.iter().copied().chain(iter
::once(va_list_ty
)),
522 let fr_fn_body
= self
524 .next_nll_region_var(FR
, || RegionCtxt
::Free(Symbol
::intern("fn_body")))
527 let num_universals
= self.infcx
.num_region_vars();
529 debug
!("build: global regions = {}..{}", FIRST_GLOBAL_INDEX
, first_extern_index
);
530 debug
!("build: extern regions = {}..{}", first_extern_index
, first_local_index
);
531 debug
!("build: local regions = {}..{}", first_local_index
, num_universals
);
533 let yield_ty
= match defining_ty
{
534 DefiningTy
::Generator(_
, substs
, _
) => Some(substs
.as_generator().yield_ty()),
546 unnormalized_output_ty
: *unnormalized_output_ty
,
547 unnormalized_input_tys
,
552 /// Returns the "defining type" of the current MIR;
553 /// see `DefiningTy` for details.
554 fn defining_ty(&self) -> DefiningTy
<'tcx
> {
555 let tcx
= self.infcx
.tcx
;
556 let typeck_root_def_id
= tcx
.typeck_root_def_id(self.mir_def
.did
.to_def_id());
558 match tcx
.hir().body_owner_kind(self.mir_def
.did
) {
559 BodyOwnerKind
::Closure
| BodyOwnerKind
::Fn
=> {
560 let defining_ty
= tcx
.type_of(self.mir_def
.def_id_for_type_of()).subst_identity();
562 debug
!("defining_ty (pre-replacement): {:?}", defining_ty
);
565 self.infcx
.replace_free_regions_with_nll_infer_vars(FR
, defining_ty
);
567 match *defining_ty
.kind() {
568 ty
::Closure(def_id
, substs
) => DefiningTy
::Closure(def_id
, substs
),
569 ty
::Generator(def_id
, substs
, movability
) => {
570 DefiningTy
::Generator(def_id
, substs
, movability
)
572 ty
::FnDef(def_id
, substs
) => DefiningTy
::FnDef(def_id
, substs
),
574 tcx
.def_span(self.mir_def
.did
),
575 "expected defining type for `{:?}`: `{:?}`",
582 BodyOwnerKind
::Const
| BodyOwnerKind
::Static(..) => {
583 let identity_substs
= InternalSubsts
::identity_for_item(tcx
, typeck_root_def_id
);
584 if self.mir_def
.did
.to_def_id() == typeck_root_def_id
{
586 self.infcx
.replace_free_regions_with_nll_infer_vars(FR
, identity_substs
);
587 DefiningTy
::Const(self.mir_def
.did
.to_def_id(), substs
)
589 // FIXME this line creates a dependency between borrowck and typeck.
591 // This is required for `AscribeUserType` canonical query, which will call
592 // `type_of(inline_const_def_id)`. That `type_of` would inject erased lifetimes
593 // into borrowck, which is ICE #78174.
595 // As a workaround, inline consts have an additional generic param (`ty`
596 // below), so that `type_of(inline_const_def_id).substs(substs)` uses the
597 // proper type with NLL infer vars.
599 .typeck(self.mir_def
.did
)
600 .node_type(tcx
.local_def_id_to_hir_id(self.mir_def
.did
));
601 let substs
= InlineConstSubsts
::new(
603 InlineConstSubstsParts { parent_substs: identity_substs, ty }
,
606 let substs
= self.infcx
.replace_free_regions_with_nll_infer_vars(FR
, substs
);
607 DefiningTy
::InlineConst(self.mir_def
.did
.to_def_id(), substs
)
613 /// Builds a hashmap that maps from the universal regions that are
614 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
615 /// `RegionVid`). The map returned by this function contains only
616 /// the early-bound regions.
619 fr_static
: RegionVid
,
620 defining_ty
: DefiningTy
<'tcx
>,
621 ) -> UniversalRegionIndices
<'tcx
> {
622 let tcx
= self.infcx
.tcx
;
623 let typeck_root_def_id
= tcx
.typeck_root_def_id(self.mir_def
.did
.to_def_id());
624 let identity_substs
= InternalSubsts
::identity_for_item(tcx
, typeck_root_def_id
);
625 let fr_substs
= match defining_ty
{
626 DefiningTy
::Closure(_
, substs
)
627 | DefiningTy
::Generator(_
, substs
, _
)
628 | DefiningTy
::InlineConst(_
, substs
) => {
629 // In the case of closures, we rely on the fact that
630 // the first N elements in the ClosureSubsts are
631 // inherited from the `typeck_root_def_id`.
632 // Therefore, when we zip together (below) with
633 // `identity_substs`, we will get only those regions
634 // that correspond to early-bound regions declared on
635 // the `typeck_root_def_id`.
636 assert
!(substs
.len() >= identity_substs
.len());
637 assert_eq
!(substs
.regions().count(), identity_substs
.regions().count());
641 DefiningTy
::FnDef(_
, substs
) | DefiningTy
::Const(_
, substs
) => substs
,
644 let global_mapping
= iter
::once((tcx
.lifetimes
.re_static
, fr_static
));
646 iter
::zip(identity_substs
.regions(), fr_substs
.regions().map(|r
| r
.to_region_vid()));
648 UniversalRegionIndices { indices: global_mapping.chain(subst_mapping).collect(), fr_static }
651 fn compute_inputs_and_output(
653 indices
: &UniversalRegionIndices
<'tcx
>,
654 defining_ty
: DefiningTy
<'tcx
>,
655 ) -> ty
::Binder
<'tcx
, &'tcx ty
::List
<Ty
<'tcx
>>> {
656 let tcx
= self.infcx
.tcx
;
658 DefiningTy
::Closure(def_id
, substs
) => {
659 assert_eq
!(self.mir_def
.did
.to_def_id(), def_id
);
660 let closure_sig
= substs
.as_closure().sig();
661 let inputs_and_output
= closure_sig
.inputs_and_output();
662 let bound_vars
= tcx
.mk_bound_variable_kinds_from_iter(
666 .chain(iter
::once(ty
::BoundVariableKind
::Region(ty
::BrEnv
))),
668 let br
= ty
::BoundRegion
{
669 var
: ty
::BoundVar
::from_usize(bound_vars
.len() - 1),
672 let env_region
= tcx
.mk_re_late_bound(ty
::INNERMOST
, br
);
673 let closure_ty
= tcx
.closure_env_ty(def_id
, substs
, env_region
).unwrap();
675 // The "inputs" of the closure in the
676 // signature appear as a tuple. The MIR side
677 // flattens this tuple.
678 let (&output
, tuplized_inputs
) =
679 inputs_and_output
.skip_binder().split_last().unwrap();
680 assert_eq
!(tuplized_inputs
.len(), 1, "multiple closure inputs");
681 let &ty
::Tuple(inputs
) = tuplized_inputs
[0].kind() else {
682 bug
!("closure inputs not a tuple: {:?}", tuplized_inputs
[0]);
685 ty
::Binder
::bind_with_vars(
686 tcx
.mk_type_list_from_iter(
687 iter
::once(closure_ty
).chain(inputs
).chain(iter
::once(output
)),
693 DefiningTy
::Generator(def_id
, substs
, movability
) => {
694 assert_eq
!(self.mir_def
.did
.to_def_id(), def_id
);
695 let resume_ty
= substs
.as_generator().resume_ty();
696 let output
= substs
.as_generator().return_ty();
697 let generator_ty
= tcx
.mk_generator(def_id
, substs
, movability
);
698 let inputs_and_output
=
699 self.infcx
.tcx
.mk_type_list(&[generator_ty
, resume_ty
, output
]);
700 ty
::Binder
::dummy(inputs_and_output
)
703 DefiningTy
::FnDef(def_id
, _
) => {
704 let sig
= tcx
.fn_sig(def_id
).subst_identity();
705 let sig
= indices
.fold_to_region_vids(tcx
, sig
);
706 sig
.inputs_and_output()
709 DefiningTy
::Const(def_id
, _
) => {
710 // For a constant body, there are no inputs, and one
711 // "output" (the type of the constant).
712 assert_eq
!(self.mir_def
.did
.to_def_id(), def_id
);
713 let ty
= tcx
.type_of(self.mir_def
.def_id_for_type_of()).subst_identity();
714 let ty
= indices
.fold_to_region_vids(tcx
, ty
);
715 ty
::Binder
::dummy(tcx
.mk_type_list(&[ty
]))
718 DefiningTy
::InlineConst(def_id
, substs
) => {
719 assert_eq
!(self.mir_def
.did
.to_def_id(), def_id
);
720 let ty
= substs
.as_inline_const().ty();
721 ty
::Binder
::dummy(tcx
.mk_type_list(&[ty
]))
727 trait InferCtxtExt
<'tcx
> {
728 fn replace_free_regions_with_nll_infer_vars
<T
>(
730 origin
: NllRegionVariableOrigin
,
734 T
: TypeFoldable
<TyCtxt
<'tcx
>>;
736 fn replace_bound_regions_with_nll_infer_vars
<T
>(
738 origin
: NllRegionVariableOrigin
,
739 all_outlive_scope
: LocalDefId
,
740 value
: ty
::Binder
<'tcx
, T
>,
741 indices
: &mut UniversalRegionIndices
<'tcx
>,
744 T
: TypeFoldable
<TyCtxt
<'tcx
>>;
746 fn replace_late_bound_regions_with_nll_infer_vars_in_recursive_scope(
748 mir_def_id
: LocalDefId
,
749 indices
: &mut UniversalRegionIndices
<'tcx
>,
752 fn replace_late_bound_regions_with_nll_infer_vars_in_item(
754 mir_def_id
: LocalDefId
,
755 indices
: &mut UniversalRegionIndices
<'tcx
>,
759 impl<'cx
, 'tcx
> InferCtxtExt
<'tcx
> for BorrowckInferCtxt
<'cx
, 'tcx
> {
760 #[instrument(skip(self), level = "debug")]
761 fn replace_free_regions_with_nll_infer_vars
<T
>(
763 origin
: NllRegionVariableOrigin
,
767 T
: TypeFoldable
<TyCtxt
<'tcx
>>,
769 self.infcx
.tcx
.fold_regions(value
, |region
, _depth
| {
770 let name
= match region
.get_name() {
772 _
=> Symbol
::intern("anon"),
774 debug
!(?region
, ?name
);
776 let reg_var
= self.next_nll_region_var(origin
, || RegionCtxt
::Free(name
));
782 #[instrument(level = "debug", skip(self, indices))]
783 fn replace_bound_regions_with_nll_infer_vars
<T
>(
785 origin
: NllRegionVariableOrigin
,
786 all_outlive_scope
: LocalDefId
,
787 value
: ty
::Binder
<'tcx
, T
>,
788 indices
: &mut UniversalRegionIndices
<'tcx
>,
791 T
: TypeFoldable
<TyCtxt
<'tcx
>>,
793 let (value
, _map
) = self.tcx
.replace_late_bound_regions(value
, |br
| {
795 let liberated_region
= self.tcx
.mk_re_free(all_outlive_scope
.to_def_id(), br
.kind
);
797 let name
= match br
.kind
.get_name() {
799 _
=> Symbol
::intern("anon"),
802 self.next_nll_region_var(origin
, || RegionCtxt
::Bound(BoundRegionInfo
::Name(name
)))
805 indices
.insert_late_bound_region(liberated_region
, region_vid
.to_region_vid());
806 debug
!(?liberated_region
, ?region_vid
);
812 /// Finds late-bound regions that do not appear in the parameter listing and adds them to the
813 /// indices vector. Typically, we identify late-bound regions as we process the inputs and
814 /// outputs of the closure/function. However, sometimes there are late-bound regions which do
815 /// not appear in the fn parameters but which are nonetheless in scope. The simplest case of
816 /// this are unused functions, like fn foo<'a>() { } (see e.g., #51351). Despite not being used,
817 /// users can still reference these regions (e.g., let x: &'a u32 = &22;), so we need to create
818 /// entries for them and store them in the indices map. This code iterates over the complete
819 /// set of late-bound regions and checks for any that we have not yet seen, adding them to the
821 #[instrument(skip(self, indices))]
822 fn replace_late_bound_regions_with_nll_infer_vars_in_recursive_scope(
824 mir_def_id
: LocalDefId
,
825 indices
: &mut UniversalRegionIndices
<'tcx
>,
827 for_each_late_bound_region_in_recursive_scope(self.tcx
, mir_def_id
, |r
| {
829 if !indices
.indices
.contains_key(&r
) {
831 let name
= match r
.get_name() {
833 _
=> Symbol
::intern("anon"),
836 self.next_nll_region_var(FR
, || {
837 RegionCtxt
::LateBound(BoundRegionInfo
::Name(name
))
842 indices
.insert_late_bound_region(r
, region_vid
.to_region_vid());
847 #[instrument(skip(self, indices))]
848 fn replace_late_bound_regions_with_nll_infer_vars_in_item(
850 mir_def_id
: LocalDefId
,
851 indices
: &mut UniversalRegionIndices
<'tcx
>,
853 for_each_late_bound_region_in_item(self.tcx
, mir_def_id
, |r
| {
855 if !indices
.indices
.contains_key(&r
) {
857 let name
= match r
.get_name() {
859 _
=> Symbol
::intern("anon"),
862 self.next_nll_region_var(FR
, || {
863 RegionCtxt
::LateBound(BoundRegionInfo
::Name(name
))
867 indices
.insert_late_bound_region(r
, region_vid
.to_region_vid());
873 impl<'tcx
> UniversalRegionIndices
<'tcx
> {
874 /// Initially, the `UniversalRegionIndices` map contains only the
875 /// early-bound regions in scope. Once that is all setup, we come
876 /// in later and instantiate the late-bound regions, and then we
877 /// insert the `ReFree` version of those into the map as
878 /// well. These are used for error reporting.
879 fn insert_late_bound_region(&mut self, r
: ty
::Region
<'tcx
>, vid
: ty
::RegionVid
) {
880 debug
!("insert_late_bound_region({:?}, {:?})", r
, vid
);
881 self.indices
.insert(r
, vid
);
884 /// Converts `r` into a local inference variable: `r` can either
885 /// by a `ReVar` (i.e., already a reference to an inference
886 /// variable) or it can be `'static` or some early-bound
887 /// region. This is useful when taking the results from
888 /// type-checking and trait-matching, which may sometimes
889 /// reference those regions from the `ParamEnv`. It is also used
890 /// during initialization. Relies on the `indices` map having been
891 /// fully initialized.
892 pub fn to_region_vid(&self, r
: ty
::Region
<'tcx
>) -> RegionVid
{
893 if let ty
::ReVar(..) = *r
{
895 } else if r
.is_error() {
896 // We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
897 // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
898 // errors are being emitted and 2) it leaves the happy path unaffected.
904 .unwrap_or_else(|| bug
!("cannot convert `{:?}` to a region vid", r
))
908 /// Replaces all free regions in `value` with region vids, as
909 /// returned by `to_region_vid`.
910 pub fn fold_to_region_vids
<T
>(&self, tcx
: TyCtxt
<'tcx
>, value
: T
) -> T
912 T
: TypeFoldable
<TyCtxt
<'tcx
>>,
914 tcx
.fold_regions(value
, |region
, _
| tcx
.mk_re_var(self.to_region_vid(region
)))
918 /// Iterates over the late-bound regions defined on `mir_def_id` and all of its
919 /// parents, up to the typeck root, and invokes `f` with the liberated form
921 fn for_each_late_bound_region_in_recursive_scope
<'tcx
>(
923 mut mir_def_id
: LocalDefId
,
924 mut f
: impl FnMut(ty
::Region
<'tcx
>),
926 let typeck_root_def_id
= tcx
.typeck_root_def_id(mir_def_id
.to_def_id());
928 // Walk up the tree, collecting late-bound regions until we hit the typeck root
930 for_each_late_bound_region_in_item(tcx
, mir_def_id
, &mut f
);
932 if mir_def_id
.to_def_id() == typeck_root_def_id
{
935 mir_def_id
= tcx
.local_parent(mir_def_id
);
940 /// Iterates over the late-bound regions defined on `mir_def_id` and all of its
941 /// parents, up to the typeck root, and invokes `f` with the liberated form
943 fn for_each_late_bound_region_in_item
<'tcx
>(
945 mir_def_id
: LocalDefId
,
946 mut f
: impl FnMut(ty
::Region
<'tcx
>),
948 if !tcx
.def_kind(mir_def_id
).is_fn_like() {
952 for bound_var
in tcx
.late_bound_vars(tcx
.hir().local_def_id_to_hir_id(mir_def_id
)) {
953 let ty
::BoundVariableKind
::Region(bound_region
) = bound_var
else { continue; }
;
954 let liberated_region
= tcx
.mk_re_free(mir_def_id
.to_def_id(), bound_region
);