1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Code to extract the universally quantified regions declared on a
12 //! function and the relationships between them. For example:
15 //! fn foo<'a, 'b, 'c: 'b>() { }
18 //! here we would be returning a map assigning each of `{'a, 'b, 'c}`
19 //! to an index, as well as the `FreeRegionMap` which can compute
20 //! relationships between them.
22 //! The code in this file doesn't *do anything* with those results; it
23 //! just returns them for other code to use.
26 use rustc::hir::def_id::DefId;
27 use rustc::hir::{self, BodyOwnerKind, HirId};
28 use rustc::infer::{InferCtxt, NLLRegionVariableOrigin};
29 use rustc::ty::fold::TypeFoldable;
30 use rustc::ty::subst::Substs;
31 use rustc::ty::{self, ClosureSubsts, GeneratorSubsts, RegionVid, Ty, TyCtxt};
32 use rustc::util::nodemap::FxHashMap;
33 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
34 use rustc_errors::DiagnosticBuilder;
38 use super::ToRegionVid;
41 pub struct UniversalRegions<'tcx> {
42 indices: UniversalRegionIndices<'tcx>,
44 /// The vid assigned to `'static`
45 pub fr_static: RegionVid,
47 /// 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.
50 pub fr_fn_body: RegionVid,
52 /// 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; and
57 /// - `first_local_index..num_universals` are local.
58 first_extern_index: usize,
60 /// See `first_extern_index`.
61 first_local_index: usize,
63 /// The total number of universal region variables instantiated.
64 num_universals: usize,
66 /// The "defining" type for this function, with all universal
67 /// regions instantiated. For a closure or generator, this is the
68 /// closure type, but for a top-level function it's the `FnDef`.
69 pub defining_ty: DefiningTy<'tcx>,
71 /// The return type of this function, with all regions replaced by
72 /// their universal `RegionVid` equivalents.
74 /// NB. Associated types in this type have not been normalized,
75 /// as the name suggests. =)
76 pub unnormalized_output_ty: Ty<'tcx>,
78 /// The fully liberated input types of this function, with all
79 /// regions replaced by their universal `RegionVid` equivalents.
81 /// NB. Associated types in these types have not been normalized,
82 /// as the name suggests. =)
83 pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
85 pub yield_ty: Option<Ty<'tcx>>,
88 /// The "defining type" for this MIR. The key feature of the "defining
89 /// type" is that it contains the information needed to derive all the
90 /// universal regions that are in scope as well as the types of the
91 /// inputs/output from the MIR. In general, early-bound universal
92 /// regions appear free in the defining type and late-bound regions
93 /// appear bound in the signature.
94 #[derive(Copy, Clone, Debug)]
95 pub enum DefiningTy<'tcx> {
96 /// The MIR is a closure. The signature is found via
97 /// `ClosureSubsts::closure_sig_ty`.
98 Closure(DefId, ty::ClosureSubsts<'tcx>),
100 /// The MIR is a generator. The signature is that generators take
101 /// no parameters and return the result of
102 /// `ClosureSubsts::generator_return_ty`.
103 Generator(DefId, ty::GeneratorSubsts<'tcx>, hir::GeneratorMovability),
105 /// The MIR is a fn item with the given def-id and substs. The signature
106 /// of the function can be bound then with the `fn_sig` query.
107 FnDef(DefId, &'tcx Substs<'tcx>),
109 /// The MIR represents some form of constant. The signature then
110 /// is that it has no inputs and a single return value, which is
111 /// the value of the constant.
112 Const(DefId, &'tcx Substs<'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_decls` field of `Mir`.
120 pub fn upvar_tys(self, tcx: TyCtxt<'_, '_, 'tcx>) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
122 DefiningTy::Closure(def_id, substs) => Either::Left(substs.upvar_tys(def_id, tcx)),
123 DefiningTy::Generator(def_id, substs, _) => {
124 Either::Right(Either::Left(substs.upvar_tys(def_id, tcx)))
126 DefiningTy::FnDef(..) | DefiningTy::Const(..) => {
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(..) => 0,
144 struct UniversalRegionIndices<'tcx> {
145 /// For those regions that may appear in the parameter environment
146 /// ('static and early-bound regions), we maintain a map from the
147 /// `ty::Region` to the internal `RegionVid` we are using. This is
148 /// used because trait matching and type-checking will feed us
149 /// region constraints that reference those regions and we need to
150 /// be able to map them our internal `RegionVid`. This is
151 /// basically equivalent to a `Substs`, except that it also
152 /// contains an entry for `ReStatic` -- it might be nice to just
153 /// use a substs, and then handle `ReStatic` another way.
154 indices: FxHashMap<ty::Region<'tcx>, RegionVid>,
157 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
158 pub enum RegionClassification {
159 /// A **global** region is one that can be named from
160 /// anywhere. There is only one, `'static`.
163 /// An **external** region is only relevant for closures. In that
164 /// case, it refers to regions that are free in the closure type
165 /// -- basically, something bound in the surrounding context.
167 /// Consider this example:
170 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
171 /// let closure = for<'x> |x: &'x u32| { .. };
172 /// ^^^^^^^ pretend this were legal syntax
173 /// for declaring a late-bound region in
174 /// a closure signature
178 /// Here, the lifetimes `'a` and `'b` would be **external** to the
181 /// If we are not analyzing a closure, there are no external
185 /// A **local** lifetime is one about which we know the full set
186 /// of relevant constraints (that is, relationships to other named
187 /// regions). For a closure, this includes any region bound in
188 /// the closure's signature. For a fn item, this includes all
189 /// regions other than global ones.
191 /// Continuing with the example from `External`, if we were
192 /// analyzing the closure, then `'x` would be local (and `'a` and
193 /// `'b` are external). If we are analyzing the function item
194 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
199 const FIRST_GLOBAL_INDEX: usize = 0;
201 impl<'tcx> UniversalRegions<'tcx> {
202 /// Creates a new and fully initialized `UniversalRegions` that
203 /// contains indices for all the free regions found in the given
204 /// MIR -- that is, all the regions that appear in the function's
205 /// signature. This will also compute the relationships that are
206 /// known between those regions.
208 infcx: &InferCtxt<'_, '_, 'tcx>,
210 param_env: ty::ParamEnv<'tcx>,
213 let mir_node_id = tcx.hir.as_local_node_id(mir_def_id).unwrap();
214 let mir_hir_id = tcx.hir.node_to_hir_id(mir_node_id);
215 UniversalRegionsBuilder {
224 /// Given a reference to a closure type, extracts all the values
225 /// from its free regions and returns a vector with them. This is
226 /// used when the closure's creator checks that the
227 /// `ClosureRegionRequirements` are met. The requirements from
228 /// `ClosureRegionRequirements` are expressed in terms of
229 /// `RegionVid` entries that map into the returned vector `V`: so
230 /// if the `ClosureRegionRequirements` contains something like
231 /// `'1: '2`, then the caller would impose the constraint that
233 pub fn closure_mapping(
234 tcx: TyCtxt<'_, '_, 'tcx>,
235 closure_ty: Ty<'tcx>,
236 expected_num_vars: usize,
237 closure_base_def_id: DefId,
238 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
239 let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
240 region_mapping.push(tcx.types.re_static);
241 tcx.for_each_free_region(&closure_ty, |fr| {
242 region_mapping.push(fr);
245 for_each_late_bound_region_defined_on(tcx, closure_base_def_id, |r| {
246 region_mapping.push(r);
250 region_mapping.len(),
252 "index vec had unexpected number of variables"
258 /// True if `r` is a member of this set of universal regions.
259 pub fn is_universal_region(&self, r: RegionVid) -> bool {
260 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
263 /// Classifies `r` as a universal region, returning `None` if this
264 /// is not a member of this set of universal regions.
265 pub fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
266 let index = r.index();
267 if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
268 Some(RegionClassification::Global)
269 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
270 Some(RegionClassification::External)
271 } else if (self.first_local_index..self.num_universals).contains(&index) {
272 Some(RegionClassification::Local)
278 /// Returns an iterator over all the RegionVids corresponding to
279 /// universally quantified free regions.
280 pub fn universal_regions(&self) -> impl Iterator<Item = RegionVid> {
281 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::new)
284 /// True if `r` is classified as an local region.
285 pub fn is_local_free_region(&self, r: RegionVid) -> bool {
286 self.region_classification(r) == Some(RegionClassification::Local)
289 /// Returns the number of universal regions created in any category.
290 pub fn len(&self) -> usize {
294 /// Returns the number of global plus external universal regions.
295 /// For closures, these are the regions that appear free in the
296 /// closure type (versus those bound in the closure
297 /// signature). They are therefore the regions between which the
298 /// closure may impose constraints that its creator must verify.
299 pub fn num_global_and_external_regions(&self) -> usize {
300 self.first_local_index
303 /// Get an iterator over all the early-bound regions that have names.
304 pub fn named_universal_regions<'s>(
306 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> + 's {
307 self.indices.indices.iter().map(|(&r, &v)| (r, v))
310 /// See `UniversalRegionIndices::to_region_vid`.
311 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
312 self.indices.to_region_vid(r)
315 /// As part of the NLL unit tests, you can annotate a function with
316 /// `#[rustc_regions]`, and we will emit information about the region
317 /// inference context and -- in particular -- the external constraints
318 /// that this region imposes on others. The methods in this file
319 /// handle the part about dumping the inference context internal
321 crate fn annotate(&self, tcx: TyCtxt<'_, '_, 'tcx>, err: &mut DiagnosticBuilder<'_>) {
322 match self.defining_ty {
323 DefiningTy::Closure(def_id, substs) => {
325 "defining type: {:?} with closure substs {:#?}",
330 // FIXME: It'd be nice to print the late-bound regions
331 // here, but unfortunately these wind up stored into
332 // tests, and the resulting print-outs include def-ids
333 // and other things that are not stable across tests!
334 // So we just include the region-vid. Annoying.
335 let closure_base_def_id = tcx.closure_base_def_id(def_id);
336 for_each_late_bound_region_defined_on(tcx, closure_base_def_id, |r| {
338 "late-bound region is {:?}",
339 self.to_region_vid(r),
343 DefiningTy::Generator(def_id, substs, _) => {
345 "defining type: {:?} with generator substs {:#?}",
350 // FIXME: As above, we'd like to print out the region
351 // `r` but doing so is not stable across architectures
353 let closure_base_def_id = tcx.closure_base_def_id(def_id);
354 for_each_late_bound_region_defined_on(tcx, closure_base_def_id, |r| {
356 "late-bound region is {:?}",
357 self.to_region_vid(r),
361 DefiningTy::FnDef(def_id, substs) => {
363 "defining type: {:?} with substs {:#?}",
368 DefiningTy::Const(def_id, substs) => {
370 "defining constant type: {:?} with substs {:#?}",
379 struct UniversalRegionsBuilder<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
380 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
383 mir_node_id: ast::NodeId,
384 param_env: ty::ParamEnv<'tcx>,
387 const FR: NLLRegionVariableOrigin = NLLRegionVariableOrigin::FreeRegion;
389 impl<'cx, 'gcx, 'tcx> UniversalRegionsBuilder<'cx, 'gcx, 'tcx> {
390 fn build(self) -> UniversalRegions<'tcx> {
391 debug!("build(mir_def_id={:?})", self.mir_def_id);
393 let param_env = self.param_env;
394 debug!("build: param_env={:?}", param_env);
396 assert_eq!(FIRST_GLOBAL_INDEX, self.infcx.num_region_vars());
398 // Create the "global" region that is always free in all contexts: 'static.
399 let fr_static = self.infcx.next_nll_region_var(FR).to_region_vid();
401 // We've now added all the global regions. The next ones we
402 // add will be external.
403 let first_extern_index = self.infcx.num_region_vars();
405 let defining_ty = self.defining_ty();
406 debug!("build: defining_ty={:?}", defining_ty);
408 let mut indices = self.compute_indices(fr_static, defining_ty);
409 debug!("build: indices={:?}", indices);
411 let closure_base_def_id = self.infcx.tcx.closure_base_def_id(self.mir_def_id);
413 // If this is a closure or generator, then the late-bound regions from the enclosing
414 // function are actually external regions to us. For example, here, 'a is not local
415 // to the closure c (although it is local to the fn foo):
417 // let c = || { let x: &'a u32 = ...; }
419 if self.mir_def_id != closure_base_def_id {
421 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id, &mut indices)
424 let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
426 // "Liberate" the late-bound regions. These correspond to
427 // "local" free regions.
428 let first_local_index = self.infcx.num_region_vars();
429 let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
432 &bound_inputs_and_output,
435 // Converse of above, if this is a function then the late-bound regions declared on its
436 // signature are local to the fn.
437 if self.mir_def_id == closure_base_def_id {
439 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id, &mut indices);
442 let fr_fn_body = self.infcx.next_nll_region_var(FR).to_region_vid();
443 let num_universals = self.infcx.num_region_vars();
445 let (unnormalized_output_ty, unnormalized_input_tys) =
446 inputs_and_output.split_last().unwrap();
449 "build: global regions = {}..{}",
450 FIRST_GLOBAL_INDEX, first_extern_index
453 "build: extern regions = {}..{}",
454 first_extern_index, first_local_index
457 "build: local regions = {}..{}",
458 first_local_index, num_universals
461 let yield_ty = match defining_ty {
462 DefiningTy::Generator(def_id, substs, _) => {
463 Some(substs.yield_ty(def_id, self.infcx.tcx))
476 unnormalized_output_ty,
477 unnormalized_input_tys,
482 /// Returns the "defining type" of the current MIR;
483 /// see `DefiningTy` for details.
484 fn defining_ty(&self) -> DefiningTy<'tcx> {
485 let tcx = self.infcx.tcx;
486 let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id);
488 match tcx.hir.body_owner_kind(self.mir_node_id) {
489 BodyOwnerKind::Fn => {
490 let defining_ty = if self.mir_def_id == closure_base_def_id {
491 tcx.type_of(closure_base_def_id)
493 let tables = tcx.typeck_tables_of(self.mir_def_id);
494 tables.node_id_to_type(self.mir_hir_id)
497 debug!("defining_ty (pre-replacement): {:?}", defining_ty);
499 let defining_ty = self.infcx
500 .replace_free_regions_with_nll_infer_vars(FR, &defining_ty);
502 match defining_ty.sty {
503 ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, substs),
504 ty::Generator(def_id, substs, movability) => {
505 DefiningTy::Generator(def_id, substs, movability)
507 ty::FnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs),
509 tcx.def_span(self.mir_def_id),
510 "expected defining type for `{:?}`: `{:?}`",
517 BodyOwnerKind::Const | BodyOwnerKind::Static(..) => {
518 assert_eq!(closure_base_def_id, self.mir_def_id);
519 let identity_substs = Substs::identity_for_item(tcx, closure_base_def_id);
520 let substs = self.infcx
521 .replace_free_regions_with_nll_infer_vars(FR, &identity_substs);
522 DefiningTy::Const(self.mir_def_id, substs)
527 /// Builds a hashmap that maps from the universal regions that are
528 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
529 /// `RegionVid`). The map returned by this function contains only
530 /// the early-bound regions.
533 fr_static: RegionVid,
534 defining_ty: DefiningTy<'tcx>,
535 ) -> UniversalRegionIndices<'tcx> {
536 let tcx = self.infcx.tcx;
537 let gcx = tcx.global_tcx();
538 let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id);
539 let identity_substs = Substs::identity_for_item(gcx, closure_base_def_id);
540 let fr_substs = match defining_ty {
541 DefiningTy::Closure(_, ClosureSubsts { ref substs })
542 | DefiningTy::Generator(_, GeneratorSubsts { ref substs }, _) => {
543 // In the case of closures, we rely on the fact that
544 // the first N elements in the ClosureSubsts are
545 // inherited from the `closure_base_def_id`.
546 // Therefore, when we zip together (below) with
547 // `identity_substs`, we will get only those regions
548 // that correspond to early-bound regions declared on
549 // the `closure_base_def_id`.
550 assert!(substs.len() >= identity_substs.len());
551 assert_eq!(substs.regions().count(), identity_substs.regions().count());
555 DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs,
558 let global_mapping = iter::once((gcx.types.re_static, fr_static));
559 let subst_mapping = identity_substs
561 .zip(fr_substs.regions().map(|r| r.to_region_vid()));
563 UniversalRegionIndices {
564 indices: global_mapping.chain(subst_mapping).collect(),
568 fn compute_inputs_and_output(
570 indices: &UniversalRegionIndices<'tcx>,
571 defining_ty: DefiningTy<'tcx>,
572 ) -> ty::Binder<&'tcx ty::List<Ty<'tcx>>> {
573 let tcx = self.infcx.tcx;
575 DefiningTy::Closure(def_id, substs) => {
576 assert_eq!(self.mir_def_id, def_id);
577 let closure_sig = substs.closure_sig_ty(def_id, tcx).fn_sig(tcx);
578 let inputs_and_output = closure_sig.inputs_and_output();
579 let closure_ty = tcx.closure_env_ty(def_id, substs).unwrap();
583 |closure_ty, inputs_and_output| {
584 // The "inputs" of the closure in the
585 // signature appear as a tuple. The MIR side
586 // flattens this tuple.
587 let (&output, tuplized_inputs) = inputs_and_output.split_last().unwrap();
588 assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
589 let inputs = match tuplized_inputs[0].sty {
590 ty::Tuple(inputs) => inputs,
591 _ => bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]),
595 iter::once(closure_ty)
596 .chain(inputs.iter().cloned())
597 .chain(iter::once(output)),
603 DefiningTy::Generator(def_id, substs, movability) => {
604 assert_eq!(self.mir_def_id, def_id);
605 let output = substs.return_ty(def_id, tcx);
606 let generator_ty = tcx.mk_generator(def_id, substs, movability);
607 let inputs_and_output = self.infcx.tcx.intern_type_list(&[generator_ty, output]);
608 ty::Binder::dummy(inputs_and_output)
611 DefiningTy::FnDef(def_id, _) => {
612 let sig = tcx.fn_sig(def_id);
613 let sig = indices.fold_to_region_vids(tcx, &sig);
614 sig.inputs_and_output()
617 DefiningTy::Const(def_id, _) => {
618 // For a constant body, there are no inputs, and one
619 // "output" (the type of the constant).
620 assert_eq!(self.mir_def_id, def_id);
621 let ty = tcx.type_of(def_id);
622 let ty = indices.fold_to_region_vids(tcx, &ty);
623 ty::Binder::dummy(tcx.intern_type_list(&[ty]))
629 trait InferCtxtExt<'tcx> {
630 fn replace_free_regions_with_nll_infer_vars<T>(
632 origin: NLLRegionVariableOrigin,
636 T: TypeFoldable<'tcx>;
638 fn replace_bound_regions_with_nll_infer_vars<T>(
640 origin: NLLRegionVariableOrigin,
641 all_outlive_scope: DefId,
642 value: &ty::Binder<T>,
643 indices: &mut UniversalRegionIndices<'tcx>,
646 T: TypeFoldable<'tcx>;
648 fn replace_late_bound_regions_with_nll_infer_vars(
651 indices: &mut UniversalRegionIndices<'tcx>,
655 impl<'cx, 'gcx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'gcx, 'tcx> {
656 fn replace_free_regions_with_nll_infer_vars<T>(
658 origin: NLLRegionVariableOrigin,
662 T: TypeFoldable<'tcx>,
664 self.tcx.fold_regions(value, &mut false, |_region, _depth| {
665 self.next_nll_region_var(origin)
669 fn replace_bound_regions_with_nll_infer_vars<T>(
671 origin: NLLRegionVariableOrigin,
672 all_outlive_scope: DefId,
673 value: &ty::Binder<T>,
674 indices: &mut UniversalRegionIndices<'tcx>,
677 T: TypeFoldable<'tcx>,
680 "replace_bound_regions_with_nll_infer_vars(value={:?}, all_outlive_scope={:?})",
681 value, all_outlive_scope,
683 let (value, _map) = self.tcx.replace_late_bound_regions(value, |br| {
684 debug!("replace_bound_regions_with_nll_infer_vars: br={:?}", br);
685 let liberated_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
686 scope: all_outlive_scope,
689 let region_vid = self.next_nll_region_var(origin);
690 indices.insert_late_bound_region(liberated_region, region_vid.to_region_vid());
692 "replace_bound_regions_with_nll_infer_vars: liberated_region={:?} => {:?}",
693 liberated_region, region_vid
700 /// Finds late-bound regions that do not appear in the parameter listing and adds them to the
701 /// indices vector. Typically, we identify late-bound regions as we process the inputs and
702 /// outputs of the closure/function. However, sometimes there are late-bound regions which do
703 /// not appear in the fn parameters but which are nonetheless in scope. The simplest case of
704 /// this are unused functions, like fn foo<'a>() { } (see eg., #51351). Despite not being used,
705 /// users can still reference these regions (e.g., let x: &'a u32 = &22;), so we need to create
706 /// entries for them and store them in the indices map. This code iterates over the complete
707 /// set of late-bound regions and checks for any that we have not yet seen, adding them to the
709 fn replace_late_bound_regions_with_nll_infer_vars(
712 indices: &mut UniversalRegionIndices<'tcx>,
715 "replace_late_bound_regions_with_nll_infer_vars(mir_def_id={:?})",
718 let closure_base_def_id = self.tcx.closure_base_def_id(mir_def_id);
719 for_each_late_bound_region_defined_on(self.tcx, closure_base_def_id, |r| {
720 debug!("replace_late_bound_regions_with_nll_infer_vars: r={:?}", r);
721 if !indices.indices.contains_key(&r) {
722 let region_vid = self.next_nll_region_var(FR);
723 indices.insert_late_bound_region(r, region_vid.to_region_vid());
729 impl<'tcx> UniversalRegionIndices<'tcx> {
730 /// Initially, the `UniversalRegionIndices` map contains only the
731 /// early-bound regions in scope. Once that is all setup, we come
732 /// in later and instantiate the late-bound regions, and then we
733 /// insert the `ReFree` version of those into the map as
734 /// well. These are used for error reporting.
735 fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
736 debug!("insert_late_bound_region({:?}, {:?})", r, vid);
737 self.indices.insert(r, vid);
740 /// Converts `r` into a local inference variable: `r` can either
741 /// by a `ReVar` (i.e., already a reference to an inference
742 /// variable) or it can be `'static` or some early-bound
743 /// region. This is useful when taking the results from
744 /// type-checking and trait-matching, which may sometimes
745 /// reference those regions from the `ParamEnv`. It is also used
746 /// during initialization. Relies on the `indices` map having been
747 /// fully initialized.
748 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
749 if let ty::ReVar(..) = r {
754 .unwrap_or_else(|| bug!("cannot convert `{:?}` to a region vid", r))
758 /// Replace all free regions in `value` with region vids, as
759 /// returned by `to_region_vid`.
760 pub fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'_, '_, 'tcx>, value: &T) -> T
762 T: TypeFoldable<'tcx>,
764 tcx.fold_regions(value, &mut false, |region, _| {
765 tcx.mk_region(ty::ReVar(self.to_region_vid(region)))
770 /// Iterates over the late-bound regions defined on fn_def_id and
771 /// invokes `f` with the liberated form of each one.
772 fn for_each_late_bound_region_defined_on<'tcx>(
773 tcx: TyCtxt<'_, '_, 'tcx>,
775 mut f: impl FnMut(ty::Region<'tcx>),
777 if let Some(late_bounds) = tcx.is_late_bound_map(fn_def_id.index) {
778 for late_bound in late_bounds.iter() {
780 owner: fn_def_id.index,
781 local_id: *late_bound,
783 let region_node_id = tcx.hir.hir_to_node_id(hir_id);
784 let name = tcx.hir.name(region_node_id).as_interned_str();
785 let region_def_id = tcx.hir.local_def_id(region_node_id);
786 let liberated_region = tcx.mk_region(ty::ReFree(ty::FreeRegion {
788 bound_region: ty::BoundRegion::BrNamed(region_def_id, name),