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