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