]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/universal_regions.rs
Collect late-bound regions from all closure parents in `closure_mapping`
[rust.git] / compiler / rustc_borrowck / src / universal_regions.rs
1 //! Code to extract the universally quantified regions declared on a
2 //! function and the relationships between them. For example:
3 //!
4 //! ```
5 //! fn foo<'a, 'b, 'c: 'b>() { }
6 //! ```
7 //!
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.
11 //!
12 //! The code in this file doesn't *do anything* with those results; it
13 //! just returns them for other code to use.
14
15 use either::Either;
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_errors::Diagnostic;
18 use rustc_hir as hir;
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_hir::lang_items::LangItem;
21 use rustc_hir::{BodyOwnerKind, HirId};
22 use rustc_index::vec::{Idx, IndexVec};
23 use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};
24 use rustc_middle::ty::fold::TypeFoldable;
25 use rustc_middle::ty::{
26     self, DefIdTree, InlineConstSubsts, InlineConstSubstsParts, RegionVid, Ty, TyCtxt,
27 };
28 use rustc_middle::ty::{InternalSubsts, SubstsRef};
29 use std::iter;
30
31 use crate::nll::ToRegionVid;
32
33 #[derive(Debug)]
34 pub struct UniversalRegions<'tcx> {
35     indices: UniversalRegionIndices<'tcx>,
36
37     /// The vid assigned to `'static`
38     pub fr_static: RegionVid,
39
40     /// A special region vid created to represent the current MIR fn
41     /// body. It will outlive the entire CFG but it will not outlive
42     /// any other universal regions.
43     pub fr_fn_body: RegionVid,
44
45     /// We create region variables such that they are ordered by their
46     /// `RegionClassification`. The first block are globals, then
47     /// externals, then locals. So, things from:
48     /// - `FIRST_GLOBAL_INDEX..first_extern_index` are global,
49     /// - `first_extern_index..first_local_index` are external,
50     /// - `first_local_index..num_universals` are local.
51     first_extern_index: usize,
52
53     /// See `first_extern_index`.
54     first_local_index: usize,
55
56     /// The total number of universal region variables instantiated.
57     num_universals: usize,
58
59     /// The "defining" type for this function, with all universal
60     /// regions instantiated. For a closure or generator, this is the
61     /// closure type, but for a top-level function it's the `FnDef`.
62     pub defining_ty: DefiningTy<'tcx>,
63
64     /// The return type of this function, with all regions replaced by
65     /// their universal `RegionVid` equivalents.
66     ///
67     /// N.B., associated types in this type have not been normalized,
68     /// as the name suggests. =)
69     pub unnormalized_output_ty: Ty<'tcx>,
70
71     /// The fully liberated input types of this function, with all
72     /// regions replaced by their universal `RegionVid` equivalents.
73     ///
74     /// N.B., associated types in these types have not been normalized,
75     /// as the name suggests. =)
76     pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
77
78     pub yield_ty: Option<Ty<'tcx>>,
79 }
80
81 /// The "defining type" for this MIR. The key feature of the "defining
82 /// type" is that it contains the information needed to derive all the
83 /// universal regions that are in scope as well as the types of the
84 /// inputs/output from the MIR. In general, early-bound universal
85 /// regions appear free in the defining type and late-bound regions
86 /// appear bound in the signature.
87 #[derive(Copy, Clone, Debug)]
88 pub enum DefiningTy<'tcx> {
89     /// The MIR is a closure. The signature is found via
90     /// `ClosureSubsts::closure_sig_ty`.
91     Closure(DefId, SubstsRef<'tcx>),
92
93     /// The MIR is a generator. The signature is that generators take
94     /// no parameters and return the result of
95     /// `ClosureSubsts::generator_return_ty`.
96     Generator(DefId, SubstsRef<'tcx>, hir::Movability),
97
98     /// The MIR is a fn item with the given `DefId` and substs. The signature
99     /// of the function can be bound then with the `fn_sig` query.
100     FnDef(DefId, SubstsRef<'tcx>),
101
102     /// The MIR represents some form of constant. The signature then
103     /// is that it has no inputs and a single return value, which is
104     /// the value of the constant.
105     Const(DefId, SubstsRef<'tcx>),
106
107     /// The MIR represents an inline const. The signature has no inputs and a
108     /// single return value found via `InlineConstSubsts::ty`.
109     InlineConst(DefId, SubstsRef<'tcx>),
110 }
111
112 impl<'tcx> DefiningTy<'tcx> {
113     /// Returns a list of all the upvar types for this MIR. If this is
114     /// not a closure or generator, there are no upvars, and hence it
115     /// will be an empty list. The order of types in this list will
116     /// match up with the upvar order in the HIR, typesystem, and MIR.
117     pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
118         match self {
119             DefiningTy::Closure(_, substs) => Either::Left(substs.as_closure().upvar_tys()),
120             DefiningTy::Generator(_, substs, _) => {
121                 Either::Right(Either::Left(substs.as_generator().upvar_tys()))
122             }
123             DefiningTy::FnDef(..) | DefiningTy::Const(..) | DefiningTy::InlineConst(..) => {
124                 Either::Right(Either::Right(iter::empty()))
125             }
126         }
127     }
128
129     /// Number of implicit inputs -- notably the "environment"
130     /// parameter for closures -- that appear in MIR but not in the
131     /// user's code.
132     pub fn implicit_inputs(self) -> usize {
133         match self {
134             DefiningTy::Closure(..) | DefiningTy::Generator(..) => 1,
135             DefiningTy::FnDef(..) | DefiningTy::Const(..) | DefiningTy::InlineConst(..) => 0,
136         }
137     }
138
139     pub fn is_fn_def(&self) -> bool {
140         matches!(*self, DefiningTy::FnDef(..))
141     }
142
143     pub fn is_const(&self) -> bool {
144         matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))
145     }
146
147     pub fn def_id(&self) -> DefId {
148         match *self {
149             DefiningTy::Closure(def_id, ..)
150             | DefiningTy::Generator(def_id, ..)
151             | DefiningTy::FnDef(def_id, ..)
152             | DefiningTy::Const(def_id, ..)
153             | DefiningTy::InlineConst(def_id, ..) => def_id,
154         }
155     }
156 }
157
158 #[derive(Debug)]
159 struct UniversalRegionIndices<'tcx> {
160     /// For those regions that may appear in the parameter environment
161     /// ('static and early-bound regions), we maintain a map from the
162     /// `ty::Region` to the internal `RegionVid` we are using. This is
163     /// used because trait matching and type-checking will feed us
164     /// region constraints that reference those regions and we need to
165     /// be able to map them our internal `RegionVid`. This is
166     /// basically equivalent to an `InternalSubsts`, except that it also
167     /// contains an entry for `ReStatic` -- it might be nice to just
168     /// use a substs, and then handle `ReStatic` another way.
169     indices: FxHashMap<ty::Region<'tcx>, RegionVid>,
170 }
171
172 #[derive(Debug, PartialEq)]
173 pub enum RegionClassification {
174     /// A **global** region is one that can be named from
175     /// anywhere. There is only one, `'static`.
176     Global,
177
178     /// An **external** region is only relevant for
179     /// closures, generators, and inline consts. In that
180     /// case, it refers to regions that are free in the type
181     /// -- basically, something bound in the surrounding context.
182     ///
183     /// Consider this example:
184     ///
185     /// ```ignore (pseudo-rust)
186     /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
187     ///   let closure = for<'x> |x: &'x u32| { .. };
188     ///    //           ^^^^^^^ pretend this were legal syntax
189     ///    //                   for declaring a late-bound region in
190     ///    //                   a closure signature
191     /// }
192     /// ```
193     ///
194     /// Here, the lifetimes `'a` and `'b` would be **external** to the
195     /// closure.
196     ///
197     /// If we are not analyzing a closure/generator/inline-const,
198     /// there are no external lifetimes.
199     External,
200
201     /// A **local** lifetime is one about which we know the full set
202     /// of relevant constraints (that is, relationships to other named
203     /// regions). For a closure, this includes any region bound in
204     /// the closure's signature. For a fn item, this includes all
205     /// regions other than global ones.
206     ///
207     /// Continuing with the example from `External`, if we were
208     /// analyzing the closure, then `'x` would be local (and `'a` and
209     /// `'b` are external). If we are analyzing the function item
210     /// `foo`, then `'a` and `'b` are local (and `'x` is not in
211     /// scope).
212     Local,
213 }
214
215 const FIRST_GLOBAL_INDEX: usize = 0;
216
217 impl<'tcx> UniversalRegions<'tcx> {
218     /// Creates a new and fully initialized `UniversalRegions` that
219     /// contains indices for all the free regions found in the given
220     /// MIR -- that is, all the regions that appear in the function's
221     /// signature. This will also compute the relationships that are
222     /// known between those regions.
223     pub fn new(
224         infcx: &InferCtxt<'tcx>,
225         mir_def: ty::WithOptConstParam<LocalDefId>,
226         param_env: ty::ParamEnv<'tcx>,
227     ) -> Self {
228         let tcx = infcx.tcx;
229         let mir_hir_id = tcx.hir().local_def_id_to_hir_id(mir_def.did);
230         UniversalRegionsBuilder { infcx, mir_def, mir_hir_id, param_env }.build()
231     }
232
233     /// Given a reference to a closure type, extracts all the values
234     /// from its free regions and returns a vector with them. This is
235     /// used when the closure's creator checks that the
236     /// `ClosureRegionRequirements` are met. The requirements from
237     /// `ClosureRegionRequirements` are expressed in terms of
238     /// `RegionVid` entries that map into the returned vector `V`: so
239     /// if the `ClosureRegionRequirements` contains something like
240     /// `'1: '2`, then the caller would impose the constraint that
241     /// `V[1]: V[2]`.
242     pub fn closure_mapping(
243         tcx: TyCtxt<'tcx>,
244         closure_substs: SubstsRef<'tcx>,
245         expected_num_vars: usize,
246         closure_def_id: LocalDefId,
247     ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
248         let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
249         region_mapping.push(tcx.lifetimes.re_static);
250         tcx.for_each_free_region(&closure_substs, |fr| {
251             region_mapping.push(fr);
252         });
253
254         for_each_late_bound_region_in_scope(
255             tcx,
256             tcx.local_parent(closure_def_id),
257             |r| {
258                 region_mapping.push(r);
259             },
260         );
261
262         assert_eq!(
263             region_mapping.len(),
264             expected_num_vars,
265             "index vec had unexpected number of variables"
266         );
267
268         region_mapping
269     }
270
271     /// Returns `true` if `r` is a member of this set of universal regions.
272     pub fn is_universal_region(&self, r: RegionVid) -> bool {
273         (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
274     }
275
276     /// Classifies `r` as a universal region, returning `None` if this
277     /// is not a member of this set of universal regions.
278     pub fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
279         let index = r.index();
280         if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
281             Some(RegionClassification::Global)
282         } else if (self.first_extern_index..self.first_local_index).contains(&index) {
283             Some(RegionClassification::External)
284         } else if (self.first_local_index..self.num_universals).contains(&index) {
285             Some(RegionClassification::Local)
286         } else {
287             None
288         }
289     }
290
291     /// Returns an iterator over all the RegionVids corresponding to
292     /// universally quantified free regions.
293     pub fn universal_regions(&self) -> impl Iterator<Item = RegionVid> {
294         (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::new)
295     }
296
297     /// Returns `true` if `r` is classified as an local region.
298     pub fn is_local_free_region(&self, r: RegionVid) -> bool {
299         self.region_classification(r) == Some(RegionClassification::Local)
300     }
301
302     /// Returns the number of universal regions created in any category.
303     pub fn len(&self) -> usize {
304         self.num_universals
305     }
306
307     /// Returns the number of global plus external universal regions.
308     /// For closures, these are the regions that appear free in the
309     /// closure type (versus those bound in the closure
310     /// signature). They are therefore the regions between which the
311     /// closure may impose constraints that its creator must verify.
312     pub fn num_global_and_external_regions(&self) -> usize {
313         self.first_local_index
314     }
315
316     /// Gets an iterator over all the early-bound regions that have names.
317     pub fn named_universal_regions<'s>(
318         &'s self,
319     ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> + 's {
320         self.indices.indices.iter().map(|(&r, &v)| (r, v))
321     }
322
323     /// See `UniversalRegionIndices::to_region_vid`.
324     pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
325         self.indices.to_region_vid(r)
326     }
327
328     /// As part of the NLL unit tests, you can annotate a function with
329     /// `#[rustc_regions]`, and we will emit information about the region
330     /// inference context and -- in particular -- the external constraints
331     /// that this region imposes on others. The methods in this file
332     /// handle the part about dumping the inference context internal
333     /// state.
334     pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
335         match self.defining_ty {
336             DefiningTy::Closure(def_id, substs) => {
337                 err.note(&format!(
338                     "defining type: {} with closure substs {:#?}",
339                     tcx.def_path_str_with_substs(def_id, substs),
340                     &substs[tcx.generics_of(def_id).parent_count..],
341                 ));
342
343                 // FIXME: It'd be nice to print the late-bound regions
344                 // here, but unfortunately these wind up stored into
345                 // tests, and the resulting print-outs include def-ids
346                 // and other things that are not stable across tests!
347                 // So we just include the region-vid. Annoying.
348                 for_each_late_bound_region_in_scope(tcx, def_id.expect_local(), |r| {
349                     err.note(&format!("late-bound region is {:?}", self.to_region_vid(r)));
350                 });
351             }
352             DefiningTy::Generator(def_id, substs, _) => {
353                 err.note(&format!(
354                     "defining type: {} with generator substs {:#?}",
355                     tcx.def_path_str_with_substs(def_id, substs),
356                     &substs[tcx.generics_of(def_id).parent_count..],
357                 ));
358
359                 // FIXME: As above, we'd like to print out the region
360                 // `r` but doing so is not stable across architectures
361                 // and so forth.
362                 for_each_late_bound_region_in_scope(tcx, def_id.expect_local(), |r| {
363                     err.note(&format!("late-bound region is {:?}", self.to_region_vid(r)));
364                 });
365             }
366             DefiningTy::FnDef(def_id, substs) => {
367                 err.note(&format!(
368                     "defining type: {}",
369                     tcx.def_path_str_with_substs(def_id, substs),
370                 ));
371             }
372             DefiningTy::Const(def_id, substs) => {
373                 err.note(&format!(
374                     "defining constant type: {}",
375                     tcx.def_path_str_with_substs(def_id, substs),
376                 ));
377             }
378             DefiningTy::InlineConst(def_id, substs) => {
379                 err.note(&format!(
380                     "defining inline constant type: {}",
381                     tcx.def_path_str_with_substs(def_id, substs),
382                 ));
383             }
384         }
385     }
386 }
387
388 struct UniversalRegionsBuilder<'cx, 'tcx> {
389     infcx: &'cx InferCtxt<'tcx>,
390     mir_def: ty::WithOptConstParam<LocalDefId>,
391     mir_hir_id: HirId,
392     param_env: ty::ParamEnv<'tcx>,
393 }
394
395 const FR: NllRegionVariableOrigin = NllRegionVariableOrigin::FreeRegion;
396
397 impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> {
398     fn build(self) -> UniversalRegions<'tcx> {
399         debug!("build(mir_def={:?})", self.mir_def);
400
401         let param_env = self.param_env;
402         debug!("build: param_env={:?}", param_env);
403
404         assert_eq!(FIRST_GLOBAL_INDEX, self.infcx.num_region_vars());
405
406         // Create the "global" region that is always free in all contexts: 'static.
407         let fr_static = self.infcx.next_nll_region_var(FR).to_region_vid();
408
409         // We've now added all the global regions. The next ones we
410         // add will be external.
411         let first_extern_index = self.infcx.num_region_vars();
412
413         let defining_ty = self.defining_ty();
414         debug!("build: defining_ty={:?}", defining_ty);
415
416         let mut indices = self.compute_indices(fr_static, defining_ty);
417         debug!("build: indices={:?}", indices);
418
419         let typeck_root_def_id = self.infcx.tcx.typeck_root_def_id(self.mir_def.did.to_def_id());
420
421         // If this is a 'root' body (not a closure/generator/inline const), then
422         // there are no extern regions, so the local regions start at the same
423         // position as the (empty) sub-list of extern regions
424         let first_local_index = if self.mir_def.did.to_def_id() == typeck_root_def_id {
425             first_extern_index
426         } else {
427             // If this is a closure, generator, or inline-const, then the late-bound regions from the enclosing
428             // function/closures are actually external regions to us. For example, here, 'a is not local
429             // to the closure c (although it is local to the fn foo):
430             // fn foo<'a>() {
431             //     let c = || { let x: &'a u32 = ...; }
432             // }
433             self.infcx.replace_late_bound_regions_with_nll_infer_vars(
434                 self.infcx.tcx.local_parent(self.mir_def.did),
435                 &mut indices,
436             );
437             // Any regions created during the execution of `defining_ty` or during the above
438             // late-bound region replacement are all considered 'extern' regions
439             self.infcx.num_region_vars()
440         };
441
442         // "Liberate" the late-bound regions. These correspond to
443         // "local" free regions.
444
445         let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
446
447         let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
448             FR,
449             self.mir_def.did,
450             bound_inputs_and_output,
451             &mut indices,
452         );
453         // Converse of above, if this is a function/closure then the late-bound regions declared on its
454         // signature are local.
455         self.infcx.replace_late_bound_regions_with_nll_infer_vars(self.mir_def.did, &mut indices);
456
457         let (unnormalized_output_ty, mut unnormalized_input_tys) =
458             inputs_and_output.split_last().unwrap();
459
460         // C-variadic fns also have a `VaList` input that's not listed in the signature
461         // (as it's created inside the body itself, not passed in from outside).
462         if let DefiningTy::FnDef(def_id, _) = defining_ty {
463             if self.infcx.tcx.fn_sig(def_id).c_variadic() {
464                 let va_list_did = self.infcx.tcx.require_lang_item(
465                     LangItem::VaList,
466                     Some(self.infcx.tcx.def_span(self.mir_def.did)),
467                 );
468                 let region = self
469                     .infcx
470                     .tcx
471                     .mk_region(ty::ReVar(self.infcx.next_nll_region_var(FR).to_region_vid()));
472                 let va_list_ty = self
473                     .infcx
474                     .tcx
475                     .bound_type_of(va_list_did)
476                     .subst(self.infcx.tcx, &[region.into()]);
477
478                 unnormalized_input_tys = self.infcx.tcx.mk_type_list(
479                     unnormalized_input_tys.iter().copied().chain(iter::once(va_list_ty)),
480                 );
481             }
482         }
483
484         let fr_fn_body = self.infcx.next_nll_region_var(FR).to_region_vid();
485         let num_universals = self.infcx.num_region_vars();
486
487         debug!("build: global regions = {}..{}", FIRST_GLOBAL_INDEX, first_extern_index);
488         debug!("build: extern regions = {}..{}", first_extern_index, first_local_index);
489         debug!("build: local regions  = {}..{}", first_local_index, num_universals);
490
491         let yield_ty = match defining_ty {
492             DefiningTy::Generator(_, substs, _) => Some(substs.as_generator().yield_ty()),
493             _ => None,
494         };
495
496         UniversalRegions {
497             indices,
498             fr_static,
499             fr_fn_body,
500             first_extern_index,
501             first_local_index,
502             num_universals,
503             defining_ty,
504             unnormalized_output_ty: *unnormalized_output_ty,
505             unnormalized_input_tys,
506             yield_ty,
507         }
508     }
509
510     /// Returns the "defining type" of the current MIR;
511     /// see `DefiningTy` for details.
512     fn defining_ty(&self) -> DefiningTy<'tcx> {
513         let tcx = self.infcx.tcx;
514         let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.did.to_def_id());
515
516         match tcx.hir().body_owner_kind(self.mir_def.did) {
517             BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
518                 let defining_ty = if self.mir_def.did.to_def_id() == typeck_root_def_id {
519                     tcx.type_of(typeck_root_def_id)
520                 } else {
521                     let tables = tcx.typeck(self.mir_def.did);
522                     tables.node_type(self.mir_hir_id)
523                 };
524
525                 debug!("defining_ty (pre-replacement): {:?}", defining_ty);
526
527                 let defining_ty =
528                     self.infcx.replace_free_regions_with_nll_infer_vars(FR, defining_ty);
529
530                 match *defining_ty.kind() {
531                     ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, substs),
532                     ty::Generator(def_id, substs, movability) => {
533                         DefiningTy::Generator(def_id, substs, movability)
534                     }
535                     ty::FnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs),
536                     _ => span_bug!(
537                         tcx.def_span(self.mir_def.did),
538                         "expected defining type for `{:?}`: `{:?}`",
539                         self.mir_def.did,
540                         defining_ty
541                     ),
542                 }
543             }
544
545             BodyOwnerKind::Const | BodyOwnerKind::Static(..) => {
546                 let identity_substs = InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
547                 if self.mir_def.did.to_def_id() == typeck_root_def_id {
548                     let substs =
549                         self.infcx.replace_free_regions_with_nll_infer_vars(FR, identity_substs);
550                     DefiningTy::Const(self.mir_def.did.to_def_id(), substs)
551                 } else {
552                     let ty = tcx.typeck(self.mir_def.did).node_type(self.mir_hir_id);
553                     let substs = InlineConstSubsts::new(
554                         tcx,
555                         InlineConstSubstsParts { parent_substs: identity_substs, ty },
556                     )
557                     .substs;
558                     let substs = self.infcx.replace_free_regions_with_nll_infer_vars(FR, substs);
559                     DefiningTy::InlineConst(self.mir_def.did.to_def_id(), substs)
560                 }
561             }
562         }
563     }
564
565     /// Builds a hashmap that maps from the universal regions that are
566     /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
567     /// `RegionVid`). The map returned by this function contains only
568     /// the early-bound regions.
569     fn compute_indices(
570         &self,
571         fr_static: RegionVid,
572         defining_ty: DefiningTy<'tcx>,
573     ) -> UniversalRegionIndices<'tcx> {
574         let tcx = self.infcx.tcx;
575         let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.did.to_def_id());
576         let identity_substs = InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
577         let fr_substs = match defining_ty {
578             DefiningTy::Closure(_, ref substs)
579             | DefiningTy::Generator(_, ref substs, _)
580             | DefiningTy::InlineConst(_, ref substs) => {
581                 // In the case of closures, we rely on the fact that
582                 // the first N elements in the ClosureSubsts are
583                 // inherited from the `typeck_root_def_id`.
584                 // Therefore, when we zip together (below) with
585                 // `identity_substs`, we will get only those regions
586                 // that correspond to early-bound regions declared on
587                 // the `typeck_root_def_id`.
588                 assert!(substs.len() >= identity_substs.len());
589                 assert_eq!(substs.regions().count(), identity_substs.regions().count());
590                 substs
591             }
592
593             DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs,
594         };
595
596         let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
597         let subst_mapping =
598             iter::zip(identity_substs.regions(), fr_substs.regions().map(|r| r.to_region_vid()));
599
600         UniversalRegionIndices { indices: global_mapping.chain(subst_mapping).collect() }
601     }
602
603     fn compute_inputs_and_output(
604         &self,
605         indices: &UniversalRegionIndices<'tcx>,
606         defining_ty: DefiningTy<'tcx>,
607     ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
608         let tcx = self.infcx.tcx;
609         match defining_ty {
610             DefiningTy::Closure(def_id, substs) => {
611                 assert_eq!(self.mir_def.did.to_def_id(), def_id);
612                 let closure_sig = substs.as_closure().sig();
613                 let inputs_and_output = closure_sig.inputs_and_output();
614                 let bound_vars = tcx.mk_bound_variable_kinds(
615                     inputs_and_output
616                         .bound_vars()
617                         .iter()
618                         .chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))),
619                 );
620                 let br = ty::BoundRegion {
621                     var: ty::BoundVar::from_usize(bound_vars.len() - 1),
622                     kind: ty::BrEnv,
623                 };
624                 let env_region = ty::ReLateBound(ty::INNERMOST, br);
625                 let closure_ty = tcx.closure_env_ty(def_id, substs, env_region).unwrap();
626
627                 // The "inputs" of the closure in the
628                 // signature appear as a tuple.  The MIR side
629                 // flattens this tuple.
630                 let (&output, tuplized_inputs) =
631                     inputs_and_output.skip_binder().split_last().unwrap();
632                 assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
633                 let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
634                     bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]);
635                 };
636
637                 ty::Binder::bind_with_vars(
638                     tcx.mk_type_list(
639                         iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
640                     ),
641                     bound_vars,
642                 )
643             }
644
645             DefiningTy::Generator(def_id, substs, movability) => {
646                 assert_eq!(self.mir_def.did.to_def_id(), def_id);
647                 let resume_ty = substs.as_generator().resume_ty();
648                 let output = substs.as_generator().return_ty();
649                 let generator_ty = tcx.mk_generator(def_id, substs, movability);
650                 let inputs_and_output =
651                     self.infcx.tcx.intern_type_list(&[generator_ty, resume_ty, output]);
652                 ty::Binder::dummy(inputs_and_output)
653             }
654
655             DefiningTy::FnDef(def_id, _) => {
656                 let sig = tcx.fn_sig(def_id);
657                 let sig = indices.fold_to_region_vids(tcx, sig);
658                 sig.inputs_and_output()
659             }
660
661             DefiningTy::Const(def_id, _) => {
662                 // For a constant body, there are no inputs, and one
663                 // "output" (the type of the constant).
664                 assert_eq!(self.mir_def.did.to_def_id(), def_id);
665                 let ty = tcx.type_of(self.mir_def.def_id_for_type_of());
666                 let ty = indices.fold_to_region_vids(tcx, ty);
667                 ty::Binder::dummy(tcx.intern_type_list(&[ty]))
668             }
669
670             DefiningTy::InlineConst(def_id, substs) => {
671                 assert_eq!(self.mir_def.did.to_def_id(), def_id);
672                 let ty = substs.as_inline_const().ty();
673                 ty::Binder::dummy(tcx.intern_type_list(&[ty]))
674             }
675         }
676     }
677 }
678
679 trait InferCtxtExt<'tcx> {
680     fn replace_free_regions_with_nll_infer_vars<T>(
681         &self,
682         origin: NllRegionVariableOrigin,
683         value: T,
684     ) -> T
685     where
686         T: TypeFoldable<'tcx>;
687
688     fn replace_bound_regions_with_nll_infer_vars<T>(
689         &self,
690         origin: NllRegionVariableOrigin,
691         all_outlive_scope: LocalDefId,
692         value: ty::Binder<'tcx, T>,
693         indices: &mut UniversalRegionIndices<'tcx>,
694     ) -> T
695     where
696         T: TypeFoldable<'tcx>;
697
698     fn replace_late_bound_regions_with_nll_infer_vars(
699         &self,
700         mir_def_id: LocalDefId,
701         indices: &mut UniversalRegionIndices<'tcx>,
702     );
703 }
704
705 impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
706     fn replace_free_regions_with_nll_infer_vars<T>(
707         &self,
708         origin: NllRegionVariableOrigin,
709         value: T,
710     ) -> T
711     where
712         T: TypeFoldable<'tcx>,
713     {
714         self.tcx.fold_regions(value, |_region, _depth| self.next_nll_region_var(origin))
715     }
716
717     #[instrument(level = "debug", skip(self, indices))]
718     fn replace_bound_regions_with_nll_infer_vars<T>(
719         &self,
720         origin: NllRegionVariableOrigin,
721         all_outlive_scope: LocalDefId,
722         value: ty::Binder<'tcx, T>,
723         indices: &mut UniversalRegionIndices<'tcx>,
724     ) -> T
725     where
726         T: TypeFoldable<'tcx>,
727     {
728         let (value, _map) = self.tcx.replace_late_bound_regions(value, |br| {
729             debug!(?br);
730             let liberated_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
731                 scope: all_outlive_scope.to_def_id(),
732                 bound_region: br.kind,
733             }));
734             let region_vid = self.next_nll_region_var(origin);
735             indices.insert_late_bound_region(liberated_region, region_vid.to_region_vid());
736             debug!(?liberated_region, ?region_vid);
737             region_vid
738         });
739         value
740     }
741
742     /// Finds late-bound regions that do not appear in the parameter listing and adds them to the
743     /// indices vector. Typically, we identify late-bound regions as we process the inputs and
744     /// outputs of the closure/function. However, sometimes there are late-bound regions which do
745     /// not appear in the fn parameters but which are nonetheless in scope. The simplest case of
746     /// this are unused functions, like fn foo<'a>() { } (see e.g., #51351). Despite not being used,
747     /// users can still reference these regions (e.g., let x: &'a u32 = &22;), so we need to create
748     /// entries for them and store them in the indices map. This code iterates over the complete
749     /// set of late-bound regions and checks for any that we have not yet seen, adding them to the
750     /// inputs vector.
751     #[instrument(skip(self, indices))]
752     fn replace_late_bound_regions_with_nll_infer_vars(
753         &self,
754         mir_def_id: LocalDefId,
755         indices: &mut UniversalRegionIndices<'tcx>,
756     ) {
757         for_each_late_bound_region_in_scope(self.tcx, mir_def_id, |r| {
758             debug!(?r);
759             if !indices.indices.contains_key(&r) {
760                 let region_vid = self.next_nll_region_var(FR);
761                 debug!(?region_vid);
762                 indices.insert_late_bound_region(r, region_vid.to_region_vid());
763             }
764         });
765     }
766 }
767
768 impl<'tcx> UniversalRegionIndices<'tcx> {
769     /// Initially, the `UniversalRegionIndices` map contains only the
770     /// early-bound regions in scope. Once that is all setup, we come
771     /// in later and instantiate the late-bound regions, and then we
772     /// insert the `ReFree` version of those into the map as
773     /// well. These are used for error reporting.
774     fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
775         debug!("insert_late_bound_region({:?}, {:?})", r, vid);
776         self.indices.insert(r, vid);
777     }
778
779     /// Converts `r` into a local inference variable: `r` can either
780     /// by a `ReVar` (i.e., already a reference to an inference
781     /// variable) or it can be `'static` or some early-bound
782     /// region. This is useful when taking the results from
783     /// type-checking and trait-matching, which may sometimes
784     /// reference those regions from the `ParamEnv`. It is also used
785     /// during initialization. Relies on the `indices` map having been
786     /// fully initialized.
787     pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
788         if let ty::ReVar(..) = *r {
789             r.to_region_vid()
790         } else {
791             *self
792                 .indices
793                 .get(&r)
794                 .unwrap_or_else(|| bug!("cannot convert `{:?}` to a region vid", r))
795         }
796     }
797
798     /// Replaces all free regions in `value` with region vids, as
799     /// returned by `to_region_vid`.
800     pub fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
801     where
802         T: TypeFoldable<'tcx>,
803     {
804         tcx.fold_regions(value, |region, _| tcx.mk_region(ty::ReVar(self.to_region_vid(region))))
805     }
806 }
807
808 /// Iterates over the late-bound regions defined on fn_def_id and all of its
809 /// parents, up to the typeck root, and invokes `f` with the liberated form
810 /// of each one.
811 fn for_each_late_bound_region_in_scope<'tcx>(
812     tcx: TyCtxt<'tcx>,
813     mut mir_def_id: LocalDefId,
814     mut f: impl FnMut(ty::Region<'tcx>),
815 ) {
816     let typeck_root_def_id = tcx.typeck_root_def_id(mir_def_id.to_def_id());
817
818     // Walk up the tree, collecting late-bound regions until we hit the typeck root
819     loop {
820         for bound_var in tcx.late_bound_vars(tcx.hir().local_def_id_to_hir_id(mir_def_id)) {
821             let ty::BoundVariableKind::Region(bound_region) = bound_var else { continue; };
822             let liberated_region = tcx.mk_region(ty::ReFree(ty::FreeRegion {
823                 scope: mir_def_id.to_def_id(),
824                 bound_region,
825             }));
826             f(liberated_region);
827         }
828
829         if mir_def_id.to_def_id() == typeck_root_def_id {
830             break;
831         } else {
832             mir_def_id = tcx.local_parent(mir_def_id);
833         }
834     }
835 }