]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/universal_regions.rs
Auto merge of #68343 - matthiaskrgr:submodule_upd, r=oli-obk
[rust.git] / src / librustc_mir / borrow_check / 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::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;
23 use rustc_hir as hir;
24 use rustc_hir::def_id::DefId;
25 use rustc_hir::{BodyOwnerKind, HirId};
26 use rustc_index::vec::{Idx, IndexVec};
27 use std::iter;
28
29 use crate::borrow_check::nll::ToRegionVid;
30
31 #[derive(Debug)]
32 pub struct UniversalRegions<'tcx> {
33     indices: UniversalRegionIndices<'tcx>,
34
35     /// The vid assigned to `'static`
36     pub fr_static: RegionVid,
37
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,
42
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,
50
51     /// See `first_extern_index`.
52     first_local_index: usize,
53
54     /// The total number of universal region variables instantiated.
55     num_universals: usize,
56
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>,
61
62     /// The return type of this function, with all regions replaced by
63     /// their universal `RegionVid` equivalents.
64     ///
65     /// N.B., associated types in this type have not been normalized,
66     /// as the name suggests. =)
67     pub unnormalized_output_ty: Ty<'tcx>,
68
69     /// The fully liberated input types of this function, with all
70     /// regions replaced by their universal `RegionVid` equivalents.
71     ///
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>],
75
76     pub yield_ty: Option<Ty<'tcx>>,
77 }
78
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>),
90
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),
95
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>),
99
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>),
104 }
105
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 {
112         match self {
113             DefiningTy::Closure(def_id, substs) => {
114                 Either::Left(substs.as_closure().upvar_tys(def_id, tcx))
115             }
116             DefiningTy::Generator(def_id, substs, _) => {
117                 Either::Right(Either::Left(substs.as_generator().upvar_tys(def_id, tcx)))
118             }
119             DefiningTy::FnDef(..) | DefiningTy::Const(..) => {
120                 Either::Right(Either::Right(iter::empty()))
121             }
122         }
123     }
124
125     /// Number of implicit inputs -- notably the "environment"
126     /// parameter for closures -- that appear in MIR but not in the
127     /// user's code.
128     pub fn implicit_inputs(self) -> usize {
129         match self {
130             DefiningTy::Closure(..) | DefiningTy::Generator(..) => 1,
131             DefiningTy::FnDef(..) | DefiningTy::Const(..) => 0,
132         }
133     }
134 }
135
136 #[derive(Debug)]
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>,
148 }
149
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`.
154     Global,
155
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.
159     ///
160     /// Consider this example:
161     ///
162     /// ```
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
168     /// }
169     /// ```
170     ///
171     /// Here, the lifetimes `'a` and `'b` would be **external** to the
172     /// closure.
173     ///
174     /// If we are not analyzing a closure, there are no external
175     /// lifetimes.
176     External,
177
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.
183     ///
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
188     /// scope).
189     Local,
190 }
191
192 const FIRST_GLOBAL_INDEX: usize = 0;
193
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.
200     pub fn new(
201         infcx: &InferCtxt<'_, 'tcx>,
202         mir_def_id: DefId,
203         param_env: ty::ParamEnv<'tcx>,
204     ) -> Self {
205         let tcx = infcx.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()
208     }
209
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
218     /// `V[1]: V[2]`.
219     pub fn closure_mapping(
220         tcx: TyCtxt<'tcx>,
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);
229         });
230
231         for_each_late_bound_region_defined_on(tcx, closure_base_def_id, |r| {
232             region_mapping.push(r);
233         });
234
235         assert_eq!(
236             region_mapping.len(),
237             expected_num_vars,
238             "index vec had unexpected number of variables"
239         );
240
241         region_mapping
242     }
243
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())
247     }
248
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)
259         } else {
260             None
261         }
262     }
263
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)
268     }
269
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)
273     }
274
275     /// Returns the number of universal regions created in any category.
276     pub fn len(&self) -> usize {
277         self.num_universals
278     }
279
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
287     }
288
289     /// Gets an iterator over all the early-bound regions that have names.
290     pub fn named_universal_regions<'s>(
291         &'s self,
292     ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> + 's {
293         self.indices.indices.iter().map(|(&r, &v)| (r, v))
294     }
295
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)
299     }
300
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
306     /// state.
307     crate fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut DiagnosticBuilder<'_>) {
308         match self.defining_ty {
309             DefiningTy::Closure(def_id, substs) => {
310                 err.note(&format!(
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..],
314                 ));
315
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),));
324                 });
325             }
326             DefiningTy::Generator(def_id, substs, _) => {
327                 err.note(&format!(
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..],
331                 ));
332
333                 // FIXME: As above, we'd like to print out the region
334                 // `r` but doing so is not stable across architectures
335                 // and so forth.
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),));
339                 });
340             }
341             DefiningTy::FnDef(def_id, substs) => {
342                 err.note(&format!(
343                     "defining type: {}",
344                     tcx.def_path_str_with_substs(def_id, substs),
345                 ));
346             }
347             DefiningTy::Const(def_id, substs) => {
348                 err.note(&format!(
349                     "defining constant type: {}",
350                     tcx.def_path_str_with_substs(def_id, substs),
351                 ));
352             }
353         }
354     }
355 }
356
357 struct UniversalRegionsBuilder<'cx, 'tcx> {
358     infcx: &'cx InferCtxt<'cx, 'tcx>,
359     mir_def_id: DefId,
360     mir_hir_id: HirId,
361     param_env: ty::ParamEnv<'tcx>,
362 }
363
364 const FR: NLLRegionVariableOrigin = NLLRegionVariableOrigin::FreeRegion;
365
366 impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> {
367     fn build(self) -> UniversalRegions<'tcx> {
368         debug!("build(mir_def_id={:?})", self.mir_def_id);
369
370         let param_env = self.param_env;
371         debug!("build: param_env={:?}", param_env);
372
373         assert_eq!(FIRST_GLOBAL_INDEX, self.infcx.num_region_vars());
374
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();
377
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();
381
382         let defining_ty = self.defining_ty();
383         debug!("build: defining_ty={:?}", defining_ty);
384
385         let mut indices = self.compute_indices(fr_static, defining_ty);
386         debug!("build: indices={:?}", indices);
387
388         let closure_base_def_id = self.infcx.tcx.closure_base_def_id(self.mir_def_id);
389
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):
393         // fn foo<'a>() {
394         //     let c = || { let x: &'a u32 = ...; }
395         // }
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)
398         }
399
400         let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
401
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(
406             FR,
407             self.mir_def_id,
408             &bound_inputs_and_output,
409             &mut indices,
410         );
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 {
414             self.infcx
415                 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def_id, &mut indices);
416         }
417
418         let (unnormalized_output_ty, mut unnormalized_input_tys) =
419             inputs_and_output.split_last().unwrap();
420
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)),
428                 );
429                 let region = self
430                     .infcx
431                     .tcx
432                     .mk_region(ty::ReVar(self.infcx.next_nll_region_var(FR).to_region_vid()));
433                 let va_list_ty =
434                     self.infcx.tcx.type_of(va_list_did).subst(self.infcx.tcx, &[region.into()]);
435
436                 unnormalized_input_tys = self.infcx.tcx.mk_type_list(
437                     unnormalized_input_tys.iter().copied().chain(iter::once(va_list_ty)),
438                 );
439             }
440         }
441
442         let fr_fn_body = self.infcx.next_nll_region_var(FR).to_region_vid();
443         let num_universals = self.infcx.num_region_vars();
444
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);
448
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))
452             }
453             _ => None,
454         };
455
456         UniversalRegions {
457             indices,
458             fr_static,
459             fr_fn_body,
460             first_extern_index,
461             first_local_index,
462             num_universals,
463             defining_ty,
464             unnormalized_output_ty,
465             unnormalized_input_tys,
466             yield_ty: yield_ty,
467         }
468     }
469
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);
475
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)
480                 } else {
481                     let tables = tcx.typeck_tables_of(self.mir_def_id);
482                     tables.node_type(self.mir_hir_id)
483                 };
484
485                 debug!("defining_ty (pre-replacement): {:?}", defining_ty);
486
487                 let defining_ty =
488                     self.infcx.replace_free_regions_with_nll_infer_vars(FR, &defining_ty);
489
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)
494                     }
495                     ty::FnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs),
496                     _ => span_bug!(
497                         tcx.def_span(self.mir_def_id),
498                         "expected defining type for `{:?}`: `{:?}`",
499                         self.mir_def_id,
500                         defining_ty
501                     ),
502                 }
503             }
504
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);
508                 let substs =
509                     self.infcx.replace_free_regions_with_nll_infer_vars(FR, &identity_substs);
510                 DefiningTy::Const(self.mir_def_id, substs)
511             }
512         }
513     }
514
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.
519     fn compute_indices(
520         &self,
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());
538                 substs
539             }
540
541             DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs,
542         };
543
544         let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
545         let subst_mapping =
546             identity_substs.regions().zip(fr_substs.regions().map(|r| r.to_region_vid()));
547
548         UniversalRegionIndices { indices: global_mapping.chain(subst_mapping).collect() }
549     }
550
551     fn compute_inputs_and_output(
552         &self,
553         indices: &UniversalRegionIndices<'tcx>,
554         defining_ty: DefiningTy<'tcx>,
555     ) -> ty::Binder<&'tcx ty::List<Ty<'tcx>>> {
556         let tcx = self.infcx.tcx;
557         match defining_ty {
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]),
572                     };
573
574                     tcx.mk_type_list(
575                         iter::once(closure_ty)
576                             .chain(inputs.iter().map(|k| k.expect_ty()))
577                             .chain(iter::once(output)),
578                     )
579                 })
580             }
581
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)
588             }
589
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()
594             }
595
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]))
603             }
604         }
605     }
606 }
607
608 trait InferCtxtExt<'tcx> {
609     fn replace_free_regions_with_nll_infer_vars<T>(
610         &self,
611         origin: NLLRegionVariableOrigin,
612         value: &T,
613     ) -> T
614     where
615         T: TypeFoldable<'tcx>;
616
617     fn replace_bound_regions_with_nll_infer_vars<T>(
618         &self,
619         origin: NLLRegionVariableOrigin,
620         all_outlive_scope: DefId,
621         value: &ty::Binder<T>,
622         indices: &mut UniversalRegionIndices<'tcx>,
623     ) -> T
624     where
625         T: TypeFoldable<'tcx>;
626
627     fn replace_late_bound_regions_with_nll_infer_vars(
628         &self,
629         mir_def_id: DefId,
630         indices: &mut UniversalRegionIndices<'tcx>,
631     );
632 }
633
634 impl<'cx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'tcx> {
635     fn replace_free_regions_with_nll_infer_vars<T>(
636         &self,
637         origin: NLLRegionVariableOrigin,
638         value: &T,
639     ) -> T
640     where
641         T: TypeFoldable<'tcx>,
642     {
643         self.tcx.fold_regions(value, &mut false, |_region, _depth| self.next_nll_region_var(origin))
644     }
645
646     fn replace_bound_regions_with_nll_infer_vars<T>(
647         &self,
648         origin: NLLRegionVariableOrigin,
649         all_outlive_scope: DefId,
650         value: &ty::Binder<T>,
651         indices: &mut UniversalRegionIndices<'tcx>,
652     ) -> T
653     where
654         T: TypeFoldable<'tcx>,
655     {
656         debug!(
657             "replace_bound_regions_with_nll_infer_vars(value={:?}, all_outlive_scope={:?})",
658             value, all_outlive_scope,
659         );
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,
664                 bound_region: br,
665             }));
666             let region_vid = self.next_nll_region_var(origin);
667             indices.insert_late_bound_region(liberated_region, region_vid.to_region_vid());
668             debug!(
669                 "replace_bound_regions_with_nll_infer_vars: liberated_region={:?} => {:?}",
670                 liberated_region, region_vid
671             );
672             region_vid
673         });
674         value
675     }
676
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
685     /// inputs vector.
686     fn replace_late_bound_regions_with_nll_infer_vars(
687         &self,
688         mir_def_id: DefId,
689         indices: &mut UniversalRegionIndices<'tcx>,
690     ) {
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());
698             }
699         });
700     }
701 }
702
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);
712     }
713
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 {
724             r.to_region_vid()
725         } else {
726             *self
727                 .indices
728                 .get(&r)
729                 .unwrap_or_else(|| bug!("cannot convert `{:?}` to a region vid", r))
730         }
731     }
732
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
736     where
737         T: TypeFoldable<'tcx>,
738     {
739         tcx.fold_regions(value, &mut false, |region, _| {
740             tcx.mk_region(ty::ReVar(self.to_region_vid(region)))
741         })
742     }
743 }
744
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>(
748     tcx: TyCtxt<'tcx>,
749     fn_def_id: DefId,
750     mut f: impl FnMut(ty::Region<'tcx>),
751 ) {
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 {
758                 scope: fn_def_id,
759                 bound_region: ty::BoundRegion::BrNamed(region_def_id, name),
760             }));
761             f(liberated_region);
762         }
763     }
764 }