Skip to main content

rustc_borrowck/
universal_regions.rs

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

        #[allow(clippy :: suspicious_else_formatting)]
        {
            let __tracing_attr_span;
            let __tracing_attr_guard;
            if ::tracing::Level::DEBUG <=
                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                        ::tracing::Level::DEBUG <=
                            ::tracing::level_filters::LevelFilter::current() ||
                    { false } {
                __tracing_attr_span =
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("replace_free_regions_with_nll_infer_vars",
                                            "rustc_borrowck::universal_regions",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
                                            ::tracing_core::__macro_support::Option::Some(855u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
                                            ::tracing_core::field::FieldSet::new(&["origin", "value"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::SPAN)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let mut interest = ::tracing::subscriber::Interest::never();
                        if ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    { interest = __CALLSITE.interest(); !interest.is_never() }
                                &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest) {
                            let meta = __CALLSITE.metadata();
                            ::tracing::Span::new(meta,
                                &{
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = meta.fields().iter();
                                        meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
                                                                    as &dyn Value))])
                                    })
                        } else {
                            let span =
                                ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                            {};
                            span
                        }
                    };
                __tracing_attr_guard = __tracing_attr_span.enter();
            }

            #[warn(clippy :: suspicious_else_formatting)]
            {

                #[allow(unknown_lints, unreachable_code, clippy ::
                diverging_sub_expression, clippy :: empty_loop, clippy ::
                let_unit_value, clippy :: let_with_type_underscore, clippy ::
                needless_return, clippy :: unreachable)]
                if false {
                    let __tracing_attr_fake_return: T = loop {};
                    return __tracing_attr_fake_return;
                }
                {
                    fold_regions(self.infcx.tcx, value,
                        |region, _depth|
                            {
                                let name = region.get_name_or_anon(self.infcx.tcx);
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:866",
                                                        "rustc_borrowck::universal_regions",
                                                        ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(866u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
                                                        ::tracing_core::field::FieldSet::new(&["region", "name"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                let mut iter = __CALLSITE.metadata().fields().iter();
                                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&debug(&region) as
                                                                            &dyn Value)),
                                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                    ::tracing::__macro_support::Option::Some(&debug(&name) as
                                                                            &dyn Value))])
                                            });
                                    } else { ; }
                                };
                                self.next_nll_region_var(origin, || RegionCtxt::Free(name))
                            })
                }
            }
        }
    }
    fn replace_bound_regions_with_nll_infer_vars<T>(&self,
        all_outlive_scope: LocalDefId, value: ty::Binder<'tcx, T>,
        indices: &UniversalRegionIndices<'tcx>) -> T where
        T: TypeFoldable<TyCtxt<'tcx>> {
        {}

        #[allow(clippy :: suspicious_else_formatting)]
        {
            let __tracing_attr_span;
            let __tracing_attr_guard;
            if ::tracing::Level::DEBUG <=
                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                        ::tracing::Level::DEBUG <=
                            ::tracing::level_filters::LevelFilter::current() ||
                    { false } {
                __tracing_attr_span =
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("replace_bound_regions_with_nll_infer_vars",
                                            "rustc_borrowck::universal_regions",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
                                            ::tracing_core::__macro_support::Option::Some(872u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
                                            ::tracing_core::field::FieldSet::new(&["all_outlive_scope",
                                                            "value"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::SPAN)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let mut interest = ::tracing::subscriber::Interest::never();
                        if ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    { interest = __CALLSITE.interest(); !interest.is_never() }
                                &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest) {
                            let meta = __CALLSITE.metadata();
                            ::tracing::Span::new(meta,
                                &{
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = meta.fields().iter();
                                        meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&all_outlive_scope)
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
                                                                    as &dyn Value))])
                                    })
                        } else {
                            let span =
                                ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                            {};
                            span
                        }
                    };
                __tracing_attr_guard = __tracing_attr_span.enter();
            }

            #[warn(clippy :: suspicious_else_formatting)]
            {

                #[allow(unknown_lints, unreachable_code, clippy ::
                diverging_sub_expression, clippy :: empty_loop, clippy ::
                let_unit_value, clippy :: let_with_type_underscore, clippy ::
                needless_return, clippy :: unreachable)]
                if false {
                    let __tracing_attr_fake_return: T = loop {};
                    return __tracing_attr_fake_return;
                }
                {
                    let (value, _map) =
                        self.tcx.instantiate_bound_regions(value,
                            |br|
                                {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:883",
                                                            "rustc_borrowck::universal_regions",
                                                            ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(883u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
                                                            ::tracing_core::field::FieldSet::new(&["br"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&debug(&br) as
                                                                                &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    let kind =
                                        ty::LateParamRegionKind::from_bound(br.var, br.kind);
                                    let liberated_region =
                                        ty::Region::new_late_param(self.tcx,
                                            all_outlive_scope.to_def_id(), kind);
                                    ty::Region::new_var(self.tcx,
                                        indices.to_region_vid(liberated_region))
                                });
                    value
                }
            }
        }
    }
}#[extension(trait InferCtxtExt<'tcx>)]
854impl<'tcx> BorrowckInferCtxt<'tcx> {
855    #[instrument(skip(self), level = "debug")]
856    fn replace_free_regions_with_nll_infer_vars<T>(
857        &self,
858        origin: NllRegionVariableOrigin<'tcx>,
859        value: T,
860    ) -> T
861    where
862        T: TypeFoldable<TyCtxt<'tcx>>,
863    {
864        fold_regions(self.infcx.tcx, value, |region, _depth| {
865            let name = region.get_name_or_anon(self.infcx.tcx);
866            debug!(?region, ?name);
867
868            self.next_nll_region_var(origin, || RegionCtxt::Free(name))
869        })
870    }
871
872    #[instrument(level = "debug", skip(self, indices))]
873    fn replace_bound_regions_with_nll_infer_vars<T>(
874        &self,
875        all_outlive_scope: LocalDefId,
876        value: ty::Binder<'tcx, T>,
877        indices: &UniversalRegionIndices<'tcx>,
878    ) -> T
879    where
880        T: TypeFoldable<TyCtxt<'tcx>>,
881    {
882        let (value, _map) = self.tcx.instantiate_bound_regions(value, |br| {
883            debug!(?br);
884            let kind = ty::LateParamRegionKind::from_bound(br.var, br.kind);
885            let liberated_region =
886                ty::Region::new_late_param(self.tcx, all_outlive_scope.to_def_id(), kind);
887            ty::Region::new_var(self.tcx, indices.to_region_vid(liberated_region))
888        });
889        value
890    }
891}
892
893impl<'tcx> UniversalRegionIndices<'tcx> {
894    /// Initially, the `UniversalRegionIndices` map contains only the
895    /// early-bound regions in scope. Once that is all setup, we come
896    /// in later and instantiate the late-bound regions, and then we
897    /// insert the `ReLateParam` version of those into the map as
898    /// well. These are used for error reporting.
899    fn insert_late_bound_region(&mut self, r: ty::Region<'tcx>, vid: ty::RegionVid) {
900        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/universal_regions.rs:900",
                        "rustc_borrowck::universal_regions",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/universal_regions.rs"),
                        ::tracing_core::__macro_support::Option::Some(900u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::universal_regions"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("insert_late_bound_region({0:?}, {1:?})",
                                                    r, vid) as &dyn Value))])
            });
    } else { ; }
};debug!("insert_late_bound_region({:?}, {:?})", r, vid);
901        match (&self.indices.insert(r, vid), &None) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(self.indices.insert(r, vid), None);
902    }
903
904    /// Converts `r` into a local inference variable: `r` can either
905    /// be a `ReVar` (i.e., already a reference to an inference
906    /// variable) or it can be `'static` or some early-bound
907    /// region. This is useful when taking the results from
908    /// type-checking and trait-matching, which may sometimes
909    /// reference those regions from the `ParamEnv`. It is also used
910    /// during initialization. Relies on the `indices` map having been
911    /// fully initialized.
912    ///
913    /// Panics if `r` is not a registered universal region, most notably
914    /// if it is a placeholder. Handling placeholders requires access to the
915    /// `MirTypeckRegionConstraints`.
916    fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
917        match r.kind() {
918            ty::ReVar(..) => r.as_var(),
919            ty::ReError(guar) => {
920                self.encountered_re_error.set(Some(guar));
921                // We use the `'static` `RegionVid` because `ReError` doesn't actually exist in the
922                // `UniversalRegionIndices`. This is fine because 1) it is a fallback only used if
923                // errors are being emitted and 2) it leaves the happy path unaffected.
924                self.fr_static
925            }
926            _ => *self
927                .indices
928                .get(&r)
929                .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("cannot convert `{0:?}` to a region vid",
        r))bug!("cannot convert `{:?}` to a region vid", r)),
