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::infer::{InferCtxt, NLLRegionVariableOrigin};
17 use rustc::middle::lang_items;
18 use rustc::ty::fold::TypeFoldable;
19 use rustc::ty::subst::{InternalSubsts, Subst, SubstsRef};
20 use rustc::ty::{self, RegionVid, Ty, TyCtxt};
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_errors::DiagnosticBuilder;
24 use rustc_hir::def_id::DefId;
25 use rustc_hir::{BodyOwnerKind, HirId};
26 use rustc_index::vec::{Idx, IndexVec};
29 use crate::borrow_check::nll::ToRegionVid;
32 pub struct UniversalRegions<'tcx> {
33 indices: UniversalRegionIndices<'tcx>,
35 /// The vid assigned to `'static`
36 pub fr_static: RegionVid,
38 /// A special region vid created to represent the current MIR fn
39 /// body. It will outlive the entire CFG but it will not outlive
40 /// any other universal regions.
41 pub fr_fn_body: RegionVid,
43 /// We create region variables such that they are ordered by their
44 /// `RegionClassification`. The first block are globals, then
45 /// externals, then locals. So, things from:
46 /// - `FIRST_GLOBAL_INDEX..first_extern_index` are global,
47 /// - `first_extern_index..first_local_index` are external,
48 /// - `first_local_index..num_universals` are local.
49 first_extern_index: usize,
51 /// See `first_extern_index`.
52 first_local_index: usize,
54 /// The total number of universal region variables instantiated.
55 num_universals: usize,
57 /// The "defining" type for this function, with all universal
58 /// regions instantiated. For a closure or generator, this is the
59 /// closure type, but for a top-level function it's the `FnDef`.
60 pub defining_ty: DefiningTy<'tcx>,
62 /// The return type of this function, with all regions replaced by
63 /// their universal `RegionVid` equivalents.
65 /// N.B., associated types in this type have not been normalized,
66 /// as the name suggests. =)
67 pub unnormalized_output_ty: Ty<'tcx>,
69 /// The fully liberated input types of this function, with all
70 /// regions replaced by their universal `RegionVid` equivalents.
72 /// N.B., associated types in these types have not been normalized,
73 /// as the name suggests. =)
74 pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
76 pub yield_ty: Option<Ty<'tcx>>,
79 /// The "defining type" for this MIR. The key feature of the "defining
80 /// type" is that it contains the information needed to derive all the
81 /// universal regions that are in scope as well as the types of the
82 /// inputs/output from the MIR. In general, early-bound universal
83 /// regions appear free in the defining type and late-bound regions
84 /// appear bound in the signature.
85 #[derive(Copy, Clone, Debug)]
86 pub enum DefiningTy<'tcx> {
87 /// The MIR is a closure. The signature is found via
88 /// `ClosureSubsts::closure_sig_ty`.
89 Closure(DefId, SubstsRef<'tcx>),
91 /// The MIR is a generator. The signature is that generators take
92 /// no parameters and return the result of
93 /// `ClosureSubsts::generator_return_ty`.
94 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
96 /// The MIR is a fn item with the given `DefId` and substs. The signature
97 /// of the function can be bound then with the `fn_sig` query.
98 FnDef(DefId, SubstsRef<'tcx>),
100 /// The MIR represents some form of constant. The signature then
101 /// is that it has no inputs and a single return value, which is
102 /// the value of the constant.
103 Const(DefId, SubstsRef<'tcx>),
106 impl<'tcx> DefiningTy<'tcx> {
107 /// Returns a list of all the upvar types for this MIR. If this is
108 /// not a closure or generator, there are no upvars, and hence it
109 /// will be an empty list. The order of types in this list will
110 /// match up with the upvar order in the HIR, typesystem, and MIR.
111 pub fn upvar_tys(self, tcx: TyCtxt<'tcx>) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
113 DefiningTy::Closure(def_id, substs) => {
114 Either::Left(substs.as_closure().upvar_tys(def_id, tcx))
116 DefiningTy::Generator(def_id, substs, _) => {
117 Either::Right(Either::Left(substs.as_generator().upvar_tys(def_id, tcx)))
119 DefiningTy::FnDef(..) | DefiningTy::Const(..) => {
120 Either::Right(Either::Right(iter::empty()))
125 /// Number of implicit inputs -- notably the "environment"
126 /// parameter for closures -- that appear in MIR but not in the
128 pub fn implicit_inputs(self) -> usize {
130 DefiningTy::Closure(..) | DefiningTy::Generator(..) => 1,
131 DefiningTy::FnDef(..) | DefiningTy::Const(..) => 0,
137 struct UniversalRegionIndices<'tcx> {
138 /// For those regions that may appear in the parameter environment
139 /// ('static and early-bound regions), we maintain a map from the
140 /// `ty::Region` to the internal `RegionVid` we are using. This is
141 /// used because trait matching and type-checking will feed us
142 /// region constraints that reference those regions and we need to
143 /// be able to map them our internal `RegionVid`. This is
144 /// basically equivalent to a `InternalSubsts`, except that it also
145 /// contains an entry for `ReStatic` -- it might be nice to just
146 /// use a substs, and then handle `ReStatic` another way.
147 indices: FxHashMap<ty::Region<'tcx>, RegionVid>,
150 #[derive(Debug, PartialEq)]
151 pub enum RegionClassification {
152 /// A **global** region is one that can be named from
153 /// anywhere. There is only one, `'static`.
156 /// An **external** region is only relevant for closures. In that
157 /// case, it refers to regions that are free in the closure type
158 /// -- basically, something bound in the surrounding context.
160 /// Consider this example:
163 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
164 /// let closure = for<'x> |x: &'x u32| { .. };
165 /// ^^^^^^^ pretend this were legal syntax
166 /// for declaring a late-bound region in
167 /// a closure signature
171 /// Here, the lifetimes `'a` and `'b` would be **external** to the
174 /// If we are not analyzing a closure, there are no external
178 /// A **local** lifetime is one about which we know the full set
179 /// of relevant constraints (that is, relationships to other named
180 /// regions). For a closure, this includes any region bound in
181 /// the closure's signature. For a fn item, this includes all
182 /// regions other than global ones.
184 /// Continuing with the example from `External`, if we were
185 /// analyzing the closure, then `'x` would be local (and `'a` and
186 /// `'b` are external). If we are analyzing the function item
187 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
192 const FIRST_GLOBAL_INDEX: usize = 0;
194 impl<'tcx> UniversalRegions<'tcx> {
195 /// Creates a new and fully initialized `UniversalRegions` that
196 /// contains indices for all the free regions found in the given
197 /// MIR -- that is, all the regions that appear in the function's
198 /// signature. This will also compute the relationships that are
199 /// known between those regions.
201 infcx: &InferCtxt<'_, 'tcx>,
203 param_env: ty::ParamEnv<'tcx>,
206 let mir_hir_id = tcx.hir().as_local_hir_id(mir_def_id).unwrap();
207 UniversalRegionsBuilder { infcx, mir_def_id, mir_hir_id, param_env }.build()
210 /// Given a reference to a closure type, extracts all the values
211 /// from its free regions and returns a vector with them. This is
212 /// used when the closure's creator checks that the
213 /// `ClosureRegionRequirements` are met. The requirements from
214 /// `ClosureRegionRequirements` are expressed in terms of
215 /// `RegionVid` entries that map into the returned vector `V`: so
216 /// if the `ClosureRegionRequirements` contains something like
217 /// `'1: '2`, then the caller would impose the constraint that
219 pub fn closure_mapping(
221 closure_substs: SubstsRef<'tcx>,
222 expected_num_vars: usize,
223 closure_base_def_id: DefId,
224 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
225 let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
226 region_mapping.push(tcx.lifetimes.re_static);
227 tcx.for_each_free_region(&closure_substs, |fr| {
228 region_mapping.push(fr);
231 for_each_late_bound_region_defined_on(tcx, closure_base_def_id, |r| {
232 region_mapping.push(r);
236 region_mapping.len(),
238 "index vec had unexpected number of variables"
244 /// Returns `true` if `r` is a member of this set of universal regions.
245 pub fn is_universal_region(&self, r: RegionVid) -> bool {
246 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
249 /// Classifies `r` as a universal region, returning `None` if this
250 /// is not a member of this set of universal regions.
251 pub fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
252 let index = r.index();
253 if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
254 Some(RegionClassification::Global)
255 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
256 Some(RegionClassification::External)
257 } else if (self.first_local_index..self.num_universals).contains(&index) {
258 Some(RegionClassification::Local)
264 /// Returns an iterator over all the RegionVids corresponding to
265 /// universally quantified free regions.
266 pub fn universal_regions(&self) -> impl Iterator<Item = RegionVid> {
267 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::new)
270 /// Returns `true` if `r` is classified as an local region.
271 pub fn is_local_free_region(&self, r: RegionVid) -> bool {
272 self.region_classification(r) == Some(RegionClassification::Local)
275 /// Returns the number of universal regions created in any category.
276 pub fn len(&self) -> usize {
280 /// Returns the number of global plus external universal regions.
281 /// For closures, these are the regions that appear free in the
282 /// closure type (versus those bound in the closure
283 /// signature). They are therefore the regions between which the
284 /// closure may impose constraints that its creator must verify.
285 pub fn num_global_and_external_regions(&self) -> usize {
286 self.first_local_index
289 /// Gets an iterator over all the early-bound regions that have names.
290 pub fn named_universal_regions<'s>(
292 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> + 's {
293 self.indices.indices.iter().map(|(&r, &v)| (r, v))
296 /// See `UniversalRegionIndices::to_region_vid`.
297 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
298 self.indices.to_region_vid(r)
301 /// As part of the NLL unit tests, you can annotate a function with
302 /// `#[rustc_regions]`, and we will emit information about the region
303 /// inference context and -- in particular -- the external constraints
304 /// that this region imposes on others. The methods in this file
305 /// handle the part about dumping the inference context internal
307 crate fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut DiagnosticBuilder<'_>) {
308 match self.defining_ty {
309 DefiningTy::Closure(def_id, substs) => {
311 "defining type: {} with closure substs {:#?}",
312 tcx.def_path_str_with_substs(def_id, substs),
313 &substs[tcx.generics_of(def_id).parent_count..],
316 // FIXME: It'd be nice to print the late-bound regions
317 // here, but unfortunately these wind up stored into
318 // tests, and the resulting print-outs include def-ids
319 // and other things that are not stable across tests!
320 // So we just include the region-vid. Annoying.
321 let closure_base_def_id = tcx.closure_base_def_id(def_id);
322 for_each_late_bound_region_defined_on(tcx, closure_base_def_id, |r| {
323 err.note(&format!("late-bound region is {:?}", self.to_region_vid(r),));
326 DefiningTy::Generator(def_id, substs, _) => {
328 "defining type: {} with generator substs {:#?}",
329 tcx.def_path_str_with_substs(def_id, substs),
330 &substs[tcx.generics_of(def_id).parent_count..],
333 // FIXME: As above, we'd like to print out the region
334 // `r` but doing so is not stable across architectures
336 let closure_base_def_id = tcx.closure_base_def_id(def_id);
337 for_each_late_bound_region_defined_on(tcx, closure_base_def_id, |r| {
338 err.note(&format!("late-bound region is {:?}", self.to_region_vid(r),));
341 DefiningTy::FnDef(def_id, substs) => {
344 tcx.def_path_str_with_substs(def_id, substs),
347 DefiningTy::Const(def_id, substs) => {
349 "defining constant type: {}",
350 tcx.def_path_str_with_substs(def_id, substs),
357 struct UniversalRegionsBuilder<'cx, 'tcx> {
358 infcx: &'cx InferCtxt<'cx, 'tcx>,
361 param_env: ty::ParamEnv<'tcx>,
364 const FR: NLLRegionVariableOrigin = NLLRegionVariableOrigin::FreeRegion;
366 impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> {
367 fn build(self) -> UniversalRegions<'tcx> {
368 debug!("build(mir_def_id={:?})", self.mir_def_id);
370 let param_env = self.param_env;
371 debug!("build: param_env={:?}", param_env);
373 assert_eq!(FIRST_GLOBAL_INDEX, self.infcx.num_region_vars());
375 // Create the "global" region that is always free in all contexts: 'static.
376 let fr_static = self.infcx.next_nll_region_var(FR).to_region_vid();
378 // We've now added all the global regions. The next ones we
379 // add will be external.
380 let first_extern_index = self.infcx.num_region_vars();
382 let defining_ty = self.defining_ty();
383 debug!("build: defining_ty={:?}", defining_ty);
385 let mut indices = self.compute_indices(fr_static, defining_ty);
386 debug!("build: indices={:?}", indices);
388 let closure_base_def_id = self.infcx.tcx.closure_base_def_id(self.mir_def_id);
390 // If this is a closure or generator, then the late-bound regions from the enclosing
391 // function are actually external regions to us. For example, here, 'a is not local
392 // to the closure c (although it is local to the fn foo):
394 // let c = || { let x: &'a u32 = ...; }
396 if self.mir_def_id != closure_base_def_id {
397 self.infcx.replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id, &mut indices)
400 let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
402 // "Liberate" the late-bound regions. These correspond to
403 // "local" free regions.
404 let first_local_index = self.infcx.num_region_vars();
405 let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
408 &bound_inputs_and_output,
411 // Converse of above, if this is a function then the late-bound regions declared on its
412 // signature are local to the fn.
413 if self.mir_def_id == closure_base_def_id {
415 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id, &mut indices);
418 let (unnormalized_output_ty, mut unnormalized_input_tys) =
419 inputs_and_output.split_last().unwrap();
421 // C-variadic fns also have a `VaList` input that's not listed in the signature
422 // (as it's created inside the body itself, not passed in from outside).
423 if let DefiningTy::FnDef(def_id, _) = defining_ty {
424 if self.infcx.tcx.fn_sig(def_id).c_variadic() {
425 let va_list_did = self.infcx.tcx.require_lang_item(
426 lang_items::VaListTypeLangItem,
427 Some(self.infcx.tcx.def_span(self.mir_def_id)),
432 .mk_region(ty::ReVar(self.infcx.next_nll_region_var(FR).to_region_vid()));
434 self.infcx.tcx.type_of(va_list_did).subst(self.infcx.tcx, &[region.into()]);
436 unnormalized_input_tys = self.infcx.tcx.mk_type_list(
437 unnormalized_input_tys.iter().copied().chain(iter::once(va_list_ty)),
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 debug!("build: global regions = {}..{}", FIRST_GLOBAL_INDEX, first_extern_index);
446 debug!("build: extern regions = {}..{}", first_extern_index, first_local_index);
447 debug!("build: local regions = {}..{}", first_local_index, num_universals);
449 let yield_ty = match defining_ty {
450 DefiningTy::Generator(def_id, substs, _) => {
451 Some(substs.as_generator().yield_ty(def_id, self.infcx.tcx))
464 unnormalized_output_ty,
465 unnormalized_input_tys,
470 /// Returns the "defining type" of the current MIR;
471 /// see `DefiningTy` for details.
472 fn defining_ty(&self) -> DefiningTy<'tcx> {
473 let tcx = self.infcx.tcx;
474 let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id);
476 match tcx.hir().body_owner_kind(self.mir_hir_id) {
477 BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
478 let defining_ty = if self.mir_def_id == closure_base_def_id {
479 tcx.type_of(closure_base_def_id)
481 let tables = tcx.typeck_tables_of(self.mir_def_id);
482 tables.node_type(self.mir_hir_id)
485 debug!("defining_ty (pre-replacement): {:?}", defining_ty);
488 self.infcx.replace_free_regions_with_nll_infer_vars(FR, &defining_ty);
490 match defining_ty.kind {
491 ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, substs),
492 ty::Generator(def_id, substs, movability) => {
493 DefiningTy::Generator(def_id, substs, movability)
495 ty::FnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs),
497 tcx.def_span(self.mir_def_id),
498 "expected defining type for `{:?}`: `{:?}`",
505 BodyOwnerKind::Const | BodyOwnerKind::Static(..) => {
506 assert_eq!(closure_base_def_id, self.mir_def_id);
507 let identity_substs = InternalSubsts::identity_for_item(tcx, closure_base_def_id);
509 self.infcx.replace_free_regions_with_nll_infer_vars(FR, &identity_substs);
510 DefiningTy::Const(self.mir_def_id, substs)
515 /// Builds a hashmap that maps from the universal regions that are
516 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
517 /// `RegionVid`). The map returned by this function contains only
518 /// the early-bound regions.
521 fr_static: RegionVid,
522 defining_ty: DefiningTy<'tcx>,
523 ) -> UniversalRegionIndices<'tcx> {
524 let tcx = self.infcx.tcx;
525 let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id);
526 let identity_substs = InternalSubsts::identity_for_item(tcx, closure_base_def_id);
527 let fr_substs = match defining_ty {
528 DefiningTy::Closure(_, ref substs) | DefiningTy::Generator(_, ref substs, _) => {
529 // In the case of closures, we rely on the fact that
530 // the first N elements in the ClosureSubsts are
531 // inherited from the `closure_base_def_id`.
532 // Therefore, when we zip together (below) with
533 // `identity_substs`, we will get only those regions
534 // that correspond to early-bound regions declared on
535 // the `closure_base_def_id`.
536 assert!(substs.len() >= identity_substs.len());
537 assert_eq!(substs.regions().count(), identity_substs.regions().count());
541 DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs,
544 let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
546 identity_substs.regions().zip(fr_substs.regions().map(|r| r.to_region_vid()));
548 UniversalRegionIndices { indices: global_mapping.chain(subst_mapping).collect() }
551 fn compute_inputs_and_output(
553 indices: &UniversalRegionIndices<'tcx>,
554 defining_ty: DefiningTy<'tcx>,
555 ) -> ty::Binder<&'tcx ty::List<Ty<'tcx>>> {
556 let tcx = self.infcx.tcx;
558 DefiningTy::Closure(def_id, substs) => {
559 assert_eq!(self.mir_def_id, def_id);
560 let closure_sig = substs.as_closure().sig_ty(def_id, tcx).fn_sig(tcx);
561 let inputs_and_output = closure_sig.inputs_and_output();
562 let closure_ty = tcx.closure_env_ty(def_id, substs).unwrap();
563 ty::Binder::fuse(closure_ty, inputs_and_output, |closure_ty, inputs_and_output| {
564 // The "inputs" of the closure in the
565 // signature appear as a tuple. The MIR side
566 // flattens this tuple.
567 let (&output, tuplized_inputs) = inputs_and_output.split_last().unwrap();
568 assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
569 let inputs = match tuplized_inputs[0].kind {
570 ty::Tuple(inputs) => inputs,
571 _ => bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]),
575 iter::once(closure_ty)
576 .chain(inputs.iter().map(|k| k.expect_ty()))
577 .chain(iter::once(output)),
582 DefiningTy::Generator(def_id, substs, movability) => {
583 assert_eq!(self.mir_def_id, def_id);
584 let output = substs.as_generator().return_ty(def_id, tcx);
585 let generator_ty = tcx.mk_generator(def_id, substs, movability);
586 let inputs_and_output = self.infcx.tcx.intern_type_list(&[generator_ty, output]);
587 ty::Binder::dummy(inputs_and_output)
590 DefiningTy::FnDef(def_id, _) => {
591 let sig = tcx.fn_sig(def_id);
592 let sig = indices.fold_to_region_vids(tcx, &sig);
593 sig.inputs_and_output()
596 DefiningTy::Const(def_id, _) => {
597 // For a constant body, there are no inputs, and one
598 // "output" (the type of the constant).
599 assert_eq!(self.mir_def_id, def_id);
600 let ty = tcx.type_of(def_id);
601 let ty = indices.fold_to_region_vids(tcx, &ty);
602 ty::Binder::dummy(tcx.intern_type_list(&[ty]))
608 trait InferCtxtExt<'tcx> {
609 fn replace_free_regions_with_nll_infer_vars<T>(
611 origin: NLLRegionVariableOrigin,
615 T: TypeFoldable<'tcx>;
617 fn replace_bound_regions_with_nll_infer_vars<T>(
619 origin: NLLRegionVariableOrigin,
620 all_outlive_scope: DefId,
621 value: &ty::Binder<T>,
622 indices: &mut UniversalRegionIndices<'tcx>,
625 T: TypeFoldable<'tcx>;
627 fn replace_late_bound_regions_with_nll_infer_vars(
630 indices: &mut UniversalRegionIndices<'tcx>,
634 impl<'cx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'tcx> {
635 fn replace_free_regions_with_nll_infer_vars<T>(
637 origin: NLLRegionVariableOrigin,
641 T: TypeFoldable<'tcx>,
643 self.tcx.fold_regions(value, &mut false, |_region, _depth| self.next_nll_region_var(origin))
646 fn replace_bound_regions_with_nll_infer_vars<T>(
648 origin: NLLRegionVariableOrigin,
649 all_outlive_scope: DefId,
650 value: &ty::Binder<T>,
651 indices: &mut UniversalRegionIndices<'tcx>,
654 T: TypeFoldable<'tcx>,
657 "replace_bound_regions_with_nll_infer_vars(value={:?}, all_outlive_scope={:?})",
658 value, all_outlive_scope,
660 let (value, _map) = self.tcx.replace_late_bound_regions(value, |br| {
661 debug!("replace_bound_regions_with_nll_infer_vars: br={:?}", br);
662 let liberated_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
663 scope: all_outlive_scope,
666 let region_vid = self.next_nll_region_var(origin);
667 indices.insert_late_bound_region(liberated_region, region_vid.to_region_vid());
669 "replace_bound_regions_with_nll_infer_vars: liberated_region={:?} => {:?}",
670 liberated_region, region_vid
677 /// Finds late-bound regions that do not appear in the parameter listing and adds them to the
678 /// indices vector. Typically, we identify late-bound regions as we process the inputs and
679 /// outputs of the closure/function. However, sometimes there are late-bound regions which do
680 /// not appear in the fn parameters but which are nonetheless in scope. The simplest case of
681 /// this are unused functions, like fn foo<'a>() { } (see e.g., #51351). Despite not being used,
682 /// users can still reference these regions (e.g., let x: &'a u32 = &22;), so we need to create
683 /// entries for them and store them in the indices map. This code iterates over the complete
684 /// set of late-bound regions and checks for any that we have not yet seen, adding them to the
686 fn replace_late_bound_regions_with_nll_infer_vars(
689 indices: &mut UniversalRegionIndices<'tcx>,
691 debug!("replace_late_bound_regions_with_nll_infer_vars(mir_def_id={:?})", mir_def_id);
692 let closure_base_def_id = self.tcx.closure_base_def_id(mir_def_id);
693 for_each_late_bound_region_defined_on(self.tcx, closure_base_def_id, |r| {
694 debug!("replace_late_bound_regions_with_nll_infer_vars: r={:?}", r);
695 if !indices.indices.contains_key(&r) {
696 let region_vid = self.next_nll_region_var(FR);
697 indices.insert_late_bound_region(r, region_vid.to_region_vid());
703 impl<'tcx> UniversalRegionIndices<'tcx> {
704 /// Initially, the `UniversalRegionIndices` map contains only the
705 /// early-bound regions in scope. Once that is all setup, we come
706 /// in later and instantiate the late-bound regions, and then we
707 /// insert the `ReFree` version of those into the map as
708 /// well. These are used for error reporting.
709 fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
710 debug!("insert_late_bound_region({:?}, {:?})", r, vid);
711 self.indices.insert(r, vid);
714 /// Converts `r` into a local inference variable: `r` can either
715 /// by a `ReVar` (i.e., already a reference to an inference
716 /// variable) or it can be `'static` or some early-bound
717 /// region. This is useful when taking the results from
718 /// type-checking and trait-matching, which may sometimes
719 /// reference those regions from the `ParamEnv`. It is also used
720 /// during initialization. Relies on the `indices` map having been
721 /// fully initialized.
722 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
723 if let ty::ReVar(..) = r {
729 .unwrap_or_else(|| bug!("cannot convert `{:?}` to a region vid", r))
733 /// Replaces all free regions in `value` with region vids, as
734 /// returned by `to_region_vid`.
735 pub fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: &T) -> T
737 T: TypeFoldable<'tcx>,
739 tcx.fold_regions(value, &mut false, |region, _| {
740 tcx.mk_region(ty::ReVar(self.to_region_vid(region)))
745 /// Iterates over the late-bound regions defined on fn_def_id and
746 /// invokes `f` with the liberated form of each one.
747 fn for_each_late_bound_region_defined_on<'tcx>(
750 mut f: impl FnMut(ty::Region<'tcx>),
752 if let Some(late_bounds) = tcx.is_late_bound_map(fn_def_id.index) {
753 for late_bound in late_bounds.iter() {
754 let hir_id = HirId { owner: fn_def_id.index, local_id: *late_bound };
755 let name = tcx.hir().name(hir_id);
756 let region_def_id = tcx.hir().local_def_id(hir_id);
757 let liberated_region = tcx.mk_region(ty::ReFree(ty::FreeRegion {
759 bound_region: ty::BoundRegion::BrNamed(region_def_id, name),