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 be returning 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
::hir
::def_id
::DefId
;
17 use rustc
::hir
::{self, BodyOwnerKind, HirId}
;
18 use rustc
::infer
::{InferCtxt, NLLRegionVariableOrigin}
;
19 use rustc
::middle
::lang_items
;
20 use rustc
::ty
::fold
::TypeFoldable
;
21 use rustc
::ty
::subst
::{InternalSubsts, SubstsRef, Subst}
;
22 use rustc
::ty
::{self, RegionVid, Ty, TyCtxt}
;
23 use rustc
::util
::nodemap
::FxHashMap
;
24 use rustc_index
::vec
::{Idx, IndexVec}
;
25 use rustc_errors
::DiagnosticBuilder
;
28 use super::ToRegionVid
;
31 pub struct UniversalRegions
<'tcx
> {
32 indices
: UniversalRegionIndices
<'tcx
>,
34 /// The vid assigned to `'static`
35 pub fr_static
: RegionVid
,
37 /// A special region vid created to represent the current MIR fn
38 /// body. It will outlive the entire CFG but it will not outlive
39 /// any other universal regions.
40 pub fr_fn_body
: RegionVid
,
42 /// We create region variables such that they are ordered by their
43 /// `RegionClassification`. The first block are globals, then
44 /// externals, then locals. So, things from:
45 /// - `FIRST_GLOBAL_INDEX..first_extern_index` are global,
46 /// - `first_extern_index..first_local_index` are external,
47 /// - `first_local_index..num_universals` are local.
48 first_extern_index
: usize,
50 /// See `first_extern_index`.
51 first_local_index
: usize,
53 /// The total number of universal region variables instantiated.
54 num_universals
: usize,
56 /// The "defining" type for this function, with all universal
57 /// regions instantiated. For a closure or generator, this is the
58 /// closure type, but for a top-level function it's the `FnDef`.
59 pub defining_ty
: DefiningTy
<'tcx
>,
61 /// The return type of this function, with all regions replaced by
62 /// their universal `RegionVid` equivalents.
64 /// N.B., associated types in this type have not been normalized,
65 /// as the name suggests. =)
66 pub unnormalized_output_ty
: Ty
<'tcx
>,
68 /// The fully liberated input types of this function, with all
69 /// regions replaced by their universal `RegionVid` equivalents.
71 /// N.B., associated types in these types have not been normalized,
72 /// as the name suggests. =)
73 pub unnormalized_input_tys
: &'tcx
[Ty
<'tcx
>],
75 pub yield_ty
: Option
<Ty
<'tcx
>>,
78 /// The "defining type" for this MIR. The key feature of the "defining
79 /// type" is that it contains the information needed to derive all the
80 /// universal regions that are in scope as well as the types of the
81 /// inputs/output from the MIR. In general, early-bound universal
82 /// regions appear free in the defining type and late-bound regions
83 /// appear bound in the signature.
84 #[derive(Copy, Clone, Debug)]
85 pub enum DefiningTy
<'tcx
> {
86 /// The MIR is a closure. The signature is found via
87 /// `ClosureSubsts::closure_sig_ty`.
88 Closure(DefId
, SubstsRef
<'tcx
>),
90 /// The MIR is a generator. The signature is that generators take
91 /// no parameters and return the result of
92 /// `ClosureSubsts::generator_return_ty`.
93 Generator(DefId
, SubstsRef
<'tcx
>, hir
::GeneratorMovability
),
95 /// The MIR is a fn item with the given `DefId` and substs. The signature
96 /// of the function can be bound then with the `fn_sig` query.
97 FnDef(DefId
, SubstsRef
<'tcx
>),
99 /// The MIR represents some form of constant. The signature then
100 /// is that it has no inputs and a single return value, which is
101 /// the value of the constant.
102 Const(DefId
, SubstsRef
<'tcx
>),
105 impl<'tcx
> DefiningTy
<'tcx
> {
106 /// Returns a list of all the upvar types for this MIR. If this is
107 /// not a closure or generator, there are no upvars, and hence it
108 /// will be an empty list. The order of types in this list will
109 /// match up with the upvar order in the HIR, typesystem, and MIR.
110 pub fn upvar_tys(self, tcx
: TyCtxt
<'tcx
>) -> impl Iterator
<Item
= Ty
<'tcx
>> + 'tcx
{
112 DefiningTy
::Closure(def_id
, substs
) => Either
::Left(
113 substs
.as_closure().upvar_tys(def_id
, tcx
)
115 DefiningTy
::Generator(def_id
, substs
, _
) => {
116 Either
::Right(Either
::Left(substs
.as_generator().upvar_tys(def_id
, tcx
)))
118 DefiningTy
::FnDef(..) | DefiningTy
::Const(..) => {
119 Either
::Right(Either
::Right(iter
::empty()))
124 /// Number of implicit inputs -- notably the "environment"
125 /// parameter for closures -- that appear in MIR but not in the
127 pub fn implicit_inputs(self) -> usize {
129 DefiningTy
::Closure(..) | DefiningTy
::Generator(..) => 1,
130 DefiningTy
::FnDef(..) | DefiningTy
::Const(..) => 0,
136 struct UniversalRegionIndices
<'tcx
> {
137 /// For those regions that may appear in the parameter environment
138 /// ('static and early-bound regions), we maintain a map from the
139 /// `ty::Region` to the internal `RegionVid` we are using. This is
140 /// used because trait matching and type-checking will feed us
141 /// region constraints that reference those regions and we need to
142 /// be able to map them our internal `RegionVid`. This is
143 /// basically equivalent to a `InternalSubsts`, except that it also
144 /// contains an entry for `ReStatic` -- it might be nice to just
145 /// use a substs, and then handle `ReStatic` another way.
146 indices
: FxHashMap
<ty
::Region
<'tcx
>, RegionVid
>,
149 #[derive(Debug, PartialEq)]
150 pub enum RegionClassification
{
151 /// A **global** region is one that can be named from
152 /// anywhere. There is only one, `'static`.
155 /// An **external** region is only relevant for closures. In that
156 /// case, it refers to regions that are free in the closure type
157 /// -- basically, something bound in the surrounding context.
159 /// Consider this example:
162 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
163 /// let closure = for<'x> |x: &'x u32| { .. };
164 /// ^^^^^^^ pretend this were legal syntax
165 /// for declaring a late-bound region in
166 /// a closure signature
170 /// Here, the lifetimes `'a` and `'b` would be **external** to the
173 /// If we are not analyzing a closure, there are no external
177 /// A **local** lifetime is one about which we know the full set
178 /// of relevant constraints (that is, relationships to other named
179 /// regions). For a closure, this includes any region bound in
180 /// the closure's signature. For a fn item, this includes all
181 /// regions other than global ones.
183 /// Continuing with the example from `External`, if we were
184 /// analyzing the closure, then `'x` would be local (and `'a` and
185 /// `'b` are external). If we are analyzing the function item
186 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
191 const FIRST_GLOBAL_INDEX
: usize = 0;
193 impl<'tcx
> UniversalRegions
<'tcx
> {
194 /// Creates a new and fully initialized `UniversalRegions` that
195 /// contains indices for all the free regions found in the given
196 /// MIR -- that is, all the regions that appear in the function's
197 /// signature. This will also compute the relationships that are
198 /// known between those regions.
200 infcx
: &InferCtxt
<'_
, 'tcx
>,
202 param_env
: ty
::ParamEnv
<'tcx
>,
205 let mir_hir_id
= tcx
.hir().as_local_hir_id(mir_def_id
).unwrap();
206 UniversalRegionsBuilder
{
214 /// Given a reference to a closure type, extracts all the values
215 /// from its free regions and returns a vector with them. This is
216 /// used when the closure's creator checks that the
217 /// `ClosureRegionRequirements` are met. The requirements from
218 /// `ClosureRegionRequirements` are expressed in terms of
219 /// `RegionVid` entries that map into the returned vector `V`: so
220 /// if the `ClosureRegionRequirements` contains something like
221 /// `'1: '2`, then the caller would impose the constraint that
223 pub fn closure_mapping(
225 closure_substs
: SubstsRef
<'tcx
>,
226 expected_num_vars
: usize,
227 closure_base_def_id
: DefId
,
228 ) -> IndexVec
<RegionVid
, ty
::Region
<'tcx
>> {
229 let mut region_mapping
= IndexVec
::with_capacity(expected_num_vars
);
230 region_mapping
.push(tcx
.lifetimes
.re_static
);
231 tcx
.for_each_free_region(&closure_substs
, |fr
| {
232 region_mapping
.push(fr
);
235 for_each_late_bound_region_defined_on(tcx
, closure_base_def_id
, |r
| {
236 region_mapping
.push(r
);
240 region_mapping
.len(),
242 "index vec had unexpected number of variables"
248 /// Returns `true` if `r` is a member of this set of universal regions.
249 pub fn is_universal_region(&self, r
: RegionVid
) -> bool
{
250 (FIRST_GLOBAL_INDEX
..self.num_universals
).contains(&r
.index())
253 /// Classifies `r` as a universal region, returning `None` if this
254 /// is not a member of this set of universal regions.
255 pub fn region_classification(&self, r
: RegionVid
) -> Option
<RegionClassification
> {
256 let index
= r
.index();
257 if (FIRST_GLOBAL_INDEX
..self.first_extern_index
).contains(&index
) {
258 Some(RegionClassification
::Global
)
259 } else if (self.first_extern_index
..self.first_local_index
).contains(&index
) {
260 Some(RegionClassification
::External
)
261 } else if (self.first_local_index
..self.num_universals
).contains(&index
) {
262 Some(RegionClassification
::Local
)
268 /// Returns an iterator over all the RegionVids corresponding to
269 /// universally quantified free regions.
270 pub fn universal_regions(&self) -> impl Iterator
<Item
= RegionVid
> {
271 (FIRST_GLOBAL_INDEX
..self.num_universals
).map(RegionVid
::new
)
274 /// Returns `true` if `r` is classified as an local region.
275 pub fn is_local_free_region(&self, r
: RegionVid
) -> bool
{
276 self.region_classification(r
) == Some(RegionClassification
::Local
)
279 /// Returns the number of universal regions created in any category.
280 pub fn len(&self) -> usize {
284 /// Returns the number of global plus external universal regions.
285 /// For closures, these are the regions that appear free in the
286 /// closure type (versus those bound in the closure
287 /// signature). They are therefore the regions between which the
288 /// closure may impose constraints that its creator must verify.
289 pub fn num_global_and_external_regions(&self) -> usize {
290 self.first_local_index
293 /// Gets an iterator over all the early-bound regions that have names.
294 pub fn named_universal_regions
<'s
>(
296 ) -> impl Iterator
<Item
= (ty
::Region
<'tcx
>, ty
::RegionVid
)> + 's
{
297 self.indices
.indices
.iter().map(|(&r
, &v
)| (r
, v
))
300 /// See `UniversalRegionIndices::to_region_vid`.
301 pub fn to_region_vid(&self, r
: ty
::Region
<'tcx
>) -> RegionVid
{
302 self.indices
.to_region_vid(r
)
305 /// As part of the NLL unit tests, you can annotate a function with
306 /// `#[rustc_regions]`, and we will emit information about the region
307 /// inference context and -- in particular -- the external constraints
308 /// that this region imposes on others. The methods in this file
309 /// handle the part about dumping the inference context internal
311 crate fn annotate(&self, tcx
: TyCtxt
<'tcx
>, err
: &mut DiagnosticBuilder
<'_
>) {
312 match self.defining_ty
{
313 DefiningTy
::Closure(def_id
, substs
) => {
315 "defining type: {:?} with closure substs {:#?}",
320 // FIXME: It'd be nice to print the late-bound regions
321 // here, but unfortunately these wind up stored into
322 // tests, and the resulting print-outs include def-ids
323 // and other things that are not stable across tests!
324 // So we just include the region-vid. Annoying.
325 let closure_base_def_id
= tcx
.closure_base_def_id(def_id
);
326 for_each_late_bound_region_defined_on(tcx
, closure_base_def_id
, |r
| {
328 "late-bound region is {:?}",
329 self.to_region_vid(r
),
333 DefiningTy
::Generator(def_id
, substs
, _
) => {
335 "defining type: {:?} with generator substs {:#?}",
340 // FIXME: As above, we'd like to print out the region
341 // `r` but doing so is not stable across architectures
343 let closure_base_def_id
= tcx
.closure_base_def_id(def_id
);
344 for_each_late_bound_region_defined_on(tcx
, closure_base_def_id
, |r
| {
346 "late-bound region is {:?}",
347 self.to_region_vid(r
),
351 DefiningTy
::FnDef(def_id
, substs
) => {
353 "defining type: {:?} with substs {:#?}",
358 DefiningTy
::Const(def_id
, substs
) => {
360 "defining constant type: {:?} with substs {:#?}",
369 struct UniversalRegionsBuilder
<'cx
, 'tcx
> {
370 infcx
: &'cx InferCtxt
<'cx
, 'tcx
>,
373 param_env
: ty
::ParamEnv
<'tcx
>,
376 const FR
: NLLRegionVariableOrigin
= NLLRegionVariableOrigin
::FreeRegion
;
378 impl<'cx
, 'tcx
> UniversalRegionsBuilder
<'cx
, 'tcx
> {
379 fn build(self) -> UniversalRegions
<'tcx
> {
380 debug
!("build(mir_def_id={:?})", self.mir_def_id
);
382 let param_env
= self.param_env
;
383 debug
!("build: param_env={:?}", param_env
);
385 assert_eq
!(FIRST_GLOBAL_INDEX
, self.infcx
.num_region_vars());
387 // Create the "global" region that is always free in all contexts: 'static.
388 let fr_static
= self.infcx
.next_nll_region_var(FR
).to_region_vid();
390 // We've now added all the global regions. The next ones we
391 // add will be external.
392 let first_extern_index
= self.infcx
.num_region_vars();
394 let defining_ty
= self.defining_ty();
395 debug
!("build: defining_ty={:?}", defining_ty
);
397 let mut indices
= self.compute_indices(fr_static
, defining_ty
);
398 debug
!("build: indices={:?}", indices
);
400 let closure_base_def_id
= self.infcx
.tcx
.closure_base_def_id(self.mir_def_id
);
402 // If this is a closure or generator, then the late-bound regions from the enclosing
403 // function are actually external regions to us. For example, here, 'a is not local
404 // to the closure c (although it is local to the fn foo):
406 // let c = || { let x: &'a u32 = ...; }
408 if self.mir_def_id
!= closure_base_def_id
{
410 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id
, &mut indices
)
413 let bound_inputs_and_output
= self.compute_inputs_and_output(&indices
, defining_ty
);
415 // "Liberate" the late-bound regions. These correspond to
416 // "local" free regions.
417 let first_local_index
= self.infcx
.num_region_vars();
418 let inputs_and_output
= self.infcx
.replace_bound_regions_with_nll_infer_vars(
421 &bound_inputs_and_output
,
424 // Converse of above, if this is a function then the late-bound regions declared on its
425 // signature are local to the fn.
426 if self.mir_def_id
== closure_base_def_id
{
428 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id
, &mut indices
);
431 let (unnormalized_output_ty
, mut unnormalized_input_tys
) =
432 inputs_and_output
.split_last().unwrap();
434 // C-variadic fns also have a `VaList` input that's not listed in the signature
435 // (as it's created inside the body itself, not passed in from outside).
436 if let DefiningTy
::FnDef(def_id
, _
) = defining_ty
{
437 if self.infcx
.tcx
.fn_sig(def_id
).c_variadic() {
438 let va_list_did
= self.infcx
.tcx
.require_lang_item(
439 lang_items
::VaListTypeLangItem
,
440 Some(self.infcx
.tcx
.def_span(self.mir_def_id
),),
442 let region
= self.infcx
.tcx
.mk_region(ty
::ReVar(
443 self.infcx
.next_nll_region_var(FR
).to_region_vid(),
445 let va_list_ty
= self.infcx
.tcx
.type_of(va_list_did
)
446 .subst(self.infcx
.tcx
, &[region
.into()]);
448 unnormalized_input_tys
= self.infcx
.tcx
.mk_type_list(
449 unnormalized_input_tys
.iter().copied()
450 .chain(iter
::once(va_list_ty
)),
455 let fr_fn_body
= self.infcx
.next_nll_region_var(FR
).to_region_vid();
456 let num_universals
= self.infcx
.num_region_vars();
459 "build: global regions = {}..{}",
460 FIRST_GLOBAL_INDEX
, first_extern_index
463 "build: extern regions = {}..{}",
464 first_extern_index
, first_local_index
467 "build: local regions = {}..{}",
468 first_local_index
, num_universals
471 let yield_ty
= match defining_ty
{
472 DefiningTy
::Generator(def_id
, substs
, _
) => {
473 Some(substs
.as_generator().yield_ty(def_id
, self.infcx
.tcx
))
486 unnormalized_output_ty
,
487 unnormalized_input_tys
,
492 /// Returns the "defining type" of the current MIR;
493 /// see `DefiningTy` for details.
494 fn defining_ty(&self) -> DefiningTy
<'tcx
> {
495 let tcx
= self.infcx
.tcx
;
496 let closure_base_def_id
= tcx
.closure_base_def_id(self.mir_def_id
);
498 match tcx
.hir().body_owner_kind(self.mir_hir_id
) {
499 BodyOwnerKind
::Closure
|
500 BodyOwnerKind
::Fn
=> {
501 let defining_ty
= if self.mir_def_id
== closure_base_def_id
{
502 tcx
.type_of(closure_base_def_id
)
504 let tables
= tcx
.typeck_tables_of(self.mir_def_id
);
505 tables
.node_type(self.mir_hir_id
)
508 debug
!("defining_ty (pre-replacement): {:?}", defining_ty
);
510 let defining_ty
= self.infcx
511 .replace_free_regions_with_nll_infer_vars(FR
, &defining_ty
);
513 match defining_ty
.kind
{
514 ty
::Closure(def_id
, substs
) => DefiningTy
::Closure(def_id
, substs
),
515 ty
::Generator(def_id
, substs
, movability
) => {
516 DefiningTy
::Generator(def_id
, substs
, movability
)
518 ty
::FnDef(def_id
, substs
) => DefiningTy
::FnDef(def_id
, substs
),
520 tcx
.def_span(self.mir_def_id
),
521 "expected defining type for `{:?}`: `{:?}`",
528 BodyOwnerKind
::Const
| BodyOwnerKind
::Static(..) => {
529 assert_eq
!(closure_base_def_id
, self.mir_def_id
);
530 let identity_substs
= InternalSubsts
::identity_for_item(tcx
, closure_base_def_id
);
531 let substs
= self.infcx
532 .replace_free_regions_with_nll_infer_vars(FR
, &identity_substs
);
533 DefiningTy
::Const(self.mir_def_id
, substs
)
538 /// Builds a hashmap that maps from the universal regions that are
539 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
540 /// `RegionVid`). The map returned by this function contains only
541 /// the early-bound regions.
544 fr_static
: RegionVid
,
545 defining_ty
: DefiningTy
<'tcx
>,
546 ) -> UniversalRegionIndices
<'tcx
> {
547 let tcx
= self.infcx
.tcx
;
548 let closure_base_def_id
= tcx
.closure_base_def_id(self.mir_def_id
);
549 let identity_substs
= InternalSubsts
::identity_for_item(tcx
, closure_base_def_id
);
550 let fr_substs
= match defining_ty
{
551 DefiningTy
::Closure(_
, ref substs
)
552 | DefiningTy
::Generator(_
, ref substs
, _
) => {
553 // In the case of closures, we rely on the fact that
554 // the first N elements in the ClosureSubsts are
555 // inherited from the `closure_base_def_id`.
556 // Therefore, when we zip together (below) with
557 // `identity_substs`, we will get only those regions
558 // that correspond to early-bound regions declared on
559 // the `closure_base_def_id`.
560 assert
!(substs
.len() >= identity_substs
.len());
561 assert_eq
!(substs
.regions().count(), identity_substs
.regions().count());
565 DefiningTy
::FnDef(_
, substs
) | DefiningTy
::Const(_
, substs
) => substs
,
568 let global_mapping
= iter
::once((tcx
.lifetimes
.re_static
, fr_static
));
569 let subst_mapping
= identity_substs
571 .zip(fr_substs
.regions().map(|r
| r
.to_region_vid()));
573 UniversalRegionIndices
{
574 indices
: global_mapping
.chain(subst_mapping
).collect(),
578 fn compute_inputs_and_output(
580 indices
: &UniversalRegionIndices
<'tcx
>,
581 defining_ty
: DefiningTy
<'tcx
>,
582 ) -> ty
::Binder
<&'tcx ty
::List
<Ty
<'tcx
>>> {
583 let tcx
= self.infcx
.tcx
;
585 DefiningTy
::Closure(def_id
, substs
) => {
586 assert_eq
!(self.mir_def_id
, def_id
);
587 let closure_sig
= substs
.as_closure().sig_ty(def_id
, tcx
).fn_sig(tcx
);
588 let inputs_and_output
= closure_sig
.inputs_and_output();
589 let closure_ty
= tcx
.closure_env_ty(def_id
, substs
).unwrap();
593 |closure_ty
, inputs_and_output
| {
594 // The "inputs" of the closure in the
595 // signature appear as a tuple. The MIR side
596 // flattens this tuple.
597 let (&output
, tuplized_inputs
) = inputs_and_output
.split_last().unwrap();
598 assert_eq
!(tuplized_inputs
.len(), 1, "multiple closure inputs");
599 let inputs
= match tuplized_inputs
[0].kind
{
600 ty
::Tuple(inputs
) => inputs
,
601 _
=> bug
!("closure inputs not a tuple: {:?}", tuplized_inputs
[0]),
605 iter
::once(closure_ty
)
606 .chain(inputs
.iter().map(|k
| k
.expect_ty()))
607 .chain(iter
::once(output
)),
613 DefiningTy
::Generator(def_id
, substs
, movability
) => {
614 assert_eq
!(self.mir_def_id
, def_id
);
615 let output
= substs
.as_generator().return_ty(def_id
, tcx
);
616 let generator_ty
= tcx
.mk_generator(def_id
, substs
, movability
);
617 let inputs_and_output
= self.infcx
.tcx
.intern_type_list(&[generator_ty
, output
]);
618 ty
::Binder
::dummy(inputs_and_output
)
621 DefiningTy
::FnDef(def_id
, _
) => {
622 let sig
= tcx
.fn_sig(def_id
);
623 let sig
= indices
.fold_to_region_vids(tcx
, &sig
);
624 sig
.inputs_and_output()
627 DefiningTy
::Const(def_id
, _
) => {
628 // For a constant body, there are no inputs, and one
629 // "output" (the type of the constant).
630 assert_eq
!(self.mir_def_id
, def_id
);
631 let ty
= tcx
.type_of(def_id
);
632 let ty
= indices
.fold_to_region_vids(tcx
, &ty
);
633 ty
::Binder
::dummy(tcx
.intern_type_list(&[ty
]))
639 trait InferCtxtExt
<'tcx
> {
640 fn replace_free_regions_with_nll_infer_vars
<T
>(
642 origin
: NLLRegionVariableOrigin
,
646 T
: TypeFoldable
<'tcx
>;
648 fn replace_bound_regions_with_nll_infer_vars
<T
>(
650 origin
: NLLRegionVariableOrigin
,
651 all_outlive_scope
: DefId
,
652 value
: &ty
::Binder
<T
>,
653 indices
: &mut UniversalRegionIndices
<'tcx
>,
656 T
: TypeFoldable
<'tcx
>;
658 fn replace_late_bound_regions_with_nll_infer_vars(
661 indices
: &mut UniversalRegionIndices
<'tcx
>,
665 impl<'cx
, 'tcx
> InferCtxtExt
<'tcx
> for InferCtxt
<'cx
, 'tcx
> {
666 fn replace_free_regions_with_nll_infer_vars
<T
>(
668 origin
: NLLRegionVariableOrigin
,
672 T
: TypeFoldable
<'tcx
>,
674 self.tcx
.fold_regions(value
, &mut false, |_region
, _depth
| {
675 self.next_nll_region_var(origin
)
679 fn replace_bound_regions_with_nll_infer_vars
<T
>(
681 origin
: NLLRegionVariableOrigin
,
682 all_outlive_scope
: DefId
,
683 value
: &ty
::Binder
<T
>,
684 indices
: &mut UniversalRegionIndices
<'tcx
>,
687 T
: TypeFoldable
<'tcx
>,
690 "replace_bound_regions_with_nll_infer_vars(value={:?}, all_outlive_scope={:?})",
691 value
, all_outlive_scope
,
693 let (value
, _map
) = self.tcx
.replace_late_bound_regions(value
, |br
| {
694 debug
!("replace_bound_regions_with_nll_infer_vars: br={:?}", br
);
695 let liberated_region
= self.tcx
.mk_region(ty
::ReFree(ty
::FreeRegion
{
696 scope
: all_outlive_scope
,
699 let region_vid
= self.next_nll_region_var(origin
);
700 indices
.insert_late_bound_region(liberated_region
, region_vid
.to_region_vid());
702 "replace_bound_regions_with_nll_infer_vars: liberated_region={:?} => {:?}",
703 liberated_region
, region_vid
710 /// Finds late-bound regions that do not appear in the parameter listing and adds them to the
711 /// indices vector. Typically, we identify late-bound regions as we process the inputs and
712 /// outputs of the closure/function. However, sometimes there are late-bound regions which do
713 /// not appear in the fn parameters but which are nonetheless in scope. The simplest case of
714 /// this are unused functions, like fn foo<'a>() { } (see e.g., #51351). Despite not being used,
715 /// users can still reference these regions (e.g., let x: &'a u32 = &22;), so we need to create
716 /// entries for them and store them in the indices map. This code iterates over the complete
717 /// set of late-bound regions and checks for any that we have not yet seen, adding them to the
719 fn replace_late_bound_regions_with_nll_infer_vars(
722 indices
: &mut UniversalRegionIndices
<'tcx
>,
725 "replace_late_bound_regions_with_nll_infer_vars(mir_def_id={:?})",
728 let closure_base_def_id
= self.tcx
.closure_base_def_id(mir_def_id
);
729 for_each_late_bound_region_defined_on(self.tcx
, closure_base_def_id
, |r
| {
730 debug
!("replace_late_bound_regions_with_nll_infer_vars: r={:?}", r
);
731 if !indices
.indices
.contains_key(&r
) {
732 let region_vid
= self.next_nll_region_var(FR
);
733 indices
.insert_late_bound_region(r
, region_vid
.to_region_vid());
739 impl<'tcx
> UniversalRegionIndices
<'tcx
> {
740 /// Initially, the `UniversalRegionIndices` map contains only the
741 /// early-bound regions in scope. Once that is all setup, we come
742 /// in later and instantiate the late-bound regions, and then we
743 /// insert the `ReFree` version of those into the map as
744 /// well. These are used for error reporting.
745 fn insert_late_bound_region(&mut self, r
: ty
::Region
<'tcx
>, vid
: ty
::RegionVid
) {
746 debug
!("insert_late_bound_region({:?}, {:?})", r
, vid
);
747 self.indices
.insert(r
, vid
);
750 /// Converts `r` into a local inference variable: `r` can either
751 /// by a `ReVar` (i.e., already a reference to an inference
752 /// variable) or it can be `'static` or some early-bound
753 /// region. This is useful when taking the results from
754 /// type-checking and trait-matching, which may sometimes
755 /// reference those regions from the `ParamEnv`. It is also used
756 /// during initialization. Relies on the `indices` map having been
757 /// fully initialized.
758 pub fn to_region_vid(&self, r
: ty
::Region
<'tcx
>) -> RegionVid
{
759 if let ty
::ReVar(..) = r
{
764 .unwrap_or_else(|| bug
!("cannot convert `{:?}` to a region vid", r
))
768 /// Replaces all free regions in `value` with region vids, as
769 /// returned by `to_region_vid`.
770 pub fn fold_to_region_vids
<T
>(&self, tcx
: TyCtxt
<'tcx
>, value
: &T
) -> T
772 T
: TypeFoldable
<'tcx
>,
774 tcx
.fold_regions(value
, &mut false, |region
, _
| {
775 tcx
.mk_region(ty
::ReVar(self.to_region_vid(region
)))
780 /// Iterates over the late-bound regions defined on fn_def_id and
781 /// invokes `f` with the liberated form of each one.
782 fn for_each_late_bound_region_defined_on
<'tcx
>(
785 mut f
: impl FnMut(ty
::Region
<'tcx
>),
787 if let Some(late_bounds
) = tcx
.is_late_bound_map(fn_def_id
.index
) {
788 for late_bound
in late_bounds
.iter() {
790 owner
: fn_def_id
.index
,
791 local_id
: *late_bound
,
793 let name
= tcx
.hir().name(hir_id
);
794 let region_def_id
= tcx
.hir().local_def_id(hir_id
);
795 let liberated_region
= tcx
.mk_region(ty
::ReFree(ty
::FreeRegion
{
797 bound_region
: ty
::BoundRegion
::BrNamed(region_def_id
, name
),