930        }
931    }
932
933    /// Replaces all free regions in `value` with region vids, as
934    /// returned by `to_region_vid`.
935    fn fold_to_region_vids<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
936    where
937        T: TypeFoldable<TyCtxt<'tcx>>,
938    {
939        fold_regions(tcx, value, |region, _| ty::Region::new_var(tcx, self.to_region_vid(region)))
940    }
941}
942
943/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
944/// parents, up to the typeck root, and invokes `f` with the liberated form
945/// of each one.
946fn for_each_late_bound_region_in_recursive_scope<'tcx>(
947    tcx: TyCtxt<'tcx>,
948    mut mir_def_id: LocalDefId,
949    mut f: impl FnMut(ty::Region<'tcx>),
950) {
951    let typeck_root_def_id = tcx.typeck_root_def_id(mir_def_id.to_def_id());
952
953    // Walk up the tree, collecting late-bound regions until we hit the typeck root
954    loop {
955        for_each_late_bound_region_in_item(tcx, mir_def_id, &mut f);
956
957        if mir_def_id.to_def_id() == typeck_root_def_id {
958            break;
959        } else {
960            mir_def_id = tcx.local_parent(mir_def_id);
961        }
962    }
963}
964
965/// Iterates over the late-bound regions defined on `mir_def_id` and all of its
966/// parents, up to the typeck root, and invokes `f` with the liberated form
967/// of each one.
968fn for_each_late_bound_region_in_item<'tcx>(
969    tcx: TyCtxt<'tcx>,
970    mir_def_id: LocalDefId,
971    mut f: impl FnMut(ty::Region<'tcx>),
972) {
973    let bound_vars = match tcx.def_kind(mir_def_id) {
974        DefKind::Fn | DefKind::AssocFn => {
975            tcx.late_bound_vars(tcx.local_def_id_to_hir_id(mir_def_id))
976        }
977        // We extract the bound vars from the deduced closure signature, since we may have
978        // only deduced that a param in the closure signature is late-bound from a constraint
979        // that we discover during typeck.
980        DefKind::Closure => {
981            let ty = tcx.type_of(mir_def_id).instantiate_identity();
982            match *ty.kind() {
983                ty::Closure(_, args) => args.as_closure().sig().bound_vars(),
984                ty::CoroutineClosure(_, args) => {
985                    args.as_coroutine_closure().coroutine_closure_sig().bound_vars()
986                }
987                ty::Coroutine(_, _) | ty::Error(_) => return,
988                _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("unexpected type for closure: {0}", ty)));
}unreachable!("unexpected type for closure: {ty}"),
989            }
990        }
991        _ => return,
992    };
993
994    for (idx, bound_var) in bound_vars.iter().enumerate() {
995        if let ty::BoundVariableKind::Region(kind) = bound_var {
996            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
997            let liberated_region = ty::Region::new_late_param(tcx, mir_def_id.to_def_id(), kind);
998            f(liberated_region);
999        }
1000    }
1001}