1 //! Code to extract the universally quantified regions declared on a
2 //! function and the relationships between them. For example:
5 //! fn foo<'a, 'b, 'c: 'b>() { }
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.
12 //! The code in this file doesn't *do anything* with those results; it
13 //! just returns them for other code to use.
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_errors::Diagnostic;
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_hir::lang_items::LangItem;
21 use rustc_hir::{BodyOwnerKind, HirId};
22 use rustc_index::vec::{Idx, IndexVec};
23 use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};
24 use rustc_middle::ty::fold::TypeFoldable;
25 use rustc_middle::ty::{self, InlineConstSubsts, InlineConstSubstsParts, RegionVid, Ty, TyCtxt};
26 use rustc_middle::ty::{InternalSubsts, SubstsRef};
29 use crate::nll::ToRegionVid;
32 pub struct UniversalRegions<'tcx> {
33 indices: UniversalRegionIndices<'tcx>,
35 /// The vid assigned to `'static`
36 pub fr_static: RegionVid,
38 /// A special region vid created to represent the current MIR fn
39 /// body. It will outlive the entire CFG but it will not outlive
40 /// any other universal regions.
41 pub fr_fn_body: RegionVid,
43 /// We create region variables such that they are ordered by their
44 /// `RegionClassification`. The first block are globals, then
45 /// externals, then locals. So, things from:
46 /// - `FIRST_GLOBAL_INDEX..first_extern_index` are global,
47 /// - `first_extern_index..first_local_index` are external,
48 /// - `first_local_index..num_universals` are local.
49 first_extern_index: usize,
51 /// See `first_extern_index`.
52 first_local_index: usize,
54 /// The total number of universal region variables instantiated.
55 num_universals: usize,
57 /// The "defining" type for this function, with all universal
58 /// regions instantiated. For a closure or generator, this is the
59 /// closure type, but for a top-level function it's the `FnDef`.
60 pub defining_ty: DefiningTy<'tcx>,
62 /// The return type of this function, with all regions replaced by
63 /// their universal `RegionVid` equivalents.
65 /// N.B., associated types in this type have not been normalized,
66 /// as the name suggests. =)
67 pub unnormalized_output_ty: Ty<'tcx>,
69 /// The fully liberated input types of this function, with all
70 /// regions replaced by their universal `RegionVid` equivalents.
72 /// N.B., associated types in these types have not been normalized,
73 /// as the name suggests. =)
74 pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
76 pub yield_ty: Option<Ty<'tcx>>,
79 /// The "defining type" for this MIR. The key feature of the "defining
80 /// type" is that it contains the information needed to derive all the
81 /// universal regions that are in scope as well as the types of the
82 /// inputs/output from the MIR. In general, early-bound universal
83 /// regions appear free in the defining type and late-bound regions
84 /// appear bound in the signature.
85 #[derive(Copy, Clone, Debug)]
86 pub enum DefiningTy<'tcx> {
87 /// The MIR is a closure. The signature is found via
88 /// `ClosureSubsts::closure_sig_ty`.
89 Closure(DefId, SubstsRef<'tcx>),
91 /// The MIR is a generator. The signature is that generators take
92 /// no parameters and return the result of
93 /// `ClosureSubsts::generator_return_ty`.
94 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
96 /// The MIR is a fn item with the given `DefId` and substs. The signature
97 /// of the function can be bound then with the `fn_sig` query.
98 FnDef(DefId, SubstsRef<'tcx>),
100 /// The MIR represents some form of constant. The signature then
101 /// is that it has no inputs and a single return value, which is
102 /// the value of the constant.
103 Const(DefId, SubstsRef<'tcx>),
105 /// The MIR represents an inline const. The signature has no inputs and a
106 /// single return value found via `InlineConstSubsts::ty`.
107 InlineConst(DefId, SubstsRef<'tcx>),
110 impl<'tcx> DefiningTy<'tcx> {
111 /// Returns a list of all the upvar types for this MIR. If this is
112 /// not a closure or generator, there are no upvars, and hence it
113 /// will be an empty list. The order of types in this list will
114 /// match up with the upvar order in the HIR, typesystem, and MIR.
115 pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
117 DefiningTy::Closure(_, substs) => Either::Left(substs.as_closure().upvar_tys()),
118 DefiningTy::Generator(_, substs, _) => {
119 Either::Right(Either::Left(substs.as_generator().upvar_tys()))
121 DefiningTy::FnDef(..) | DefiningTy::Const(..) | DefiningTy::InlineConst(..) => {
122 Either::Right(Either::Right(iter::empty()))
127 /// Number of implicit inputs -- notably the "environment"
128 /// parameter for closures -- that appear in MIR but not in the
130 pub fn implicit_inputs(self) -> usize {
132 DefiningTy::Closure(..) | DefiningTy::Generator(..) => 1,
133 DefiningTy::FnDef(..) | DefiningTy::Const(..) | DefiningTy::InlineConst(..) => 0,
137 pub fn is_fn_def(&self) -> bool {
138 matches!(*self, DefiningTy::FnDef(..))
141 pub fn is_const(&self) -> bool {
142 matches!(*self, DefiningTy::Const(..) | DefiningTy::InlineConst(..))
145 pub fn def_id(&self) -> DefId {
147 DefiningTy::Closure(def_id, ..)
148 | DefiningTy::Generator(def_id, ..)
149 | DefiningTy::FnDef(def_id, ..)
150 | DefiningTy::Const(def_id, ..)
151 | DefiningTy::InlineConst(def_id, ..) => def_id,
157 struct UniversalRegionIndices<'tcx> {
158 /// For those regions that may appear in the parameter environment
159 /// ('static and early-bound regions), we maintain a map from the
160 /// `ty::Region` to the internal `RegionVid` we are using. This is
161 /// used because trait matching and type-checking will feed us
162 /// region constraints that reference those regions and we need to
163 /// be able to map them our internal `RegionVid`. This is
164 /// basically equivalent to an `InternalSubsts`, except that it also
165 /// contains an entry for `ReStatic` -- it might be nice to just
166 /// use a substs, and then handle `ReStatic` another way.
167 indices: FxHashMap<ty::Region<'tcx>, RegionVid>,
170 #[derive(Debug, PartialEq)]
171 pub enum RegionClassification {
172 /// A **global** region is one that can be named from
173 /// anywhere. There is only one, `'static`.
176 /// An **external** region is only relevant for
177 /// closures, generators, and inline consts. In that
178 /// case, it refers to regions that are free in the type
179 /// -- basically, something bound in the surrounding context.
181 /// Consider this example:
183 /// ```ignore (pseudo-rust)
184 /// fn foo<'a, 'b>(a: &'a u32, b: &'b u32, c: &'static u32) {
185 /// let closure = for<'x> |x: &'x u32| { .. };
186 /// // ^^^^^^^ pretend this were legal syntax
187 /// // for declaring a late-bound region in
188 /// // a closure signature
192 /// Here, the lifetimes `'a` and `'b` would be **external** to the
195 /// If we are not analyzing a closure/generator/inline-const,
196 /// there are no external lifetimes.
199 /// A **local** lifetime is one about which we know the full set
200 /// of relevant constraints (that is, relationships to other named
201 /// regions). For a closure, this includes any region bound in
202 /// the closure's signature. For a fn item, this includes all
203 /// regions other than global ones.
205 /// Continuing with the example from `External`, if we were
206 /// analyzing the closure, then `'x` would be local (and `'a` and
207 /// `'b` are external). If we are analyzing the function item
208 /// `foo`, then `'a` and `'b` are local (and `'x` is not in
213 const FIRST_GLOBAL_INDEX: usize = 0;
215 impl<'tcx> UniversalRegions<'tcx> {
216 /// Creates a new and fully initialized `UniversalRegions` that
217 /// contains indices for all the free regions found in the given
218 /// MIR -- that is, all the regions that appear in the function's
219 /// signature. This will also compute the relationships that are
220 /// known between those regions.
222 infcx: &InferCtxt<'tcx>,
223 mir_def: ty::WithOptConstParam<LocalDefId>,
224 param_env: ty::ParamEnv<'tcx>,
227 let mir_hir_id = tcx.hir().local_def_id_to_hir_id(mir_def.did);
228 UniversalRegionsBuilder { infcx, mir_def, mir_hir_id, param_env }.build()
231 /// Given a reference to a closure type, extracts all the values
232 /// from its free regions and returns a vector with them. This is
233 /// used when the closure's creator checks that the
234 /// `ClosureRegionRequirements` are met. The requirements from
235 /// `ClosureRegionRequirements` are expressed in terms of
236 /// `RegionVid` entries that map into the returned vector `V`: so
237 /// if the `ClosureRegionRequirements` contains something like
238 /// `'1: '2`, then the caller would impose the constraint that
240 pub fn closure_mapping(
242 closure_substs: SubstsRef<'tcx>,
243 expected_num_vars: usize,
244 typeck_root_def_id: DefId,
245 ) -> IndexVec<RegionVid, ty::Region<'tcx>> {
246 let mut region_mapping = IndexVec::with_capacity(expected_num_vars);
247 region_mapping.push(tcx.lifetimes.re_static);
248 tcx.for_each_free_region(&closure_substs, |fr| {
249 region_mapping.push(fr);
252 for_each_late_bound_region_defined_on(tcx, typeck_root_def_id, |r| {
253 region_mapping.push(r);
257 region_mapping.len(),
259 "index vec had unexpected number of variables"
265 /// Returns `true` if `r` is a member of this set of universal regions.
266 pub fn is_universal_region(&self, r: RegionVid) -> bool {
267 (FIRST_GLOBAL_INDEX..self.num_universals).contains(&r.index())
270 /// Classifies `r` as a universal region, returning `None` if this
271 /// is not a member of this set of universal regions.
272 pub fn region_classification(&self, r: RegionVid) -> Option<RegionClassification> {
273 let index = r.index();
274 if (FIRST_GLOBAL_INDEX..self.first_extern_index).contains(&index) {
275 Some(RegionClassification::Global)
276 } else if (self.first_extern_index..self.first_local_index).contains(&index) {
277 Some(RegionClassification::External)
278 } else if (self.first_local_index..self.num_universals).contains(&index) {
279 Some(RegionClassification::Local)
285 /// Returns an iterator over all the RegionVids corresponding to
286 /// universally quantified free regions.
287 pub fn universal_regions(&self) -> impl Iterator<Item = RegionVid> {
288 (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::new)
291 /// Returns `true` if `r` is classified as an local region.
292 pub fn is_local_free_region(&self, r: RegionVid) -> bool {
293 self.region_classification(r) == Some(RegionClassification::Local)
296 /// Returns the number of universal regions created in any category.
297 pub fn len(&self) -> usize {
301 /// Returns the number of global plus external universal regions.
302 /// For closures, these are the regions that appear free in the
303 /// closure type (versus those bound in the closure
304 /// signature). They are therefore the regions between which the
305 /// closure may impose constraints that its creator must verify.
306 pub fn num_global_and_external_regions(&self) -> usize {
307 self.first_local_index
310 /// Gets an iterator over all the early-bound regions that have names.
311 pub fn named_universal_regions<'s>(
313 ) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> + 's {
314 self.indices.indices.iter().map(|(&r, &v)| (r, v))
317 /// See `UniversalRegionIndices::to_region_vid`.
318 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
319 self.indices.to_region_vid(r)
322 /// As part of the NLL unit tests, you can annotate a function with
323 /// `#[rustc_regions]`, and we will emit information about the region
324 /// inference context and -- in particular -- the external constraints
325 /// that this region imposes on others. The methods in this file
326 /// handle the part about dumping the inference context internal
328 pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
329 match self.defining_ty {
330 DefiningTy::Closure(def_id, substs) => {
332 "defining type: {} with closure substs {:#?}",
333 tcx.def_path_str_with_substs(def_id, substs),
334 &substs[tcx.generics_of(def_id).parent_count..],
337 // FIXME: It'd be nice to print the late-bound regions
338 // here, but unfortunately these wind up stored into
339 // tests, and the resulting print-outs include def-ids
340 // and other things that are not stable across tests!
341 // So we just include the region-vid. Annoying.
342 let typeck_root_def_id = tcx.typeck_root_def_id(def_id);
343 for_each_late_bound_region_defined_on(tcx, typeck_root_def_id, |r| {
344 err.note(&format!("late-bound region is {:?}", self.to_region_vid(r),));
347 DefiningTy::Generator(def_id, substs, _) => {
349 "defining type: {} with generator substs {:#?}",
350 tcx.def_path_str_with_substs(def_id, substs),
351 &substs[tcx.generics_of(def_id).parent_count..],
354 // FIXME: As above, we'd like to print out the region
355 // `r` but doing so is not stable across architectures
357 let typeck_root_def_id = tcx.typeck_root_def_id(def_id);
358 for_each_late_bound_region_defined_on(tcx, typeck_root_def_id, |r| {
359 err.note(&format!("late-bound region is {:?}", self.to_region_vid(r),));
362 DefiningTy::FnDef(def_id, substs) => {
365 tcx.def_path_str_with_substs(def_id, substs),
368 DefiningTy::Const(def_id, substs) => {
370 "defining constant type: {}",
371 tcx.def_path_str_with_substs(def_id, substs),
374 DefiningTy::InlineConst(def_id, substs) => {
376 "defining inline constant type: {}",
377 tcx.def_path_str_with_substs(def_id, substs),
384 struct UniversalRegionsBuilder<'cx, 'tcx> {
385 infcx: &'cx InferCtxt<'tcx>,
386 mir_def: ty::WithOptConstParam<LocalDefId>,
388 param_env: ty::ParamEnv<'tcx>,
391 const FR: NllRegionVariableOrigin = NllRegionVariableOrigin::FreeRegion;
393 impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> {
394 fn build(self) -> UniversalRegions<'tcx> {
395 debug!("build(mir_def={:?})", self.mir_def);
397 let param_env = self.param_env;
398 debug!("build: param_env={:?}", param_env);
400 assert_eq!(FIRST_GLOBAL_INDEX, self.infcx.num_region_vars());
402 // Create the "global" region that is always free in all contexts: 'static.
403 let fr_static = self.infcx.next_nll_region_var(FR).to_region_vid();
405 // We've now added all the global regions. The next ones we
406 // add will be external.
407 let first_extern_index = self.infcx.num_region_vars();
409 let defining_ty = self.defining_ty();
410 debug!("build: defining_ty={:?}", defining_ty);
412 let mut indices = self.compute_indices(fr_static, defining_ty);
413 debug!("build: indices={:?}", indices);
415 let typeck_root_def_id = self.infcx.tcx.typeck_root_def_id(self.mir_def.did.to_def_id());
417 // If this is a 'root' body (not a closure/generator/inline const), then
418 // there are no extern regions, so the local regions start at the same
419 // position as the (empty) sub-list of extern regions
420 let first_local_index = if self.mir_def.did.to_def_id() == typeck_root_def_id {
423 // If this is a closure, generator, or inline-const, then the late-bound regions from the enclosing
424 // function are actually external regions to us. For example, here, 'a is not local
425 // to the closure c (although it is local to the fn foo):
427 // let c = || { let x: &'a u32 = ...; }
430 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def.did, &mut indices);
431 // Any regions created during the execution of `defining_ty` or during the above
432 // late-bound region replacement are all considered 'extern' regions
433 self.infcx.num_region_vars()
436 // "Liberate" the late-bound regions. These correspond to
437 // "local" free regions.
439 let bound_inputs_and_output = self.compute_inputs_and_output(&indices, defining_ty);
441 let inputs_and_output = self.infcx.replace_bound_regions_with_nll_infer_vars(
444 bound_inputs_and_output,
447 // Converse of above, if this is a function then the late-bound regions declared on its
448 // signature are local to the fn.
449 if self.mir_def.did.to_def_id() == typeck_root_def_id {
451 .replace_late_bound_regions_with_nll_infer_vars(self.mir_def.did, &mut indices);
454 let (unnormalized_output_ty, mut unnormalized_input_tys) =
455 inputs_and_output.split_last().unwrap();
457 // C-variadic fns also have a `VaList` input that's not listed in the signature
458 // (as it's created inside the body itself, not passed in from outside).
459 if let DefiningTy::FnDef(def_id, _) = defining_ty {
460 if self.infcx.tcx.fn_sig(def_id).c_variadic() {
461 let va_list_did = self.infcx.tcx.require_lang_item(
463 Some(self.infcx.tcx.def_span(self.mir_def.did)),
468 .mk_region(ty::ReVar(self.infcx.next_nll_region_var(FR).to_region_vid()));
469 let va_list_ty = self
472 .bound_type_of(va_list_did)
473 .subst(self.infcx.tcx, &[region.into()]);
475 unnormalized_input_tys = self.infcx.tcx.mk_type_list(
476 unnormalized_input_tys.iter().copied().chain(iter::once(va_list_ty)),
481 let fr_fn_body = self.infcx.next_nll_region_var(FR).to_region_vid();
482 let num_universals = self.infcx.num_region_vars();
484 debug!("build: global regions = {}..{}", FIRST_GLOBAL_INDEX, first_extern_index);
485 debug!("build: extern regions = {}..{}", first_extern_index, first_local_index);
486 debug!("build: local regions = {}..{}", first_local_index, num_universals);
488 let yield_ty = match defining_ty {
489 DefiningTy::Generator(_, substs, _) => Some(substs.as_generator().yield_ty()),
501 unnormalized_output_ty: *unnormalized_output_ty,
502 unnormalized_input_tys,
507 /// Returns the "defining type" of the current MIR;
508 /// see `DefiningTy` for details.
509 fn defining_ty(&self) -> DefiningTy<'tcx> {
510 let tcx = self.infcx.tcx;
511 let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.did.to_def_id());
513 match tcx.hir().body_owner_kind(self.mir_def.did) {
514 BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
515 let defining_ty = if self.mir_def.did.to_def_id() == typeck_root_def_id {
516 tcx.type_of(typeck_root_def_id)
518 let tables = tcx.typeck(self.mir_def.did);
519 tables.node_type(self.mir_hir_id)
522 debug!("defining_ty (pre-replacement): {:?}", defining_ty);
525 self.infcx.replace_free_regions_with_nll_infer_vars(FR, defining_ty);
527 match *defining_ty.kind() {
528 ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, substs),
529 ty::Generator(def_id, substs, movability) => {
530 DefiningTy::Generator(def_id, substs, movability)
532 ty::FnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs),
534 tcx.def_span(self.mir_def.did),
535 "expected defining type for `{:?}`: `{:?}`",
542 BodyOwnerKind::Const | BodyOwnerKind::Static(..) => {
543 let identity_substs = InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
544 if self.mir_def.did.to_def_id() == typeck_root_def_id {
546 self.infcx.replace_free_regions_with_nll_infer_vars(FR, identity_substs);
547 DefiningTy::Const(self.mir_def.did.to_def_id(), substs)
549 let ty = tcx.typeck(self.mir_def.did).node_type(self.mir_hir_id);
550 let substs = InlineConstSubsts::new(
552 InlineConstSubstsParts { parent_substs: identity_substs, ty },
555 let substs = self.infcx.replace_free_regions_with_nll_infer_vars(FR, substs);
556 DefiningTy::InlineConst(self.mir_def.did.to_def_id(), substs)
562 /// Builds a hashmap that maps from the universal regions that are
563 /// in scope (as a `ty::Region<'tcx>`) to their indices (as a
564 /// `RegionVid`). The map returned by this function contains only
565 /// the early-bound regions.
568 fr_static: RegionVid,
569 defining_ty: DefiningTy<'tcx>,
570 ) -> UniversalRegionIndices<'tcx> {
571 let tcx = self.infcx.tcx;
572 let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.did.to_def_id());
573 let identity_substs = InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
574 let fr_substs = match defining_ty {
575 DefiningTy::Closure(_, ref substs)
576 | DefiningTy::Generator(_, ref substs, _)
577 | DefiningTy::InlineConst(_, ref substs) => {
578 // In the case of closures, we rely on the fact that
579 // the first N elements in the ClosureSubsts are
580 // inherited from the `typeck_root_def_id`.
581 // Therefore, when we zip together (below) with
582 // `identity_substs`, we will get only those regions
583 // that correspond to early-bound regions declared on
584 // the `typeck_root_def_id`.
585 assert!(substs.len() >= identity_substs.len());
586 assert_eq!(substs.regions().count(), identity_substs.regions().count());
590 DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs,
593 let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static));
595 iter::zip(identity_substs.regions(), fr_substs.regions().map(|r| r.to_region_vid()));
597 UniversalRegionIndices { indices: global_mapping.chain(subst_mapping).collect() }
600 fn compute_inputs_and_output(
602 indices: &UniversalRegionIndices<'tcx>,
603 defining_ty: DefiningTy<'tcx>,
604 ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> {
605 let tcx = self.infcx.tcx;
607 DefiningTy::Closure(def_id, substs) => {
608 assert_eq!(self.mir_def.did.to_def_id(), def_id);
609 let closure_sig = substs.as_closure().sig();
610 let inputs_and_output = closure_sig.inputs_and_output();
611 let bound_vars = tcx.mk_bound_variable_kinds(
615 .chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))),
617 let br = ty::BoundRegion {
618 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
621 let env_region = ty::ReLateBound(ty::INNERMOST, br);
622 let closure_ty = tcx.closure_env_ty(def_id, substs, env_region).unwrap();
624 // The "inputs" of the closure in the
625 // signature appear as a tuple. The MIR side
626 // flattens this tuple.
627 let (&output, tuplized_inputs) =
628 inputs_and_output.skip_binder().split_last().unwrap();
629 assert_eq!(tuplized_inputs.len(), 1, "multiple closure inputs");
630 let &ty::Tuple(inputs) = tuplized_inputs[0].kind() else {
631 bug!("closure inputs not a tuple: {:?}", tuplized_inputs[0]);
634 ty::Binder::bind_with_vars(
636 iter::once(closure_ty).chain(inputs).chain(iter::once(output)),
642 DefiningTy::Generator(def_id, substs, movability) => {
643 assert_eq!(self.mir_def.did.to_def_id(), def_id);
644 let resume_ty = substs.as_generator().resume_ty();
645 let output = substs.as_generator().return_ty();
646 let generator_ty = tcx.mk_generator(def_id, substs, movability);
647 let inputs_and_output =
648 self.infcx.tcx.intern_type_list(&[generator_ty, resume_ty, output]);
649 ty::Binder::dummy(inputs_and_output)
652 DefiningTy::FnDef(def_id, _) => {
653 let sig = tcx.fn_sig(def_id);
654 let sig = indices.fold_to_region_vids(tcx, sig);
655 sig.inputs_and_output()
658 DefiningTy::Const(def_id, _) => {
659 // For a constant body, there are no inputs, and one
660 // "output" (the type of the constant).
661 assert_eq!(self.mir_def.did.to_def_id(), def_id);
662 let ty = tcx.type_of(self.mir_def.def_id_for_type_of());
663 let ty = indices.fold_to_region_vids(tcx, ty);
664 ty::Binder::dummy(tcx.intern_type_list(&[ty]))
667 DefiningTy::InlineConst(def_id, substs) => {
668 assert_eq!(self.mir_def.did.to_def_id(), def_id);
669 let ty = substs.as_inline_const().ty();
670 ty::Binder::dummy(tcx.intern_type_list(&[ty]))
676 trait InferCtxtExt<'tcx> {
677 fn replace_free_regions_with_nll_infer_vars<T>(
679 origin: NllRegionVariableOrigin,
683 T: TypeFoldable<'tcx>;
685 fn replace_bound_regions_with_nll_infer_vars<T>(
687 origin: NllRegionVariableOrigin,
688 all_outlive_scope: LocalDefId,
689 value: ty::Binder<'tcx, T>,
690 indices: &mut UniversalRegionIndices<'tcx>,
693 T: TypeFoldable<'tcx>;
695 fn replace_late_bound_regions_with_nll_infer_vars(
697 mir_def_id: LocalDefId,
698 indices: &mut UniversalRegionIndices<'tcx>,
702 impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
703 fn replace_free_regions_with_nll_infer_vars<T>(
705 origin: NllRegionVariableOrigin,
709 T: TypeFoldable<'tcx>,
711 self.tcx.fold_regions(value, |_region, _depth| self.next_nll_region_var(origin))
714 #[instrument(level = "debug", skip(self, indices))]
715 fn replace_bound_regions_with_nll_infer_vars<T>(
717 origin: NllRegionVariableOrigin,
718 all_outlive_scope: LocalDefId,
719 value: ty::Binder<'tcx, T>,
720 indices: &mut UniversalRegionIndices<'tcx>,
723 T: TypeFoldable<'tcx>,
725 let (value, _map) = self.tcx.replace_late_bound_regions(value, |br| {
727 let liberated_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
728 scope: all_outlive_scope.to_def_id(),
729 bound_region: br.kind,
731 let region_vid = self.next_nll_region_var(origin);
732 indices.insert_late_bound_region(liberated_region, region_vid.to_region_vid());
733 debug!(?liberated_region, ?region_vid);
739 /// Finds late-bound regions that do not appear in the parameter listing and adds them to the
740 /// indices vector. Typically, we identify late-bound regions as we process the inputs and
741 /// outputs of the closure/function. However, sometimes there are late-bound regions which do
742 /// not appear in the fn parameters but which are nonetheless in scope. The simplest case of
743 /// this are unused functions, like fn foo<'a>() { } (see e.g., #51351). Despite not being used,
744 /// users can still reference these regions (e.g., let x: &'a u32 = &22;), so we need to create
745 /// entries for them and store them in the indices map. This code iterates over the complete
746 /// set of late-bound regions and checks for any that we have not yet seen, adding them to the
748 #[instrument(skip(self, indices))]
749 fn replace_late_bound_regions_with_nll_infer_vars(
751 mir_def_id: LocalDefId,
752 indices: &mut UniversalRegionIndices<'tcx>,
754 let typeck_root_def_id = self.tcx.typeck_root_def_id(mir_def_id.to_def_id());
755 for_each_late_bound_region_defined_on(self.tcx, typeck_root_def_id, |r| {
757 if !indices.indices.contains_key(&r) {
758 let region_vid = self.next_nll_region_var(FR);
760 indices.insert_late_bound_region(r, region_vid.to_region_vid());
766 impl<'tcx> UniversalRegionIndices<'tcx> {
767 /// Initially, the `UniversalRegionIndices` map contains only the
768 /// early-bound regions in scope. Once that is all setup, we come
769 /// in later and instantiate the late-bound regions, and then we
770 /// insert the `ReFree` version of those into the map as
771 /// well. These are used for error reporting.
772 fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
773 debug!("insert_late_bound_region({:?}, {:?})", r, vid);
774 self.indices.insert(r, vid);
777 /// Converts `r` into a local inference variable: `r` can either
778 /// by a `ReVar` (i.e., already a reference to an inference
779 /// variable) or it can be `'static` or some early-bound
780 /// region. This is useful when taking the results from
781 /// type-checking and trait-matching, which may sometimes
782 /// reference those regions from the `ParamEnv`. It is also used
783 /// during initialization. Relies on the `indices` map having been
784 /// fully initialized.
785 pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
786 if let ty::ReVar(..) = *r {
792 .unwrap_or_else(|| bug!("cannot convert `{:?}` to a region vid", r))
796 /// Replaces all free regions in `value` with region vids, as
797 /// returned by `to_region_vid`.
798 pub fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
800 T: TypeFoldable<'tcx>,
802 tcx.fold_regions(value, |region, _| tcx.mk_region(ty::ReVar(self.to_region_vid(region))))
806 /// Iterates over the late-bound regions defined on fn_def_id and
807 /// invokes `f` with the liberated form of each one.
808 fn for_each_late_bound_region_defined_on<'tcx>(
811 mut f: impl FnMut(ty::Region<'tcx>),
813 if let Some(late_bounds) = tcx.is_late_bound_map(fn_def_id.expect_local()) {
814 for ®ion_def_id in late_bounds.iter() {
815 let name = tcx.item_name(region_def_id.to_def_id());
816 let liberated_region = tcx.mk_region(ty::ReFree(ty::FreeRegion {
818 bound_region: ty::BoundRegionKind::BrNamed(region_def_id.to_def_id(), name),