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