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