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