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::ty::fold::TypeFoldable;
20 use rustc::ty::subst::Substs;
21 use rustc::ty::{self, ClosureSubsts, GeneratorSubsts, RegionVid, Ty, TyCtxt};
22 use rustc::util::nodemap::FxHashMap;
23 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
24 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; and
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 /// NB. 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 /// NB. 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, ty::ClosureSubsts<'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, ty::GeneratorSubsts<'tcx>, hir::GeneratorMovability),
95 /// The MIR is a fn item with the given def-id and substs. The signature
96 /// of the function can be bound then with the `fn_sig` query.
97 FnDef(DefId, &'tcx Substs<'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, &'tcx Substs<'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_decls` field of `Mir`.
110 pub fn upvar_tys(self, tcx: TyCtxt<'_, '_, 'tcx>) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
112 DefiningTy::Closure(def_id, substs) => Either::Left(substs.upvar_tys(def_id, tcx)),
113 DefiningTy::Generator(def_id, substs, _) => {
114 Either::Right(Either::Left(substs.upvar_tys(def_id, tcx)))
116 DefiningTy::FnDef(..) | DefiningTy::Const(..) => {
117 Either::Right(Either::Right(iter::empty()))
122 /// Number of implicit inputs -- notably the "environment"
123 /// parameter for closures -- that appear in MIR but not in the
125 pub fn implicit_inputs(self) -> usize {
127 DefiningTy::Closure(..) | DefiningTy::Generator(..) => 1,
128 DefiningTy::FnDef(..) | DefiningTy::Const(..) => 0,
134 struct UniversalRegionIndices<'tcx> {
135 /// For those regions that may appear in the parameter environment
136 /// ('static and early-bound regions), we maintain a map from the
137 /// `ty::Region` to the internal `RegionVid` we are using. This is
138 /// used because trait matching and type-checking will feed us
139 /// region constraints that reference those regions and we need to
140 /// be able to map them our internal `RegionVid`. This is
141 /// basically equivalent to a `Substs`, except that it also
142 /// contains an entry for `ReStatic` -- it might be nice to just
143 /// use a substs, and then handle `ReStatic` another way.
144 indices: FxHashMap<ty::Region<'tcx>, RegionVid>,
147 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
148 pub enum RegionClassification {
149 /// A **global** region is one that can be named from
150 /// anywhere. There is only one, `'static`.
153 /// An **external** region is only relevant for closures. In that
154 /// case, it refers to regions that are free in the closure type
155 /// -- basically, something bound in the surrounding context.
157 /// Consider this example:
160 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
161 /// let closure = for<'x> |x: &'x u32| { .. };
162 /// ^^^^^^^ pretend this were legal syntax
163 /// for declaring a late-bound region in
164 /// a closure signature
168 /// Here, the lifetimes `'a` and `'b` would be **external** to the
171 /// If we are not analyzing a closure, there are no external
175 /// A **local** lifetime is one about which we know the full set
176 /// of relevant constraints (that is, relationships to other named
177 /// regions). For a closure, this includes any region bound in
178 /// the closure's signature. For a fn item, this includes all
179 /// regions other than global ones.
181 /// Continuing with the example from `External`, if we were
182 /// analyzing the closure, then `'x` would be local (and `'a` and
183 /// `'b` are external). If we are analyzing the function item
184 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
189 const FIRST_GLOBAL_INDEX: usize = 0;
191 impl<'tcx> UniversalRegions<'tcx> {
192 /// Creates a new and fully initialized `UniversalRegions` that
193 /// contains indices for all the free regions found in the given
194 /// MIR -- that is, all the regions that appear in the function's
195 /// signature. This will also compute the relationships that are
196 /// known between those regions.
198 infcx: &InferCtxt<'_, '_, 'tcx>,
200 param_env: ty::ParamEnv<'tcx>,
203 let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).unwrap();
204 let mir_hir_id = tcx.hir().node_to_hir_id(mir_node_id);
205 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(
224 tcx: TyCtxt<'_, '_, 'tcx>,
225 closure_substs: &'tcx Substs<'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.types.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 /// 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 /// 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 /// Get 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, 'gcx: 'tcx, 'tcx: 'cx> {
370 infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
373 mir_node_id: ast::NodeId,
374 param_env: ty::ParamEnv<'tcx>,
377 const FR: NLLRegionVariableOrigin = NLLRegionVariableOrigin::FreeRegion;
379 impl<'cx, 'gcx, 'tcx> UniversalRegionsBuilder<'cx, 'gcx, 'tcx> {
380 fn build(self) -> UniversalRegions<'tcx> {
381 debug!("build(mir_def_id={:?})", self.mir_def_id);
383 let param_env = self.param_env;
384 debug!("build: param_env={:?}", param_env);
386 assert_eq!(FIRST_GLOBAL_INDEX, self.infcx.num_region_vars());
388 // Create the "global" region that is always free in all contexts: 'static.
389 let fr_static = self.infcx.next_nll_region_var(FR).to_region_vid();
391 // We've now added all the global regions. The next ones we
392 // add will be external.
393 let first_extern_index = self.infcx.num_region_vars();
395 let defining_ty = self.defining_ty();
396 debug!("build: defining_ty={:?}", defining_ty);
398 let mut indices = self.compute_indices(fr_static, defining_ty);
399 debug!("build: indices={:?}", indices);
401 let closure_base_def_id = self.infcx.tcx.closure_base_def_id(self.mir_def_id);
403 // If this is a closure or generator, then the late-bound regions from the enclosing
404 // function are actually external regions to us. For example, here, 'a is not local
405 // to the closure c (although it is local to the fn foo):
407 // let c = || { let x: &'a u32 = ...; }
409 if self.mir_def_id != closure_base_def_id {
411 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id, &mut indices)
414 let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
416 // "Liberate" the late-bound regions. These correspond to
417 // "local" free regions.
418 let first_local_index = self.infcx.num_region_vars();
419 let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
422 &bound_inputs_and_output,
425 // Converse of above, if this is a function then the late-bound regions declared on its
426 // signature are local to the fn.
427 if self.mir_def_id == closure_base_def_id {
429 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id, &mut indices);
432 let fr_fn_body = self.infcx.next_nll_region_var(FR).to_region_vid();
433 let num_universals = self.infcx.num_region_vars();
435 let (unnormalized_output_ty, unnormalized_input_tys) =
436 inputs_and_output.split_last().unwrap();
439 "build: global regions = {}..{}",
440 FIRST_GLOBAL_INDEX, first_extern_index
443 "build: extern regions = {}..{}",
444 first_extern_index, first_local_index
447 "build: local regions = {}..{}",
448 first_local_index, num_universals
451 let yield_ty = match defining_ty {
452 DefiningTy::Generator(def_id, substs, _) => {
453 Some(substs.yield_ty(def_id, self.infcx.tcx))
466 unnormalized_output_ty,
467 unnormalized_input_tys,
472 /// Returns the "defining type" of the current MIR;
473 /// see `DefiningTy` for details.
474 fn defining_ty(&self) -> DefiningTy<'tcx> {
475 let tcx = self.infcx.tcx;
476 let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id);
478 match tcx.hir().body_owner_kind(self.mir_node_id) {
479 BodyOwnerKind::Closure |
480 BodyOwnerKind::Fn => {
481 let defining_ty = if self.mir_def_id == closure_base_def_id {
482 tcx.type_of(closure_base_def_id)
484 let tables = tcx.typeck_tables_of(self.mir_def_id);
485 tables.node_id_to_type(self.mir_hir_id)
488 debug!("defining_ty (pre-replacement): {:?}", defining_ty);
490 let defining_ty = self.infcx
491 .replace_free_regions_with_nll_infer_vars(FR, &defining_ty);
493 match defining_ty.sty {
494 ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, substs),
495 ty::Generator(def_id, substs, movability) => {
496 DefiningTy::Generator(def_id, substs, movability)
498 ty::FnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs),
500 tcx.def_span(self.mir_def_id),
501 "expected defining type for `{:?}`: `{:?}`",
508 BodyOwnerKind::Const | BodyOwnerKind::Static(..) => {
509 assert_eq!(closure_base_def_id, self.mir_def_id);
510 let identity_substs = Substs::identity_for_item(tcx, closure_base_def_id);
511 let substs = self.infcx
512 .replace_free_regions_with_nll_infer_vars(FR, &identity_substs);
513 DefiningTy::Const(self.mir_def_id, substs)
518 /// Builds a hashmap that maps from the universal regions that are
519 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
520 /// `RegionVid`). The map returned by this function contains only
521 /// the early-bound regions.
524 fr_static: RegionVid,
525 defining_ty: DefiningTy<'tcx>,
526 ) -> UniversalRegionIndices<'tcx> {
527 let tcx = self.infcx.tcx;
528 let gcx = tcx.global_tcx();
529 let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id);
530 let identity_substs = Substs::identity_for_item(gcx, closure_base_def_id);
531 let fr_substs = match defining_ty {
532 DefiningTy::Closure(_, ClosureSubsts { ref substs })
533 | DefiningTy::Generator(_, GeneratorSubsts { ref substs }, _) => {
534 // In the case of closures, we rely on the fact that
535 // the first N elements in the ClosureSubsts are
536 // inherited from the `closure_base_def_id`.
537 // Therefore, when we zip together (below) with
538 // `identity_substs`, we will get only those regions
539 // that correspond to early-bound regions declared on
540 // the `closure_base_def_id`.
541 assert!(substs.len() >= identity_substs.len());
542 assert_eq!(substs.regions().count(), identity_substs.regions().count());
546 DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs,
549 let global_mapping = iter::once((gcx.types.re_static, fr_static));
550 let subst_mapping = identity_substs
552 .zip(fr_substs.regions().map(|r| r.to_region_vid()));
554 UniversalRegionIndices {
555 indices: global_mapping.chain(subst_mapping).collect(),
559 fn compute_inputs_and_output(
561 indices: &UniversalRegionIndices<'tcx>,
562 defining_ty: DefiningTy<'tcx>,
563 ) -> ty::Binder<&'tcx ty::List<Ty<'tcx>>> {
564 let tcx = self.infcx.tcx;
566 DefiningTy::Closure(def_id, substs) => {
567 assert_eq!(self.mir_def_id, def_id);
568 let closure_sig = substs.closure_sig_ty(def_id, tcx).fn_sig(tcx);
569 let inputs_and_output = closure_sig.inputs_and_output();
570 let closure_ty = tcx.closure_env_ty(def_id, substs).unwrap();
574 |closure_ty, inputs_and_output| {
575 // The "inputs" of the closure in the
576 // signature appear as a tuple. The MIR side
577 // flattens this tuple.
578 let (&output, tuplized_inputs) = inputs_and_output.split_last().unwrap();
579 assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
580 let inputs = match tuplized_inputs[0].sty {
581 ty::Tuple(inputs) => inputs,
582 _ => bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]),
586 iter::once(closure_ty)
587 .chain(inputs.iter().cloned())
588 .chain(iter::once(output)),
594 DefiningTy::Generator(def_id, substs, movability) => {
595 assert_eq!(self.mir_def_id, def_id);
596 let output = substs.return_ty(def_id, tcx);
597 let generator_ty = tcx.mk_generator(def_id, substs, movability);
598 let inputs_and_output = self.infcx.tcx.intern_type_list(&[generator_ty, output]);
599 ty::Binder::dummy(inputs_and_output)
602 DefiningTy::FnDef(def_id, _) => {
603 let sig = tcx.fn_sig(def_id);
604 let sig = indices.fold_to_region_vids(tcx, &sig);
605 sig.inputs_and_output()
608 DefiningTy::Const(def_id, _) => {
609 // For a constant body, there are no inputs, and one
610 // "output" (the type of the constant).
611 assert_eq!(self.mir_def_id, def_id);
612 let ty = tcx.type_of(def_id);
613 let ty = indices.fold_to_region_vids(tcx, &ty);
614 ty::Binder::dummy(tcx.intern_type_list(&[ty]))
620 trait InferCtxtExt<'tcx> {
621 fn replace_free_regions_with_nll_infer_vars<T>(
623 origin: NLLRegionVariableOrigin,
627 T: TypeFoldable<'tcx>;
629 fn replace_bound_regions_with_nll_infer_vars<T>(
631 origin: NLLRegionVariableOrigin,
632 all_outlive_scope: DefId,
633 value: &ty::Binder<T>,
634 indices: &mut UniversalRegionIndices<'tcx>,
637 T: TypeFoldable<'tcx>;
639 fn replace_late_bound_regions_with_nll_infer_vars(
642 indices: &mut UniversalRegionIndices<'tcx>,
646 impl<'cx, 'gcx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'gcx, 'tcx> {
647 fn replace_free_regions_with_nll_infer_vars<T>(
649 origin: NLLRegionVariableOrigin,
653 T: TypeFoldable<'tcx>,
655 self.tcx.fold_regions(value, &mut false, |_region, _depth| {
656 self.next_nll_region_var(origin)
660 fn replace_bound_regions_with_nll_infer_vars<T>(
662 origin: NLLRegionVariableOrigin,
663 all_outlive_scope: DefId,
664 value: &ty::Binder<T>,
665 indices: &mut UniversalRegionIndices<'tcx>,
668 T: TypeFoldable<'tcx>,
671 "replace_bound_regions_with_nll_infer_vars(value={:?}, all_outlive_scope={:?})",
672 value, all_outlive_scope,
674 let (value, _map) = self.tcx.replace_late_bound_regions(value, |br| {
675 debug!("replace_bound_regions_with_nll_infer_vars: br={:?}", br);
676 let liberated_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
677 scope: all_outlive_scope,
680 let region_vid = self.next_nll_region_var(origin);
681 indices.insert_late_bound_region(liberated_region, region_vid.to_region_vid());
683 "replace_bound_regions_with_nll_infer_vars: liberated_region={:?} => {:?}",
684 liberated_region, region_vid
691 /// Finds late-bound regions that do not appear in the parameter listing and adds them to the
692 /// indices vector. Typically, we identify late-bound regions as we process the inputs and
693 /// outputs of the closure/function. However, sometimes there are late-bound regions which do
694 /// not appear in the fn parameters but which are nonetheless in scope. The simplest case of
695 /// this are unused functions, like fn foo<'a>() { } (see eg., #51351). Despite not being used,
696 /// users can still reference these regions (e.g., let x: &'a u32 = &22;), so we need to create
697 /// entries for them and store them in the indices map. This code iterates over the complete
698 /// set of late-bound regions and checks for any that we have not yet seen, adding them to the
700 fn replace_late_bound_regions_with_nll_infer_vars(
703 indices: &mut UniversalRegionIndices<'tcx>,
706 "replace_late_bound_regions_with_nll_infer_vars(mir_def_id={:?})",
709 let closure_base_def_id = self.tcx.closure_base_def_id(mir_def_id);
710 for_each_late_bound_region_defined_on(self.tcx, closure_base_def_id, |r| {
711 debug!("replace_late_bound_regions_with_nll_infer_vars: r={:?}", r);
712 if !indices.indices.contains_key(&r) {
713 let region_vid = self.next_nll_region_var(FR);
714 indices.insert_late_bound_region(r, region_vid.to_region_vid());
720 impl<'tcx> UniversalRegionIndices<'tcx> {
721 /// Initially, the `UniversalRegionIndices` map contains only the
722 /// early-bound regions in scope. Once that is all setup, we come
723 /// in later and instantiate the late-bound regions, and then we
724 /// insert the `ReFree` version of those into the map as
725 /// well. These are used for error reporting.
726 fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
727 debug!("insert_late_bound_region({:?}, {:?})", r, vid);
728 self.indices.insert(r, vid);
731 /// Converts `r` into a local inference variable: `r` can either
732 /// by a `ReVar` (i.e., already a reference to an inference
733 /// variable) or it can be `'static` or some early-bound
734 /// region. This is useful when taking the results from
735 /// type-checking and trait-matching, which may sometimes
736 /// reference those regions from the `ParamEnv`. It is also used
737 /// during initialization. Relies on the `indices` map having been
738 /// fully initialized.
739 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
740 if let ty::ReVar(..) = r {
745 .unwrap_or_else(|| bug!("cannot convert `{:?}` to a region vid", r))
749 /// Replace all free regions in `value` with region vids, as
750 /// returned by `to_region_vid`.
751 pub fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'_, '_, 'tcx>, value: &T) -> T
753 T: TypeFoldable<'tcx>,
755 tcx.fold_regions(value, &mut false, |region, _| {
756 tcx.mk_region(ty::ReVar(self.to_region_vid(region)))
761 /// Iterates over the late-bound regions defined on fn_def_id and
762 /// invokes `f` with the liberated form of each one.
763 fn for_each_late_bound_region_defined_on<'tcx>(
764 tcx: TyCtxt<'_, '_, 'tcx>,
766 mut f: impl FnMut(ty::Region<'tcx>),
768 if let Some(late_bounds) = tcx.is_late_bound_map(fn_def_id.index) {
769 for late_bound in late_bounds.iter() {
771 owner: fn_def_id.index,
772 local_id: *late_bound,
774 let region_node_id = tcx.hir().hir_to_node_id(hir_id);
775 let name = tcx.hir().name(region_node_id).as_interned_str();
776 let region_def_id = tcx.hir().local_def_id(region_node_id);
777 let liberated_region = tcx.mk_region(ty::ReFree(ty::FreeRegion {
779 bound_region: ty::BoundRegion::BrNamed(region_def_id, name),