Skip to main content

rustc_borrowck/type_check/
mod.rs

1//! This pass type-checks the MIR to ensure it is not broken.
2
3use std::rc::Rc;
4use std::{fmt, iter, mem};
5
6use rustc_abi::FieldIdx;
7use rustc_data_structures::frozen::Frozen;
8use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
9use rustc_errors::ErrorGuaranteed;
10use rustc_hir as hir;
11use rustc_hir::def::DefKind;
12use rustc_hir::def_id::LocalDefId;
13use rustc_hir::lang_items::LangItem;
14use rustc_index::{IndexSlice, IndexVec};
15use rustc_infer::infer::canonical::QueryRegionConstraints;
16use rustc_infer::infer::outlives::env::RegionBoundPairs;
17use rustc_infer::infer::region_constraints::RegionConstraintData;
18use rustc_infer::infer::{
19    BoundRegionConversionTime, InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin,
20};
21use rustc_infer::traits::PredicateObligations;
22use rustc_middle::bug;
23use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
24use rustc_middle::mir::*;
25use rustc_middle::traits::query::NoSolution;
26use rustc_middle::ty::adjustment::PointerCoercion;
27use rustc_middle::ty::cast::CastTy;
28use rustc_middle::ty::{
29    self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, CoroutineArgsExt,
30    GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, UserArgs, UserTypeAnnotationIndex, fold_regions,
31};
32use rustc_mir_dataflow::move_paths::MoveData;
33use rustc_mir_dataflow::points::DenseLocationMap;
34use rustc_span::def_id::CRATE_DEF_ID;
35use rustc_span::{Span, Spanned, sym};
36use rustc_trait_selection::infer::InferCtxtExt;
37use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
38use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
39use tracing::{debug, instrument, trace};
40
41use crate::borrow_set::BorrowSet;
42use crate::constraints::{OutlivesConstraint, OutlivesConstraintSet};
43use crate::diagnostics::UniverseInfo;
44use crate::polonius::PoloniusContext;
45use crate::polonius::legacy::{PoloniusFacts, PoloniusLocationTable};
46use crate::region_infer::TypeTest;
47use crate::region_infer::values::{LivenessValues, PlaceholderIndex, PlaceholderIndices};
48use crate::session_diagnostics::{MoveUnsized, SimdIntrinsicArgConst};
49use crate::type_check::free_region_relations::{CreateResult, UniversalRegionRelations};
50use crate::universal_regions::{DefiningTy, UniversalRegions};
51use crate::{BorrowCheckRootCtxt, BorrowckInferCtxt, DeferredClosureRequirements, path_utils};
52
53macro_rules! span_mirbug {
54    ($context:expr, $elem:expr, $($message:tt)*) => ({
55        $crate::type_check::mirbug(
56            $context.tcx(),
57            $context.last_span,
58            format!(
59                "broken MIR in {:?} ({:?}): {}",
60                $context.body().source.def_id(),
61                $elem,
62                format_args!($($message)*),
63            ),
64        )
65    })
66}
67
68pub(crate) mod canonical;
69pub(crate) mod constraint_conversion;
70pub(crate) mod free_region_relations;
71mod input_output;
72pub(crate) mod liveness;
73mod relate_tys;
74
75/// Type checks the given `mir` in the context of the inference
76/// context `infcx`. Returns any region constraints that have yet to
77/// be proven. This result includes liveness constraints that
78/// ensure that regions appearing in the types of all local variables
79/// are live at all points where that local variable may later be
80/// used.
81///
82/// This phase of type-check ought to be infallible -- this is because
83/// the original, HIR-based type-check succeeded. So if any errors
84/// occur here, we will get a `bug!` reported.
85///
86/// # Parameters
87///
88/// - `infcx` -- inference context to use
89/// - `body` -- MIR body to type-check
90/// - `promoted` -- map of promoted constants within `body`
91/// - `universal_regions` -- the universal regions from `body`s function signature
92/// - `location_table` -- for datalog polonius, the map between `Location`s and `RichLocation`s
93/// - `borrow_set` -- information about borrows occurring in `body`
94/// - `polonius_facts` -- when using Polonius, this is the generated set of Polonius facts
95/// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
96/// - `location_map` -- map between MIR `Location` and `PointIndex`
97pub(crate) fn type_check<'tcx>(
98    root_cx: &BorrowCheckRootCtxt<'tcx>,
99    infcx: &BorrowckInferCtxt<'tcx>,
100    body: &Body<'tcx>,
101    promoted: &IndexSlice<Promoted, Body<'tcx>>,
102    universal_regions: UniversalRegions<'tcx>,
103    location_table: &PoloniusLocationTable,
104    borrow_set: &BorrowSet<'tcx>,
105    polonius_facts: &mut Option<PoloniusFacts>,
106    move_data: &MoveData<'tcx>,
107    location_map: Rc<DenseLocationMap>,
108) -> MirTypeckResults<'tcx> {
109    let mut constraints = MirTypeckRegionConstraints {
110        placeholder_indices: PlaceholderIndices::default(),
111        placeholder_index_to_region: IndexVec::default(),
112        liveness_constraints: LivenessValues::with_specific_points(Rc::clone(&location_map)),
113        outlives_constraints: OutlivesConstraintSet::default(),
114        type_tests: Vec::default(),
115        universe_causes: FxIndexMap::default(),
116    };
117
118    let CreateResult {
119        universal_region_relations,
120        region_bound_pairs,
121        normalized_inputs_and_output,
122        known_type_outlives_obligations,
123    } = free_region_relations::create(infcx, universal_regions, &mut constraints);
124
125    {
126        // Scope these variables so it's clear they're not used later
127        let pre_obligations = infcx.take_registered_region_obligations();
128        if !pre_obligations.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("there should be no incoming region obligations = {0:#?}",
                pre_obligations));
    }
};assert!(
129            pre_obligations.is_empty(),
130            "there should be no incoming region obligations = {pre_obligations:#?}",
131        );
132        let pre_assumptions = infcx.take_registered_region_assumptions();
133        if !pre_assumptions.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("there should be no incoming region assumptions = {0:#?}",
                pre_assumptions));
    }
};assert!(
134            pre_assumptions.is_empty(),
135            "there should be no incoming region assumptions = {pre_assumptions:#?}",
136        );
137    }
138
139    {
    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/type_check/mod.rs:139",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(139u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["normalized_inputs_and_output"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&normalized_inputs_and_output)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?normalized_inputs_and_output);
140
141    let polonius_context = if infcx.tcx.sess.opts.unstable_opts.polonius.is_next_enabled() {
142        Some(PoloniusContext::default())
143    } else {
144        None
145    };
146
147    let mut deferred_closure_requirements = Default::default();
148    let mut typeck = TypeChecker {
149        root_cx,
150        infcx,
151        last_span: body.span,
152        body,
153        promoted,
154        user_type_annotations: &body.user_type_annotations,
155        region_bound_pairs: &region_bound_pairs,
156        known_type_outlives_obligations: &known_type_outlives_obligations,
157        reported_errors: Default::default(),
158        universal_regions: &universal_region_relations.universal_regions,
159        location_table,
160        polonius_facts,
161        borrow_set,
162        constraints: &mut constraints,
163        deferred_closure_requirements: &mut deferred_closure_requirements,
164        polonius_context,
165    };
166
167    typeck.check_user_type_annotations();
168    typeck.visit_body(body);
169    typeck.equate_inputs_and_outputs(&normalized_inputs_and_output);
170    typeck.check_signature_annotation();
171
172    liveness::generate(&mut typeck, &location_map, move_data);
173
174    let polonius_context = typeck.polonius_context;
175
176    if infcx.tcx.assumptions_on_binders() {
177        let mut converter = constraint_conversion::ConstraintConversion::new(
178            typeck.infcx,
179            typeck.universal_regions,
180            typeck.region_bound_pairs,
181            typeck.known_type_outlives_obligations,
182            Locations::All(rustc_span::DUMMY_SP),
183            rustc_span::DUMMY_SP,
184            ConstraintCategory::Boring,
185            typeck.constraints,
186        );
187        typeck.infcx.destructure_solver_region_constraints_for_borrowck(
188            &mut converter,
189            typeck.known_type_outlives_obligations,
190            universal_region_relations.outlives.clone(),
191            infcx.tcx.def_span(infcx.root_def_id),
192        );
193    }
194
195    // In case type check encountered an error region, we suppress unhelpful extra
196    // errors in by clearing out all outlives bounds that we may end up checking.
197    if let Some(guar) = universal_region_relations.universal_regions.encountered_re_error() {
198        {
    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/type_check/mod.rs:198",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(198u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("encountered an error region; removing constraints!")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("encountered an error region; removing constraints!");
199        constraints.outlives_constraints = Default::default();
200        constraints.type_tests = Default::default();
201        infcx.set_tainted_by_errors(guar);
202    }
203
204    MirTypeckResults {
205        constraints,
206        universal_region_relations,
207        region_bound_pairs,
208        known_type_outlives_obligations,
209        deferred_closure_requirements,
210        polonius_context,
211    }
212}
213
214#[track_caller]
215fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: String) {
216    // We sometimes see MIR failures (notably predicate failures) due to
217    // the fact that we check rvalue sized predicates here. So use `span_delayed_bug`
218    // to avoid reporting bugs in those cases.
219    tcx.dcx().span_delayed_bug(span, msg);
220}
221
222enum FieldAccessError {
223    OutOfRange { field_count: usize },
224}
225
226/// The MIR type checker. Visits the MIR and enforces all the
227/// constraints needed for it to be valid and well-typed. Along the
228/// way, it accrues region constraints -- these can later be used by
229/// NLL region checking.
230struct TypeChecker<'a, 'tcx> {
231    root_cx: &'a BorrowCheckRootCtxt<'tcx>,
232    infcx: &'a BorrowckInferCtxt<'tcx>,
233    last_span: Span,
234    body: &'a Body<'tcx>,
235    /// The bodies of all promoteds. As promoteds have a completely separate CFG
236    /// recursing into them may corrupt your data structures if you're not careful.
237    promoted: &'a IndexSlice<Promoted, Body<'tcx>>,
238    /// User type annotations are shared between the main MIR and the MIR of
239    /// all of the promoted items.
240    user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
241    region_bound_pairs: &'a RegionBoundPairs<'tcx>,
242    known_type_outlives_obligations: &'a [ty::PolyTypeOutlivesPredicate<'tcx>],
243    reported_errors: FxIndexSet<(Ty<'tcx>, Span)>,
244    universal_regions: &'a UniversalRegions<'tcx>,
245    location_table: &'a PoloniusLocationTable,
246    polonius_facts: &'a mut Option<PoloniusFacts>,
247    borrow_set: &'a BorrowSet<'tcx>,
248    constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
249    deferred_closure_requirements: &'a mut DeferredClosureRequirements<'tcx>,
250    /// When using `-Zpolonius=next`, the liveness helper data used to create polonius constraints.
251    polonius_context: Option<PoloniusContext>,
252}
253
254/// Holder struct for passing results from MIR typeck to the rest of the non-lexical regions
255/// inference computation.
256pub(crate) struct MirTypeckResults<'tcx> {
257    pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
258    pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
259    pub(crate) region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
260    pub(crate) known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesPredicate<'tcx>>>,
261    pub(crate) deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
262    pub(crate) polonius_context: Option<PoloniusContext>,
263}
264
265/// A collection of region constraints that must be satisfied for the
266/// program to be considered well-typed.
267#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for MirTypeckRegionConstraints<'tcx> {
    #[inline]
    fn clone(&self) -> MirTypeckRegionConstraints<'tcx> {
        MirTypeckRegionConstraints {
            placeholder_indices: ::core::clone::Clone::clone(&self.placeholder_indices),
            placeholder_index_to_region: ::core::clone::Clone::clone(&self.placeholder_index_to_region),
            liveness_constraints: ::core::clone::Clone::clone(&self.liveness_constraints),
            outlives_constraints: ::core::clone::Clone::clone(&self.outlives_constraints),
            universe_causes: ::core::clone::Clone::clone(&self.universe_causes),
            type_tests: ::core::clone::Clone::clone(&self.type_tests),
        }
    }
}Clone)] // FIXME(#146079)
268pub(crate) struct MirTypeckRegionConstraints<'tcx> {
269    /// Maps from a `ty::Placeholder` to the corresponding
270    /// `PlaceholderIndex` bit that we will use for it.
271    ///
272    /// To keep everything in sync, do not insert this set
273    /// directly. Instead, use the `placeholder_region` helper.
274    pub(crate) placeholder_indices: PlaceholderIndices<'tcx>,
275
276    /// Each time we add a placeholder to `placeholder_indices`, we
277    /// also create a corresponding "representative" region vid for
278    /// that wraps it. This vector tracks those. This way, when we
279    /// convert the same `ty::RePlaceholder(p)` twice, we can map to
280    /// the same underlying `RegionVid`.
281    pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
282
283    /// In general, the type-checker is not responsible for enforcing
284    /// liveness constraints; this job falls to the region inferencer,
285    /// which performs a liveness analysis. However, in some limited
286    /// cases, the MIR type-checker creates temporary regions that do
287    /// not otherwise appear in the MIR -- in particular, the
288    /// late-bound regions that it instantiates at call-sites -- and
289    /// hence it must report on their liveness constraints.
290    pub(crate) liveness_constraints: LivenessValues,
291
292    pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
293
294    pub(crate) universe_causes: FxIndexMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
295
296    pub(crate) type_tests: Vec<TypeTest<'tcx>>,
297}
298
299impl<'tcx> MirTypeckRegionConstraints<'tcx> {
300    /// Creates a `Region` for a given `PlaceholderRegion`, or returns the
301    /// region that corresponds to a previously created one.
302    pub(crate) fn placeholder_region(
303        &mut self,
304        infcx: &InferCtxt<'tcx>,
305        placeholder: ty::PlaceholderRegion<'tcx>,
306    ) -> ty::Region<'tcx> {
307        let placeholder_index = self.placeholder_indices.insert(placeholder);
308        match self.placeholder_index_to_region.get(placeholder_index) {
309            Some(&v) => v,
310            None => {
311                let origin = NllRegionVariableOrigin::Placeholder(placeholder);
312                let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
313                self.placeholder_index_to_region.push(region);
314                region
315            }
316        }
317    }
318}
319
320/// The `Locations` type summarizes *where* region constraints are
321/// required to hold. Normally, this is at a particular point which
322/// created the obligation, but for constraints that the user gave, we
323/// want the constraint to hold at all points.
324#[derive(#[automatically_derived]
impl ::core::marker::Copy for Locations { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Locations {
    #[inline]
    fn clone(&self) -> Locations {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<Location>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Locations {
    #[inline]
    fn eq(&self, other: &Locations) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Locations::All(__self_0), Locations::All(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Locations::Single(__self_0), Locations::Single(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Locations {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Span>;
        let _: ::core::cmp::AssertParamIsEq<Location>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Locations {
    #[inline]
    fn partial_cmp(&self, other: &Locations)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for Locations {
    #[inline]
    fn cmp(&self, other: &Locations) -> ::core::cmp::Ordering {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        match ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr) {
            ::core::cmp::Ordering::Equal =>
                match (self, other) {
                    (Locations::All(__self_0), Locations::All(__arg1_0)) =>
                        ::core::cmp::Ord::cmp(__self_0, __arg1_0),
                    (Locations::Single(__self_0), Locations::Single(__arg1_0))
                        => ::core::cmp::Ord::cmp(__self_0, __arg1_0),
                    _ => unsafe { ::core::intrinsics::unreachable() }
                },
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::hash::Hash for Locations {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            Locations::All(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            Locations::Single(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for Locations {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Locations::All(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "All",
                    &__self_0),
            Locations::Single(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Single",
                    &__self_0),
        }
    }
}Debug)]
325pub enum Locations {
326    /// Indicates that a type constraint should always be true. This
327    /// is particularly important in the new borrowck analysis for
328    /// things like the type of the return slot. Consider this
329    /// example:
330    ///
331    /// ```compile_fail,E0515
332    /// fn foo<'a>(x: &'a u32) -> &'a u32 {
333    ///     let y = 22;
334    ///     return &y; // error
335    /// }
336    /// ```
337    ///
338    /// Here, we wind up with the signature from the return type being
339    /// something like `&'1 u32` where `'1` is a universal region. But
340    /// the type of the return slot `_0` is something like `&'2 u32`
341    /// where `'2` is an existential region variable. The type checker
342    /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
343    /// older NLL analysis, we required this only at the entry point
344    /// to the function. By the nature of the constraints, this wound
345    /// up propagating to all points reachable from start (because
346    /// `'1` -- as a universal region -- is live everywhere). In the
347    /// newer analysis, though, this doesn't work: `_0` is considered
348    /// dead at the start (it has no usable value) and hence this type
349    /// equality is basically a no-op. Then, later on, when we do `_0
350    /// = &'3 y`, that region `'3` never winds up related to the
351    /// universal region `'1` and hence no error occurs. Therefore, we
352    /// use Locations::All instead, which ensures that the `'1` and
353    /// `'2` are equal everything. We also use this for other
354    /// user-given type annotations; e.g., if the user wrote `let mut
355    /// x: &'static u32 = ...`, we would ensure that all values
356    /// assigned to `x` are of `'static` lifetime.
357    ///
358    /// The span points to the place the constraint arose. For example,
359    /// it points to the type in a user-given type annotation. If
360    /// there's no sensible span then it's DUMMY_SP.
361    All(Span),
362
363    /// An outlives constraint that only has to hold at a single location,
364    /// usually it represents a point where references flow from one spot to
365    /// another (e.g., `x = y`)
366    Single(Location),
367}
368
369impl Locations {
370    pub fn from_location(&self) -> Option<Location> {
371        match self {
372            Locations::All(_) => None,
373            Locations::Single(from_location) => Some(*from_location),
374        }
375    }
376
377    /// Gets a span representing the location.
378    pub fn span(&self, body: &Body<'_>) -> Span {
379        match self {
380            Locations::All(span) => *span,
381            Locations::Single(l) => body.source_info(*l).span,
382        }
383    }
384}
385
386impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
387    fn tcx(&self) -> TyCtxt<'tcx> {
388        self.infcx.tcx
389    }
390
391    fn body(&self) -> &Body<'tcx> {
392        self.body
393    }
394
395    /// Equate the inferred type and the annotated type for user type annotations
396    #[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("check_user_type_annotations",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(396u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set(&[]) })
                } 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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                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/type_check/mod.rs:398",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(398u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["self.user_type_annotations"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&self.user_type_annotations)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            for user_annotation in self.user_type_annotations {
                let CanonicalUserTypeAnnotation {
                        span, ref user_ty, inferred_ty } = *user_annotation;
                let annotation = self.instantiate_canonical(span, user_ty);
                self.ascribe_user_type(inferred_ty, annotation, span);
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
397    fn check_user_type_annotations(&mut self) {
398        debug!(?self.user_type_annotations);
399        for user_annotation in self.user_type_annotations {
400            let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
401            let annotation = self.instantiate_canonical(span, user_ty);
402            self.ascribe_user_type(inferred_ty, annotation, span);
403        }
404    }
405
406    #[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("push_region_constraints",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(406u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["locations",
                                                    "category"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&locations)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&category)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                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/type_check/mod.rs:413",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(413u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("constraints generated: {0:#?}",
                                                                data) as &dyn Value))])
                        });
                } else { ; }
            };
            constraint_conversion::ConstraintConversion::new(self.infcx,
                    self.universal_regions, self.region_bound_pairs,
                    self.known_type_outlives_obligations, locations,
                    locations.span(self.body), category,
                    self.constraints).convert_all(data);
        }
    }
}#[instrument(skip(self, data), level = "debug")]
407    fn push_region_constraints(
408        &mut self,
409        locations: Locations,
410        category: ConstraintCategory<'tcx>,
411        data: &QueryRegionConstraints<'tcx>,
412    ) {
413        debug!("constraints generated: {:#?}", data);
414
415        constraint_conversion::ConstraintConversion::new(
416            self.infcx,
417            self.universal_regions,
418            self.region_bound_pairs,
419            self.known_type_outlives_obligations,
420            locations,
421            locations.span(self.body),
422            category,
423            self.constraints,
424        )
425        .convert_all(data);
426    }
427
428    /// Try to relate `sub <: sup`
429    fn sub_types(
430        &mut self,
431        sub: Ty<'tcx>,
432        sup: Ty<'tcx>,
433        locations: Locations,
434        category: ConstraintCategory<'tcx>,
435    ) -> Result<(), NoSolution> {
436        // Use this order of parameters because the sup type is usually the
437        // "expected" type in diagnostics.
438        self.relate_types(sup, ty::Contravariant, sub, locations, category)
439    }
440
441    #[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("eq_types",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(441u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["expected", "found",
                                                    "locations"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&locations)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), NoSolution> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.relate_types(expected, ty::Invariant, found, locations,
                category)
        }
    }
}#[instrument(skip(self, category), level = "debug")]
442    fn eq_types(
443        &mut self,
444        expected: Ty<'tcx>,
445        found: Ty<'tcx>,
446        locations: Locations,
447        category: ConstraintCategory<'tcx>,
448    ) -> Result<(), NoSolution> {
449        self.relate_types(expected, ty::Invariant, found, locations, category)
450    }
451
452    #[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("relate_type_and_user_type",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(452u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["a", "v", "user_ty",
                                                    "locations", "category"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&v)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&user_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&locations)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&category)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), NoSolution> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let annotated_type =
                self.user_type_annotations[user_ty.base].inferred_ty;
            {
                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/type_check/mod.rs:462",
                                    "rustc_borrowck::type_check", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(462u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["annotated_type"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&annotated_type)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
            let tcx = self.infcx.tcx;
            for proj in &user_ty.projs {
                if !self.infcx.next_trait_solver() &&
                        let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, ..
                            }) = curr_projected_ty.ty.kind() {
                    return Ok(());
                }
                let projected_ty =
                    curr_projected_ty.projection_ty_core(tcx, proj,
                        |ty|
                            self.normalize(ty::Unnormalized::new_wip(ty), locations),
                        |ty, variant_index, field, ()|
                            {
                                PlaceTy::field_ty(tcx, ty, variant_index,
                                        field).skip_norm_wip()
                            },
                        |_|
                            ::core::panicking::panic("internal error: entered unreachable code"));
                curr_projected_ty = projected_ty;
            }
            {
                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/type_check/mod.rs:490",
                                    "rustc_borrowck::type_check", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(490u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["curr_projected_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&curr_projected_ty)
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let mut a = a;
            let mut ty = curr_projected_ty.ty;
            if !self.infcx.next_trait_solver() {
                a = self.normalize(ty::Unnormalized::new_wip(a), locations);
                ty = self.normalize(ty::Unnormalized::new_wip(ty), locations);
            }
            self.relate_types(ty, v.xform(ty::Contravariant), a, locations,
                    category)?;
            Ok(())
        }
    }
}#[instrument(skip(self), level = "debug")]
453    fn relate_type_and_user_type(
454        &mut self,
455        a: Ty<'tcx>,
456        v: ty::Variance,
457        user_ty: &UserTypeProjection,
458        locations: Locations,
459        category: ConstraintCategory<'tcx>,
460    ) -> Result<(), NoSolution> {
461        let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
462        trace!(?annotated_type);
463        let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
464
465        let tcx = self.infcx.tcx;
466
467        for proj in &user_ty.projs {
468            // Necessary for non-trivial patterns whose user-type annotation is an opaque type,
469            // e.g. `let (_a,): Tait = whatever`, see #105897
470            if !self.infcx.next_trait_solver()
471                && let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) =
472                    curr_projected_ty.ty.kind()
473            {
474                // There is nothing that we can compare here if we go through an opaque type.
475                // We're always in its defining scope as we can otherwise not project through
476                // it, so we're constraining it anyways.
477                return Ok(());
478            }
479            let projected_ty = curr_projected_ty.projection_ty_core(
480                tcx,
481                proj,
482                |ty| self.normalize(ty::Unnormalized::new_wip(ty), locations),
483                |ty, variant_index, field, ()| {
484                    PlaceTy::field_ty(tcx, ty, variant_index, field).skip_norm_wip()
485                },
486                |_| unreachable!(),
487            );
488            curr_projected_ty = projected_ty;
489        }
490        trace!(?curr_projected_ty);
491
492        // Need to renormalize `a` in the old solver as typecheck may have failed
493        // to normalize higher-ranked aliases if normalization was ambiguous due
494        // to inference.
495        //
496        // We properly normalize higher-ranked aliases during writeback with the
497        // new solver, so this is no longer necessary.
498        let mut a = a;
499        let mut ty = curr_projected_ty.ty;
500        if !self.infcx.next_trait_solver() {
501            a = self.normalize(ty::Unnormalized::new_wip(a), locations);
502            ty = self.normalize(ty::Unnormalized::new_wip(ty), locations);
503        }
504        self.relate_types(ty, v.xform(ty::Contravariant), a, locations, category)?;
505
506        Ok(())
507    }
508
509    fn check_promoted(&mut self, promoted_body: &'a Body<'tcx>, location: Location) {
510        // Determine the constraints from the promoted MIR by running the type
511        // checker on the promoted MIR, then transfer the constraints back to
512        // the main MIR, changing the locations to the provided location.
513
514        let parent_body = mem::replace(&mut self.body, promoted_body);
515
516        // Use new sets of constraints and closure bounds so that we can
517        // modify their locations.
518        let polonius_facts = &mut None;
519        let mut constraints = Default::default();
520        let mut liveness_constraints =
521            LivenessValues::without_specific_points(Rc::new(DenseLocationMap::new(promoted_body)));
522        let mut deferred_closure_requirements = Default::default();
523
524        // Don't try to add borrow_region facts for the promoted MIR as they refer
525        // to the wrong locations.
526        let mut swap_constraints = |this: &mut Self| {
527            mem::swap(this.polonius_facts, polonius_facts);
528            mem::swap(&mut this.constraints.outlives_constraints, &mut constraints);
529            mem::swap(&mut this.constraints.liveness_constraints, &mut liveness_constraints);
530            mem::swap(this.deferred_closure_requirements, &mut deferred_closure_requirements);
531        };
532
533        swap_constraints(self);
534
535        self.visit_body(promoted_body);
536
537        self.body = parent_body;
538
539        // Merge the outlives constraints back in, at the given location.
540        swap_constraints(self);
541        let locations = location.to_locations();
542        for constraint in constraints.outlives().iter() {
543            let mut constraint = *constraint;
544            constraint.locations = locations;
545            if let ConstraintCategory::Return(_)
546            | ConstraintCategory::UseAsConst
547            | ConstraintCategory::UseAsStatic = constraint.category
548            {
549                // "Returning" from a promoted is an assignment to a
550                // temporary from the user's point of view.
551                constraint.category = ConstraintCategory::Boring;
552            }
553            self.constraints.outlives_constraints.push(constraint)
554        }
555
556        // If there are nested bodies in promoteds, we also need to update their
557        // location to something in the actual body, not the promoted.
558        //
559        // We don't update the constraint categories of the resulting constraints
560        // as returns in nested bodies are a proper return, even if that nested body
561        // is in a promoted.
562        for (closure_def_id, args, _locations) in deferred_closure_requirements {
563            self.deferred_closure_requirements.push((closure_def_id, args, locations));
564        }
565
566        // If the region is live at least one location in the promoted MIR,
567        // then add a liveness constraint to the main MIR for this region
568        // at the location provided as an argument to this method
569        //
570        // add_location doesn't care about ordering so not a problem for the live regions to be
571        // unordered.
572        #[allow(rustc::potential_query_instability)]
573        for region in liveness_constraints.live_regions_unordered() {
574            self.constraints.liveness_constraints.add_location(region, location);
575        }
576    }
577}
578
579impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
580    fn visit_span(&mut self, span: Span) {
581        if !span.is_dummy() {
582            {
    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/type_check/mod.rs:582",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(582u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["span"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&span) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?span);
583            self.last_span = span;
584        }
585    }
586
587    #[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("visit_body",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(587u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set(&[]) })
                } 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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                if !std::ptr::eq(self.body, body) {
                    ::core::panicking::panic("assertion failed: std::ptr::eq(self.body, body)")
                };
            };
            for (local, local_decl) in body.local_decls.iter_enumerated() {
                self.visit_local_decl(local, local_decl);
            }
            for (block, block_data) in body.basic_blocks.iter_enumerated() {
                let mut location = Location { block, statement_index: 0 };
                for stmt in &block_data.statements {
                    self.visit_statement(stmt, location);
                    location.statement_index += 1;
                }
                self.visit_terminator(block_data.terminator(), location);
                self.check_iscleanup(block_data);
            }
        }
    }
}#[instrument(skip(self, body), level = "debug")]
588    fn visit_body(&mut self, body: &Body<'tcx>) {
589        debug_assert!(std::ptr::eq(self.body, body));
590
591        for (local, local_decl) in body.local_decls.iter_enumerated() {
592            self.visit_local_decl(local, local_decl);
593        }
594
595        for (block, block_data) in body.basic_blocks.iter_enumerated() {
596            let mut location = Location { block, statement_index: 0 };
597            for stmt in &block_data.statements {
598                self.visit_statement(stmt, location);
599                location.statement_index += 1;
600            }
601
602            self.visit_terminator(block_data.terminator(), location);
603            self.check_iscleanup(block_data);
604        }
605    }
606
607    #[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("visit_statement",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(607u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["stmt", "location"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&stmt)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_statement(stmt, location);
            let tcx = self.tcx();
            match &stmt.kind {
                StatementKind::Assign((place, rv)) => {
                    let category =
                        match place.as_local() {
                            Some(RETURN_PLACE) => {
                                let defining_ty = &self.universal_regions.defining_ty;
                                if defining_ty.is_const() {
                                    if tcx.is_static(defining_ty.def_id()) {
                                        ConstraintCategory::UseAsStatic
                                    } else { ConstraintCategory::UseAsConst }
                                } else {
                                    ConstraintCategory::Return(ReturnConstraint::Normal)
                                }
                            }
                            Some(l) if
                                #[allow(non_exhaustive_omitted_patterns)] match self.body.local_decls[l].local_info()
                                    {
                                    LocalInfo::AggregateTemp => true,
                                    _ => false,
                                } => {
                                ConstraintCategory::Usage
                            }
                            Some(l) if !self.body.local_decls[l].is_user_variable() => {
                                ConstraintCategory::Boring
                            }
                            _ => ConstraintCategory::Assignment,
                        };
                    {
                        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/type_check/mod.rs:643",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(643u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("assignment category: {0:?} {1:?}",
                                                                        category,
                                                                        place.as_local().map(|l| &self.body.local_decls[l])) as
                                                                &dyn Value))])
                                });
                        } else { ; }
                    };
                    let place_ty = place.ty(self.body, tcx).ty;
                    {
                        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/type_check/mod.rs:650",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(650u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["place_ty"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&place_ty)
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    let place_ty =
                        self.normalize(ty::Unnormalized::new_wip(place_ty),
                            location);
                    {
                        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/type_check/mod.rs:652",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(652u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("place_ty normalized: {0:?}",
                                                                        place_ty) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    let rv_ty = rv.ty(self.body, 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/type_check/mod.rs:654",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(654u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["rv_ty"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&rv_ty) as
                                                                &dyn Value))])
                                });
                        } else { ; }
                    };
                    let rv_ty =
                        self.normalize(ty::Unnormalized::new_wip(rv_ty), location);
                    {
                        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/type_check/mod.rs:656",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(656u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("normalized rv_ty: {0:?}",
                                                                        rv_ty) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    if let Err(terr) =
                            self.sub_types(rv_ty, place_ty, location.to_locations(),
                                category) {
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), stmt,
                                                format_args!("bad assignment ({0:?} = {1:?}): {2:?}",
                                                    place_ty, rv_ty, terr)))
                                    }))
                        };
                    }
                    if let Some(annotation_index) = self.rvalue_user_ty(rv) &&
                            let Err(terr) =
                                self.relate_type_and_user_type(rv_ty, ty::Invariant,
                                    &UserTypeProjection {
                                            base: annotation_index,
                                            projs: ::alloc::vec::Vec::new(),
                                        }, location.to_locations(),
                                    ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg))
                        {
                        let annotation =
                            &self.user_type_annotations[annotation_index];
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), stmt,
                                                format_args!("bad user type on rvalue ({0:?} = {1:?}): {2:?}",
                                                    annotation, rv_ty, terr)))
                                    }))
                        };
                    }
                    if !self.tcx().features().unsized_fn_params() {
                        let trait_ref =
                            ty::TraitRef::new(tcx,
                                tcx.require_lang_item(LangItem::Sized, self.last_span),
                                [place_ty]);
                        self.prove_trait_ref(trait_ref, location.to_locations(),
                            ConstraintCategory::SizedBound);
                    }
                }
                StatementKind::AscribeUserType((place, projection), variance)
                    => {
                    let place_ty = place.ty(self.body, tcx).ty;
                    if let Err(terr) =
                            self.relate_type_and_user_type(place_ty, *variance,
                                projection, Locations::All(stmt.source_info.span),
                                ConstraintCategory::TypeAnnotation(AnnotationSource::Ascription))
                        {
                        let annotation =
                            &self.user_type_annotations[projection.base];
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), stmt,
                                                format_args!("bad type assert ({0:?} <: {1:?} with projections {2:?}): {3:?}",
                                                    place_ty, annotation, projection.projs, terr)))
                                    }))
                        };
                    }
                }
                StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(..)) |
                    StatementKind::FakeRead(..) | StatementKind::StorageLive(..)
                    | StatementKind::StorageDead(..) |
                    StatementKind::Coverage(..) |
                    StatementKind::ConstEvalCounter |
                    StatementKind::PlaceMention(..) |
                    StatementKind::BackwardIncompatibleDropHint { .. } |
                    StatementKind::Nop => {}
                StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(..))
                    | StatementKind::SetDiscriminant { .. } => {
                    ::rustc_middle::util::bug::bug_fmt(format_args!("Statement not allowed in this MIR phase"))
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
608    fn visit_statement(&mut self, stmt: &Statement<'tcx>, location: Location) {
609        self.super_statement(stmt, location);
610        let tcx = self.tcx();
611        match &stmt.kind {
612            StatementKind::Assign((place, rv)) => {
613                // Assignments to temporaries are not "interesting";
614                // they are not caused by the user, but rather artifacts
615                // of lowering. Assignments to other sorts of places *are* interesting
616                // though.
617                let category = match place.as_local() {
618                    Some(RETURN_PLACE) => {
619                        let defining_ty = &self.universal_regions.defining_ty;
620                        if defining_ty.is_const() {
621                            if tcx.is_static(defining_ty.def_id()) {
622                                ConstraintCategory::UseAsStatic
623                            } else {
624                                ConstraintCategory::UseAsConst
625                            }
626                        } else {
627                            ConstraintCategory::Return(ReturnConstraint::Normal)
628                        }
629                    }
630                    Some(l)
631                        if matches!(
632                            self.body.local_decls[l].local_info(),
633                            LocalInfo::AggregateTemp
634                        ) =>
635                    {
636                        ConstraintCategory::Usage
637                    }
638                    Some(l) if !self.body.local_decls[l].is_user_variable() => {
639                        ConstraintCategory::Boring
640                    }
641                    _ => ConstraintCategory::Assignment,
642                };
643                debug!(
644                    "assignment category: {:?} {:?}",
645                    category,
646                    place.as_local().map(|l| &self.body.local_decls[l])
647                );
648
649                let place_ty = place.ty(self.body, tcx).ty;
650                debug!(?place_ty);
651                let place_ty = self.normalize(ty::Unnormalized::new_wip(place_ty), location);
652                debug!("place_ty normalized: {:?}", place_ty);
653                let rv_ty = rv.ty(self.body, tcx);
654                debug!(?rv_ty);
655                let rv_ty = self.normalize(ty::Unnormalized::new_wip(rv_ty), location);
656                debug!("normalized rv_ty: {:?}", rv_ty);
657                if let Err(terr) =
658                    self.sub_types(rv_ty, place_ty, location.to_locations(), category)
659                {
660                    span_mirbug!(
661                        self,
662                        stmt,
663                        "bad assignment ({:?} = {:?}): {:?}",
664                        place_ty,
665                        rv_ty,
666                        terr
667                    );
668                }
669
670                if let Some(annotation_index) = self.rvalue_user_ty(rv)
671                    && let Err(terr) = self.relate_type_and_user_type(
672                        rv_ty,
673                        ty::Invariant,
674                        &UserTypeProjection { base: annotation_index, projs: vec![] },
675                        location.to_locations(),
676                        ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg),
677                    )
678                {
679                    let annotation = &self.user_type_annotations[annotation_index];
680                    span_mirbug!(
681                        self,
682                        stmt,
683                        "bad user type on rvalue ({:?} = {:?}): {:?}",
684                        annotation,
685                        rv_ty,
686                        terr
687                    );
688                }
689
690                if !self.tcx().features().unsized_fn_params() {
691                    let trait_ref = ty::TraitRef::new(
692                        tcx,
693                        tcx.require_lang_item(LangItem::Sized, self.last_span),
694                        [place_ty],
695                    );
696                    self.prove_trait_ref(
697                        trait_ref,
698                        location.to_locations(),
699                        ConstraintCategory::SizedBound,
700                    );
701                }
702            }
703            StatementKind::AscribeUserType((place, projection), variance) => {
704                let place_ty = place.ty(self.body, tcx).ty;
705                if let Err(terr) = self.relate_type_and_user_type(
706                    place_ty,
707                    *variance,
708                    projection,
709                    Locations::All(stmt.source_info.span),
710                    ConstraintCategory::TypeAnnotation(AnnotationSource::Ascription),
711                ) {
712                    let annotation = &self.user_type_annotations[projection.base];
713                    span_mirbug!(
714                        self,
715                        stmt,
716                        "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
717                        place_ty,
718                        annotation,
719                        projection.projs,
720                        terr
721                    );
722                }
723            }
724            StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(..))
725            | StatementKind::FakeRead(..)
726            | StatementKind::StorageLive(..)
727            | StatementKind::StorageDead(..)
728            | StatementKind::Coverage(..)
729            | StatementKind::ConstEvalCounter
730            | StatementKind::PlaceMention(..)
731            | StatementKind::BackwardIncompatibleDropHint { .. }
732            | StatementKind::Nop => {}
733            StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(..))
734            | StatementKind::SetDiscriminant { .. } => {
735                bug!("Statement not allowed in this MIR phase")
736            }
737        }
738    }
739
740    #[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("visit_terminator",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(740u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["term",
                                                    "term_location"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term_location)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_terminator(term, term_location);
            let tcx = self.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/type_check/mod.rs:744",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(744u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("terminator kind: {0:?}",
                                                                term.kind) as &dyn Value))])
                        });
                } else { ; }
            };
            match &term.kind {
                TerminatorKind::Goto { .. } | TerminatorKind::UnwindResume |
                    TerminatorKind::UnwindTerminate(_) | TerminatorKind::Return
                    | TerminatorKind::CoroutineDrop |
                    TerminatorKind::Unreachable | TerminatorKind::Drop { .. } |
                    TerminatorKind::FalseEdge { .. } |
                    TerminatorKind::FalseUnwind { .. } |
                    TerminatorKind::InlineAsm { .. } => {}
                TerminatorKind::SwitchInt { discr, .. } => {
                    let switch_ty = discr.ty(self.body, tcx);
                    if !switch_ty.is_integral() && !switch_ty.is_char() &&
                            !switch_ty.is_bool() {
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), term,
                                                format_args!("bad SwitchInt discr ty {0:?}", switch_ty)))
                                    }))
                        };
                    }
                }
                TerminatorKind::Call { func, args, .. } |
                    TerminatorKind::TailCall { func, args, .. } => {
                    let (call_source, destination, is_diverging) =
                        match term.kind {
                            TerminatorKind::Call { call_source, destination, target, ..
                                } => {
                                (call_source, destination, target.is_none())
                            }
                            TerminatorKind::TailCall { .. } => {
                                (CallSource::Normal, RETURN_PLACE.into(), false)
                            }
                            _ =>
                                ::core::panicking::panic("internal error: entered unreachable code"),
                        };
                    let func_ty = func.ty(self.body, 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/type_check/mod.rs:779",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(779u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("func_ty.kind: {0:?}",
                                                                        func_ty.kind()) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    let sig =
                        match func_ty.kind() {
                            ty::FnDef(..) | ty::FnPtr(..) => func_ty.fn_sig(tcx),
                            _ => {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), term,
                                                        format_args!("call to non-function {0:?}", func_ty)))
                                            }))
                                };
                                return;
                            }
                        };
                    let (unnormalized_sig, map) =
                        tcx.instantiate_bound_regions(sig,
                            |br|
                                {
                                    use crate::renumber::RegionCtxt;
                                    let region_ctxt_fn =
                                        ||
                                            {
                                                let reg_info =
                                                    match br.kind {
                                                        ty::BoundRegionKind::Anon => sym::anon,
                                                        ty::BoundRegionKind::Named(def_id) => tcx.item_name(def_id),
                                                        ty::BoundRegionKind::ClosureEnv => sym::env,
                                                        ty::BoundRegionKind::NamedForPrinting(_) => {
                                                            ::rustc_middle::util::bug::bug_fmt(format_args!("only used for pretty printing"))
                                                        }
                                                    };
                                                RegionCtxt::LateBound(reg_info)
                                            };
                                    self.infcx.next_region_var(RegionVariableOrigin::BoundRegion(term.source_info.span,
                                            br.kind, BoundRegionConversionTime::FnCall), region_ctxt_fn)
                                });
                    {
                        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/type_check/mod.rs:813",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(813u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["unnormalized_sig"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&debug(&unnormalized_sig)
                                                                as &dyn Value))])
                                });
                        } else { ; }
                    };
                    self.prove_clauses(unnormalized_sig.inputs_and_output.iter().map(|ty|
                                ty::ClauseKind::WellFormed(ty.into())),
                        term_location.to_locations(), ConstraintCategory::Boring);
                    let sig =
                        self.deeply_normalize(unnormalized_sig, term_location);
                    if sig != unnormalized_sig {
                        self.prove_clauses(sig.inputs_and_output.iter().map(|ty|
                                    ty::ClauseKind::WellFormed(ty.into())),
                            term_location.to_locations(), ConstraintCategory::Boring);
                    }
                    self.check_call_dest(term, &sig, destination, is_diverging,
                        term_location);
                    for &late_bound_region in map.values() {
                        let region_vid =
                            self.universal_regions.to_region_vid(late_bound_region);
                        self.constraints.liveness_constraints.add_location(region_vid,
                            term_location);
                    }
                    self.check_call_inputs(term, func, &sig, args,
                        term_location, call_source);
                }
                TerminatorKind::Assert { cond, msg, .. } => {
                    let cond_ty = cond.ty(self.body, tcx);
                    if cond_ty != tcx.types.bool {
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), term,
                                                format_args!("bad Assert ({0:?}, not bool", cond_ty)))
                                    }))
                        };
                    }
                    if let AssertKind::BoundsCheck { len, index } = &**msg {
                        if len.ty(self.body, tcx) != tcx.types.usize {
                            {
                                crate::type_check::mirbug(self.tcx(), self.last_span,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                    self.body().source.def_id(), len,
                                                    format_args!("bounds-check length non-usize {0:?}", len)))
                                        }))
                            }
                        }
                        if index.ty(self.body, tcx) != tcx.types.usize {
                            {
                                crate::type_check::mirbug(self.tcx(), self.last_span,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                    self.body().source.def_id(), index,
                                                    format_args!("bounds-check index non-usize {0:?}", index)))
                                        }))
                            }
                        }
                    }
                }
                TerminatorKind::Yield { value, resume_arg, .. } => {
                    match self.body.yield_ty() {
                        None => {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), term,
                                                format_args!("yield in non-coroutine")))
                                    }))
                        }
                        Some(ty) => {
                            let value_ty = value.ty(self.body, tcx);
                            if let Err(terr) =
                                    self.sub_types(value_ty, ty, term_location.to_locations(),
                                        ConstraintCategory::Yield) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), term,
                                                        format_args!("type of yield value is {0:?}, but the yield type is {1:?}: {2:?}",
                                                            value_ty, ty, terr)))
                                            }))
                                };
                            }
                        }
                    }
                    match self.body.resume_ty() {
                        None => {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), term,
                                                format_args!("yield in non-coroutine")))
                                    }))
                        }
                        Some(ty) => {
                            let resume_ty = resume_arg.ty(self.body, tcx);
                            if let Err(terr) =
                                    self.sub_types(ty, resume_ty.ty,
                                        term_location.to_locations(), ConstraintCategory::Yield) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), term,
                                                        format_args!("type of resume place is {0:?}, but the resume type is {1:?}: {2:?}",
                                                            resume_ty, ty, terr)))
                                            }))
                                };
                            }
                        }
                    }
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
741    fn visit_terminator(&mut self, term: &Terminator<'tcx>, term_location: Location) {
742        self.super_terminator(term, term_location);
743        let tcx = self.tcx();
744        debug!("terminator kind: {:?}", term.kind);
745        match &term.kind {
746            TerminatorKind::Goto { .. }
747            | TerminatorKind::UnwindResume
748            | TerminatorKind::UnwindTerminate(_)
749            | TerminatorKind::Return
750            | TerminatorKind::CoroutineDrop
751            | TerminatorKind::Unreachable
752            | TerminatorKind::Drop { .. }
753            | TerminatorKind::FalseEdge { .. }
754            | TerminatorKind::FalseUnwind { .. }
755            | TerminatorKind::InlineAsm { .. } => {
756                // no checks needed for these
757            }
758
759            TerminatorKind::SwitchInt { discr, .. } => {
760                let switch_ty = discr.ty(self.body, tcx);
761                if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
762                    span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
763                }
764                // FIXME: check the values
765            }
766            TerminatorKind::Call { func, args, .. }
767            | TerminatorKind::TailCall { func, args, .. } => {
768                let (call_source, destination, is_diverging) = match term.kind {
769                    TerminatorKind::Call { call_source, destination, target, .. } => {
770                        (call_source, destination, target.is_none())
771                    }
772                    TerminatorKind::TailCall { .. } => {
773                        (CallSource::Normal, RETURN_PLACE.into(), false)
774                    }
775                    _ => unreachable!(),
776                };
777
778                let func_ty = func.ty(self.body, tcx);
779                debug!("func_ty.kind: {:?}", func_ty.kind());
780
781                let sig = match func_ty.kind() {
782                    ty::FnDef(..) | ty::FnPtr(..) => func_ty.fn_sig(tcx),
783                    _ => {
784                        span_mirbug!(self, term, "call to non-function {:?}", func_ty);
785                        return;
786                    }
787                };
788                let (unnormalized_sig, map) = tcx.instantiate_bound_regions(sig, |br| {
789                    use crate::renumber::RegionCtxt;
790
791                    let region_ctxt_fn = || {
792                        let reg_info = match br.kind {
793                            ty::BoundRegionKind::Anon => sym::anon,
794                            ty::BoundRegionKind::Named(def_id) => tcx.item_name(def_id),
795                            ty::BoundRegionKind::ClosureEnv => sym::env,
796                            ty::BoundRegionKind::NamedForPrinting(_) => {
797                                bug!("only used for pretty printing")
798                            }
799                        };
800
801                        RegionCtxt::LateBound(reg_info)
802                    };
803
804                    self.infcx.next_region_var(
805                        RegionVariableOrigin::BoundRegion(
806                            term.source_info.span,
807                            br.kind,
808                            BoundRegionConversionTime::FnCall,
809                        ),
810                        region_ctxt_fn,
811                    )
812                });
813                debug!(?unnormalized_sig);
814                // IMPORTANT: We have to prove well formed for the function signature before
815                // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc`
816                // get normalized away, causing us to ignore the `'b: 'a` bound used by the function.
817                //
818                // Normalization results in a well formed type if the input is well formed, so we
819                // don't have to check it twice.
820                //
821                // See #91068 for an example.
822                self.prove_clauses(
823                    unnormalized_sig
824                        .inputs_and_output
825                        .iter()
826                        .map(|ty| ty::ClauseKind::WellFormed(ty.into())),
827                    term_location.to_locations(),
828                    ConstraintCategory::Boring,
829                );
830
831                let sig = self.deeply_normalize(unnormalized_sig, term_location);
832                // HACK(#114936): `WF(sig)` does not imply `WF(normalized(sig))`
833                // with built-in `Fn` implementations, since the impl may not be
834                // well-formed itself.
835                if sig != unnormalized_sig {
836                    self.prove_clauses(
837                        sig.inputs_and_output
838                            .iter()
839                            .map(|ty| ty::ClauseKind::WellFormed(ty.into())),
840                        term_location.to_locations(),
841                        ConstraintCategory::Boring,
842                    );
843                }
844
845                self.check_call_dest(term, &sig, destination, is_diverging, term_location);
846
847                // The ordinary liveness rules will ensure that all
848                // regions in the type of the callee are live here. We
849                // then further constrain the late-bound regions that
850                // were instantiated at the call site to be live as
851                // well. The resulting is that all the input (and
852                // output) types in the signature must be live, since
853                // all the inputs that fed into it were live.
854                for &late_bound_region in map.values() {
855                    let region_vid = self.universal_regions.to_region_vid(late_bound_region);
856                    self.constraints.liveness_constraints.add_location(region_vid, term_location);
857                }
858
859                self.check_call_inputs(term, func, &sig, args, term_location, call_source);
860            }
861            TerminatorKind::Assert { cond, msg, .. } => {
862                let cond_ty = cond.ty(self.body, tcx);
863                if cond_ty != tcx.types.bool {
864                    span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
865                }
866
867                if let AssertKind::BoundsCheck { len, index } = &**msg {
868                    if len.ty(self.body, tcx) != tcx.types.usize {
869                        span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
870                    }
871                    if index.ty(self.body, tcx) != tcx.types.usize {
872                        span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
873                    }
874                }
875            }
876            TerminatorKind::Yield { value, resume_arg, .. } => {
877                match self.body.yield_ty() {
878                    None => span_mirbug!(self, term, "yield in non-coroutine"),
879                    Some(ty) => {
880                        let value_ty = value.ty(self.body, tcx);
881                        if let Err(terr) = self.sub_types(
882                            value_ty,
883                            ty,
884                            term_location.to_locations(),
885                            ConstraintCategory::Yield,
886                        ) {
887                            span_mirbug!(
888                                self,
889                                term,
890                                "type of yield value is {:?}, but the yield type is {:?}: {:?}",
891                                value_ty,
892                                ty,
893                                terr
894                            );
895                        }
896                    }
897                }
898
899                match self.body.resume_ty() {
900                    None => span_mirbug!(self, term, "yield in non-coroutine"),
901                    Some(ty) => {
902                        let resume_ty = resume_arg.ty(self.body, tcx);
903                        if let Err(terr) = self.sub_types(
904                            ty,
905                            resume_ty.ty,
906                            term_location.to_locations(),
907                            ConstraintCategory::Yield,
908                        ) {
909                            span_mirbug!(
910                                self,
911                                term,
912                                "type of resume place is {:?}, but the resume type is {:?}: {:?}",
913                                resume_ty,
914                                ty,
915                                terr
916                            );
917                        }
918                    }
919                }
920            }
921        }
922    }
923
924    fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
925        self.super_local_decl(local, local_decl);
926
927        for user_ty in
928            local_decl.user_ty.as_deref().map(UserTypeProjections::projections).into_flat_iter()
929        {
930            let span = self.user_type_annotations[user_ty.base].span;
931
932            let ty = if local_decl.is_nonref_binding() {
933                local_decl.ty
934            } else if let &ty::Ref(_, rty, _) = local_decl.ty.kind() {
935                // If we have a binding of the form `let ref x: T = ..`
936                // then remove the outermost reference so we can check the
937                // type annotation for the remaining type.
938                rty
939            } else {
940                ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} with ref binding has wrong type {1}",
        local, local_decl.ty));bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
941            };
942
943            if let Err(terr) = self.relate_type_and_user_type(
944                ty,
945                ty::Invariant,
946                user_ty,
947                Locations::All(span),
948                ConstraintCategory::TypeAnnotation(AnnotationSource::Declaration),
949            ) {
950                {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), local,
                        format_args!("bad user type on variable {0:?}: {1:?} != {2:?} ({3:?})",
                            local, local_decl.ty, local_decl.user_ty, terr)))
            }))
};span_mirbug!(
951                    self,
952                    local,
953                    "bad user type on variable {:?}: {:?} != {:?} ({:?})",
954                    local,
955                    local_decl.ty,
956                    local_decl.user_ty,
957                    terr,
958                );
959            }
960        }
961
962        // When `unsized_fn_params` is enabled, this is checked in `check_call_dest`,
963        // and `hir_typeck` still forces all non-argument locals to be sized (i.e., we don't
964        // fully re-check what was already checked on HIR).
965        if !self.tcx().features().unsized_fn_params() {
966            match self.body.local_kind(local) {
967                LocalKind::ReturnPointer | LocalKind::Arg => {
968                    // return values of normal functions are required to be
969                    // sized by typeck, but return values of ADT constructors are
970                    // not because we don't include a `Self: Sized` bounds on them.
971                    //
972                    // Unbound parts of arguments were never required to be Sized
973                    // - maybe we should make that a warning.
974                    return;
975                }
976                LocalKind::Temp => {
977                    let span = local_decl.source_info.span;
978                    let ty = local_decl.ty;
979                    self.ensure_place_sized(ty, span);
980                }
981            }
982        }
983    }
984
985    #[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("visit_rvalue",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(985u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["rvalue",
                                                    "location"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rvalue)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_rvalue(rvalue, location);
            let tcx = self.tcx();
            let span = self.body.source_info(location).span;
            match rvalue {
                Rvalue::Aggregate(ak, ops) =>
                    self.check_aggregate_rvalue(rvalue, ak, ops, location),
                Rvalue::Repeat(operand, len) => {
                    let array_ty = rvalue.ty(self.body.local_decls(), tcx);
                    self.prove_clause(ty::ClauseKind::WellFormed(array_ty.into()),
                        Locations::Single(location), ConstraintCategory::Boring);
                    if len.try_to_target_usize(tcx).is_none_or(|len| len > 1) {
                        match operand {
                            Operand::Copy(..) | Operand::Constant(..) |
                                Operand::RuntimeChecks(_) => {}
                            Operand::Move(place) => {
                                let ty = place.ty(self.body, tcx).ty;
                                let trait_ref =
                                    ty::TraitRef::new(tcx,
                                        tcx.require_lang_item(LangItem::Copy, span), [ty]);
                                self.prove_trait_ref(trait_ref, Locations::Single(location),
                                    ConstraintCategory::CopyBound);
                            }
                        }
                    }
                }
                Rvalue::Cast(cast_kind, op, ty) => {
                    match *cast_kind {
                        CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(target_safety),
                            coercion_source) => {
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            let src_ty = op.ty(self.body, tcx);
                            let mut src_sig = src_ty.fn_sig(tcx);
                            if let ty::FnDef(def_id, _) = *src_ty.kind() &&
                                                let ty::FnPtr(_, target_hdr) = *ty.kind() &&
                                            tcx.codegen_fn_attrs(def_id).safe_target_features &&
                                        target_hdr.safety().is_safe() &&
                                    let Some(safe_sig) =
                                        tcx.adjust_target_feature_sig(def_id, src_sig,
                                            self.body.source.def_id()) {
                                src_sig = safe_sig;
                            }
                            if src_sig.safety().is_safe() && target_safety.is_unsafe() {
                                src_sig = tcx.safe_to_unsafe_sig(src_sig);
                            }
                            if src_sig.has_bound_regions() &&
                                            let ty::FnPtr(target_fn_tys, target_hdr) = *ty.kind() &&
                                        let target_sig = target_fn_tys.with(target_hdr) &&
                                    let Some(target_sig) = target_sig.no_bound_vars() {
                                let src_sig =
                                    self.infcx.instantiate_binder_with_fresh_vars(span,
                                        BoundRegionConversionTime::HigherRankedType, src_sig);
                                let src_ty =
                                    Ty::new_fn_ptr(self.tcx(), ty::Binder::dummy(src_sig));
                                self.prove_clause(ty::ClauseKind::WellFormed(src_ty.into()),
                                    location.to_locations(),
                                    ConstraintCategory::Cast {
                                        is_raw_ptr_dyn_type_cast: false,
                                        is_implicit_coercion,
                                        unsize_to: None,
                                    });
                                let src_ty =
                                    self.normalize(ty::Unnormalized::new_wip(src_ty), location);
                                if let Err(terr) =
                                        self.sub_types(src_ty, *ty, location.to_locations(),
                                            ConstraintCategory::Cast {
                                                is_raw_ptr_dyn_type_cast: false,
                                                is_implicit_coercion,
                                                unsize_to: None,
                                            }) {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("equating {0:?} with {1:?} yields {2:?}",
                                                                target_sig, src_sig, terr)))
                                                }))
                                    };
                                };
                            }
                            let src_ty = Ty::new_fn_ptr(tcx, src_sig);
                            self.prove_clause(ty::ClauseKind::WellFormed(src_ty.into()),
                                location.to_locations(),
                                ConstraintCategory::Cast {
                                    is_raw_ptr_dyn_type_cast: false,
                                    is_implicit_coercion,
                                    unsize_to: None,
                                });
                            let src_ty =
                                self.normalize(ty::Unnormalized::new_wip(src_ty), location);
                            if let Err(terr) =
                                    self.sub_types(src_ty, *ty, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("equating {0:?} with {1:?} yields {2:?}",
                                                            src_ty, ty, terr)))
                                            }))
                                };
                            }
                        }
                        CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(safety),
                            coercion_source) => {
                            let sig =
                                match op.ty(self.body, tcx).kind() {
                                    ty::Closure(_, args) => args.as_closure().sig(),
                                    _ =>
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached")),
                                };
                            let ty_fn_ptr_from =
                                Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, safety));
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            if let Err(terr) =
                                    self.sub_types(ty_fn_ptr_from, *ty, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("equating {0:?} with {1:?} yields {2:?}",
                                                            ty_fn_ptr_from, ty, terr)))
                                            }))
                                };
                            }
                        }
                        CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer,
                            coercion_source) => {
                            let fn_sig = op.ty(self.body, tcx).fn_sig(tcx);
                            let fn_sig =
                                self.normalize(ty::Unnormalized::new_wip(fn_sig), location);
                            let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            if let Err(terr) =
                                    self.sub_types(ty_fn_ptr_from, *ty, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("equating {0:?} with {1:?} yields {2:?}",
                                                            ty_fn_ptr_from, ty, terr)))
                                            }))
                                };
                            }
                        }
                        CastKind::PointerCoercion(PointerCoercion::Unsize,
                            coercion_source) => {
                            let &ty = ty;
                            let trait_ref =
                                ty::TraitRef::new(tcx,
                                    tcx.require_lang_item(LangItem::CoerceUnsized, span),
                                    [op.ty(self.body, tcx), ty]);
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            let unsize_to =
                                fold_regions(tcx, ty,
                                    |r, _|
                                        {
                                            if let ty::ReVar(_) = r.kind() {
                                                tcx.lifetimes.re_erased
                                            } else { r }
                                        });
                            self.prove_trait_ref(trait_ref, location.to_locations(),
                                ConstraintCategory::Cast {
                                    is_raw_ptr_dyn_type_cast: false,
                                    is_implicit_coercion,
                                    unsize_to: Some(unsize_to),
                                });
                        }
                        CastKind::PointerCoercion(PointerCoercion::MutToConstPointer,
                            coercion_source) => {
                            let ty::RawPtr(ty_from, hir::Mutability::Mut) =
                                op.ty(self.body,
                                        tcx).kind() else {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("unexpected base type for cast {0:?}", ty)))
                                                }))
                                    };
                                    return;
                                };
                            let ty::RawPtr(ty_to, hir::Mutability::Not) =
                                ty.kind() else {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("unexpected target type for cast {0:?}", ty)))
                                                }))
                                    };
                                    return;
                                };
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            if let Err(terr) =
                                    self.sub_types(*ty_from, *ty_to, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("relating {0:?} with {1:?} yields {2:?}",
                                                            ty_from, ty_to, terr)))
                                            }))
                                };
                            }
                        }
                        CastKind::PointerCoercion(PointerCoercion::ArrayToPointer,
                            coercion_source) => {
                            let ty_from = op.ty(self.body, tcx);
                            let opt_ty_elem_mut =
                                match ty_from.kind() {
                                    ty::RawPtr(array_ty, array_mut) =>
                                        match array_ty.kind() {
                                            ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
                                            _ => None,
                                        },
                                    _ => None,
                                };
                            let Some((ty_elem, ty_mut)) =
                                opt_ty_elem_mut else {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("ArrayToPointer cast from unexpected type {0:?}",
                                                                ty_from)))
                                                }))
                                    };
                                    return;
                                };
                            let (ty_to, ty_to_mut) =
                                match ty.kind() {
                                    ty::RawPtr(ty_to, ty_to_mut) => (ty_to, *ty_to_mut),
                                    _ => {
                                        {
                                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                                ::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                                self.body().source.def_id(), rvalue,
                                                                format_args!("ArrayToPointer cast to unexpected type {0:?}",
                                                                    ty)))
                                                    }))
                                        };
                                        return;
                                    }
                                };
                            if ty_to_mut.is_mut() && ty_mut.is_not() {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("ArrayToPointer cast from const {0:?} to mut {1:?}",
                                                            ty, ty_to)))
                                            }))
                                };
                                return;
                            }
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            if let Err(terr) =
                                    self.sub_types(*ty_elem, *ty_to, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("relating {0:?} with {1:?} yields {2:?}",
                                                            ty_elem, ty_to, terr)))
                                            }))
                                }
                            }
                        }
                        CastKind::PointerExposeProvenance => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_)))
                                    => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid PointerExposeProvenance cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::PointerWithExposedProvenance => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid PointerWithExposedProvenance cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::IntToInt => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid IntToInt cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::IntToFloat => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid IntToFloat cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::FloatToInt => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid FloatToInt cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::FloatToFloat => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Float), Some(CastTy::Float)) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid FloatToFloat cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::FnPtrToPtr => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid FnPtrToPtr cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::PtrToPtr => {
                            let ty_from = op.ty(self.body, tcx);
                            let Some(CastTy::Ptr(src)) =
                                CastTy::from_ty(ty_from) else {
                                    ::core::panicking::panic("internal error: entered unreachable code");
                                };
                            let Some(CastTy::Ptr(dst)) =
                                CastTy::from_ty(*ty) else {
                                    ::core::panicking::panic("internal error: entered unreachable code");
                                };
                            if self.infcx.type_is_sized_modulo_regions(self.infcx.param_env,
                                    dst.ty) {
                                let trait_ref =
                                    ty::TraitRef::new(tcx,
                                        tcx.require_lang_item(LangItem::Sized, self.last_span),
                                        [dst.ty]);
                                self.prove_trait_ref(trait_ref, location.to_locations(),
                                    ConstraintCategory::Cast {
                                        is_raw_ptr_dyn_type_cast: false,
                                        is_implicit_coercion: true,
                                        unsize_to: None,
                                    });
                            } else if let ty::Dynamic(src_tty, src_lt) =
                                        *self.struct_tail(src.ty, location).kind() &&
                                    let ty::Dynamic(dst_tty, dst_lt) =
                                        *self.struct_tail(dst.ty, location).kind() {
                                match (src_tty.principal(), dst_tty.principal()) {
                                    (Some(_), Some(_)) => {
                                        let src_obj =
                                            Ty::new_dynamic(tcx,
                                                tcx.mk_poly_existential_predicates(&src_tty.without_auto_traits().collect::<Vec<_>>()),
                                                src_lt);
                                        let dst_obj =
                                            Ty::new_dynamic(tcx,
                                                tcx.mk_poly_existential_predicates(&dst_tty.without_auto_traits().collect::<Vec<_>>()),
                                                dst_lt);
                                        {
                                            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/type_check/mod.rs:1532",
                                                                "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                                                ::tracing_core::__macro_support::Option::Some(1532u32),
                                                                ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                                                ::tracing_core::field::FieldSet::new(&["src_tty", "dst_tty",
                                                                                "src_obj", "dst_obj"],
                                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                ::tracing::metadata::Kind::EVENT)
                                                        };
                                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                                };
                                            let enabled =
                                                ::tracing::Level::DEBUG <=
                                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                        ::tracing::Level::DEBUG <=
                                                            ::tracing::level_filters::LevelFilter::current() &&
                                                    {
                                                        let interest = __CALLSITE.interest();
                                                        !interest.is_never() &&
                                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                interest)
                                                    };
                                            if enabled {
                                                (|value_set: ::tracing::field::ValueSet|
                                                            {
                                                                let meta = __CALLSITE.metadata();
                                                                ::tracing::Event::dispatch(meta, &value_set);
                                                                ;
                                                            })({
                                                        #[allow(unused_imports)]
                                                        use ::tracing::field::{debug, display, Value};
                                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                            ::tracing::__macro_support::Option::Some(&debug(&src_tty) as
                                                                                    &dyn Value)),
                                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                            ::tracing::__macro_support::Option::Some(&debug(&dst_tty) as
                                                                                    &dyn Value)),
                                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                            ::tracing::__macro_support::Option::Some(&debug(&src_obj) as
                                                                                    &dyn Value)),
                                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                            ::tracing::__macro_support::Option::Some(&debug(&dst_obj) as
                                                                                    &dyn Value))])
                                                    });
                                            } else { ; }
                                        };
                                        self.sub_types(src_obj, dst_obj, location.to_locations(),
                                                ConstraintCategory::Cast {
                                                    is_raw_ptr_dyn_type_cast: true,
                                                    is_implicit_coercion: false,
                                                    unsize_to: None,
                                                }).unwrap();
                                    }
                                    (None, None) => {
                                        let src_lt = self.universal_regions.to_region_vid(src_lt);
                                        let dst_lt = self.universal_regions.to_region_vid(dst_lt);
                                        self.constraints.outlives_constraints.push(OutlivesConstraint {
                                                sup: src_lt,
                                                sub: dst_lt,
                                                locations: location.to_locations(),
                                                span: location.to_locations().span(self.body),
                                                category: ConstraintCategory::Cast {
                                                    is_raw_ptr_dyn_type_cast: true,
                                                    is_implicit_coercion: false,
                                                    unsize_to: None,
                                                },
                                                variance_info: ty::VarianceDiagInfo::default(),
                                                from_closure: false,
                                            });
                                    }
                                    (None, Some(_)) =>
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("introducing a principal should have errored in HIR typeck")),
                                    (Some(_), None) => {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("dropping the principal should have been an unsizing cast"))
                                    }
                                }
                            }
                        }
                        CastKind::Transmute => {
                            let ty_from = op.ty(self.body, tcx);
                            match ty_from.kind() {
                                ty::Pat(base, _) if base == ty => {}
                                _ => {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("Unexpected CastKind::Transmute {0:?} -> {1:?}, which is not permitted in Analysis MIR",
                                                            ty_from, ty)))
                                            }))
                                }
                            }
                        }
                        CastKind::Subtype => {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("CastKind::Subtype shouldn\'t exist in borrowck"))
                        }
                    }
                }
                Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
                    self.add_reborrow_constraint(location, *region,
                        borrowed_place);
                }
                Rvalue::Reborrow(target, mutability, borrowed_place) => {
                    self.add_generic_reborrow_constraint(*mutability, location,
                        borrowed_place, *target);
                }
                Rvalue::BinaryOp(BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le
                    | BinOp::Gt | BinOp::Ge, (left, right)) => {
                    let ty_left = left.ty(self.body, tcx);
                    match ty_left.kind() {
                        ty::RawPtr(_, _) | ty::FnPtr(..) => {
                            let ty_right = right.ty(self.body, tcx);
                            let common_ty =
                                self.infcx.next_ty_var(self.body.source_info(location).span);
                            self.sub_types(ty_left, common_ty, location.to_locations(),
                                    ConstraintCategory::CallArgument(None)).unwrap_or_else(|err|
                                    {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("Could not equate type variable with {0:?}: {1:?}",
                                                ty_left, err))
                                    });
                            if let Err(terr) =
                                    self.sub_types(ty_right, common_ty, location.to_locations(),
                                        ConstraintCategory::CallArgument(None)) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("unexpected comparison types {0:?} and {1:?} yields {2:?}",
                                                            ty_left, ty_right, terr)))
                                            }))
                                }
                            }
                        }
                        ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char |
                            ty::Float(_) if ty_left == right.ty(self.body, tcx) => {}
                        _ => {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), rvalue,
                                                format_args!("unexpected comparison types {0:?} and {1:?}",
                                                    ty_left, right.ty(self.body, tcx))))
                                    }))
                        }
                    }
                }
                Rvalue::WrapUnsafeBinder(op, ty) => {
                    let operand_ty = op.ty(self.body, self.tcx());
                    let ty::UnsafeBinder(binder_ty) =
                        *ty.kind() else {
                            ::core::panicking::panic("internal error: entered unreachable code");
                        };
                    let expected_ty =
                        self.infcx.instantiate_binder_with_fresh_vars(self.body().source_info(location).span,
                            BoundRegionConversionTime::HigherRankedType,
                            binder_ty.into());
                    self.sub_types(operand_ty, expected_ty,
                            location.to_locations(),
                            ConstraintCategory::Boring).unwrap();
                }
                Rvalue::Use(_, _) | Rvalue::UnaryOp(_, _) |
                    Rvalue::CopyForDeref(_) | Rvalue::BinaryOp(..) |
                    Rvalue::RawPtr(..) | Rvalue::ThreadLocalRef(..) |
                    Rvalue::Discriminant(..) => {}
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
986    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
987        self.super_rvalue(rvalue, location);
988        let tcx = self.tcx();
989        let span = self.body.source_info(location).span;
990        match rvalue {
991            Rvalue::Aggregate(ak, ops) => self.check_aggregate_rvalue(rvalue, ak, ops, location),
992
993            Rvalue::Repeat(operand, len) => {
994                let array_ty = rvalue.ty(self.body.local_decls(), tcx);
995                self.prove_clause(
996                    ty::ClauseKind::WellFormed(array_ty.into()),
997                    Locations::Single(location),
998                    ConstraintCategory::Boring,
999                );
1000
1001                // If the length cannot be evaluated we must assume that the length can be larger
1002                // than 1.
1003                // If the length is larger than 1, the repeat expression will need to copy the
1004                // element, so we require the `Copy` trait.
1005                if len.try_to_target_usize(tcx).is_none_or(|len| len > 1) {
1006                    match operand {
1007                        Operand::Copy(..) | Operand::Constant(..) | Operand::RuntimeChecks(_) => {
1008                            // These are always okay: direct use of a const, or a value that can
1009                            // evidently be copied.
1010                        }
1011                        Operand::Move(place) => {
1012                            // Make sure that repeated elements implement `Copy`.
1013                            let ty = place.ty(self.body, tcx).ty;
1014                            let trait_ref = ty::TraitRef::new(
1015                                tcx,
1016                                tcx.require_lang_item(LangItem::Copy, span),
1017                                [ty],
1018                            );
1019
1020                            self.prove_trait_ref(
1021                                trait_ref,
1022                                Locations::Single(location),
1023                                ConstraintCategory::CopyBound,
1024                            );
1025                        }
1026                    }
1027                }
1028            }
1029
1030            Rvalue::Cast(cast_kind, op, ty) => {
1031                match *cast_kind {
1032                    CastKind::PointerCoercion(
1033                        PointerCoercion::ReifyFnPointer(target_safety),
1034                        coercion_source,
1035                    ) => {
1036                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1037                        let src_ty = op.ty(self.body, tcx);
1038                        let mut src_sig = src_ty.fn_sig(tcx);
1039                        if let ty::FnDef(def_id, _) = *src_ty.kind()
1040                            && let ty::FnPtr(_, target_hdr) = *ty.kind()
1041                            && tcx.codegen_fn_attrs(def_id).safe_target_features
1042                            && target_hdr.safety().is_safe()
1043                            && let Some(safe_sig) = tcx.adjust_target_feature_sig(
1044                                def_id,
1045                                src_sig,
1046                                self.body.source.def_id(),
1047                            )
1048                        {
1049                            src_sig = safe_sig;
1050                        }
1051
1052                        if src_sig.safety().is_safe() && target_safety.is_unsafe() {
1053                            src_sig = tcx.safe_to_unsafe_sig(src_sig);
1054                        }
1055
1056                        // HACK: This shouldn't be necessary... We can remove this when we actually
1057                        // get binders with where clauses, then elaborate implied bounds into that
1058                        // binder, and implement a higher-ranked subtyping algorithm that actually
1059                        // respects these implied bounds.
1060                        //
1061                        // This protects against the case where we are casting from a higher-ranked
1062                        // fn item to a non-higher-ranked fn pointer, where the cast throws away
1063                        // implied bounds that would've needed to be checked at the call site. This
1064                        // only works when we're casting to a non-higher-ranked fn ptr, since
1065                        // placeholders in the target signature could have untracked implied
1066                        // bounds, resulting in incorrect errors.
1067                        //
1068                        // We check that this signature is WF before subtyping the signature with
1069                        // the target fn sig.
1070                        if src_sig.has_bound_regions()
1071                            && let ty::FnPtr(target_fn_tys, target_hdr) = *ty.kind()
1072                            && let target_sig = target_fn_tys.with(target_hdr)
1073                            && let Some(target_sig) = target_sig.no_bound_vars()
1074                        {
1075                            let src_sig = self.infcx.instantiate_binder_with_fresh_vars(
1076                                span,
1077                                BoundRegionConversionTime::HigherRankedType,
1078                                src_sig,
1079                            );
1080                            let src_ty = Ty::new_fn_ptr(self.tcx(), ty::Binder::dummy(src_sig));
1081                            self.prove_clause(
1082                                ty::ClauseKind::WellFormed(src_ty.into()),
1083                                location.to_locations(),
1084                                ConstraintCategory::Cast {
1085                                    is_raw_ptr_dyn_type_cast: false,
1086                                    is_implicit_coercion,
1087                                    unsize_to: None,
1088                                },
1089                            );
1090
1091                            let src_ty =
1092                                self.normalize(ty::Unnormalized::new_wip(src_ty), location);
1093                            if let Err(terr) = self.sub_types(
1094                                src_ty,
1095                                *ty,
1096                                location.to_locations(),
1097                                ConstraintCategory::Cast {
1098                                    is_raw_ptr_dyn_type_cast: false,
1099                                    is_implicit_coercion,
1100                                    unsize_to: None,
1101                                },
1102                            ) {
1103                                span_mirbug!(
1104                                    self,
1105                                    rvalue,
1106                                    "equating {:?} with {:?} yields {:?}",
1107                                    target_sig,
1108                                    src_sig,
1109                                    terr
1110                                );
1111                            };
1112                        }
1113
1114                        let src_ty = Ty::new_fn_ptr(tcx, src_sig);
1115                        // HACK: We want to assert that the signature of the source fn is
1116                        // well-formed, because we don't enforce that via the WF of FnDef
1117                        // types normally. This should be removed when we improve the tracking
1118                        // of implied bounds of fn signatures.
1119                        self.prove_clause(
1120                            ty::ClauseKind::WellFormed(src_ty.into()),
1121                            location.to_locations(),
1122                            ConstraintCategory::Cast {
1123                                is_raw_ptr_dyn_type_cast: false,
1124                                is_implicit_coercion,
1125                                unsize_to: None,
1126                            },
1127                        );
1128
1129                        // The type that we see in the fcx is like
1130                        // `foo::<'a, 'b>`, where `foo` is the path to a
1131                        // function definition. When we extract the
1132                        // signature, it comes from the `fn_sig` query,
1133                        // and hence may contain unnormalized results.
1134                        let src_ty = self.normalize(ty::Unnormalized::new_wip(src_ty), location);
1135                        if let Err(terr) = self.sub_types(
1136                            src_ty,
1137                            *ty,
1138                            location.to_locations(),
1139                            ConstraintCategory::Cast {
1140                                is_raw_ptr_dyn_type_cast: false,
1141                                is_implicit_coercion,
1142                                unsize_to: None,
1143                            },
1144                        ) {
1145                            span_mirbug!(
1146                                self,
1147                                rvalue,
1148                                "equating {:?} with {:?} yields {:?}",
1149                                src_ty,
1150                                ty,
1151                                terr
1152                            );
1153                        }
1154                    }
1155
1156                    CastKind::PointerCoercion(
1157                        PointerCoercion::ClosureFnPointer(safety),
1158                        coercion_source,
1159                    ) => {
1160                        let sig = match op.ty(self.body, tcx).kind() {
1161                            ty::Closure(_, args) => args.as_closure().sig(),
1162                            _ => bug!(),
1163                        };
1164                        let ty_fn_ptr_from =
1165                            Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, safety));
1166
1167                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1168                        if let Err(terr) = self.sub_types(
1169                            ty_fn_ptr_from,
1170                            *ty,
1171                            location.to_locations(),
1172                            ConstraintCategory::Cast {
1173                                is_raw_ptr_dyn_type_cast: false,
1174                                is_implicit_coercion,
1175                                unsize_to: None,
1176                            },
1177                        ) {
1178                            span_mirbug!(
1179                                self,
1180                                rvalue,
1181                                "equating {:?} with {:?} yields {:?}",
1182                                ty_fn_ptr_from,
1183                                ty,
1184                                terr
1185                            );
1186                        }
1187                    }
1188
1189                    CastKind::PointerCoercion(
1190                        PointerCoercion::UnsafeFnPointer,
1191                        coercion_source,
1192                    ) => {
1193                        let fn_sig = op.ty(self.body, tcx).fn_sig(tcx);
1194
1195                        // The type that we see in the fcx is like
1196                        // `foo::<'a, 'b>`, where `foo` is the path to a
1197                        // function definition. When we extract the
1198                        // signature, it comes from the `fn_sig` query,
1199                        // and hence may contain unnormalized results.
1200                        let fn_sig = self.normalize(ty::Unnormalized::new_wip(fn_sig), location);
1201
1202                        let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1203
1204                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1205                        if let Err(terr) = self.sub_types(
1206                            ty_fn_ptr_from,
1207                            *ty,
1208                            location.to_locations(),
1209                            ConstraintCategory::Cast {
1210                                is_raw_ptr_dyn_type_cast: false,
1211                                is_implicit_coercion,
1212                                unsize_to: None,
1213                            },
1214                        ) {
1215                            span_mirbug!(
1216                                self,
1217                                rvalue,
1218                                "equating {:?} with {:?} yields {:?}",
1219                                ty_fn_ptr_from,
1220                                ty,
1221                                terr
1222                            );
1223                        }
1224                    }
1225
1226                    CastKind::PointerCoercion(PointerCoercion::Unsize, coercion_source) => {
1227                        let &ty = ty;
1228                        let trait_ref = ty::TraitRef::new(
1229                            tcx,
1230                            tcx.require_lang_item(LangItem::CoerceUnsized, span),
1231                            [op.ty(self.body, tcx), ty],
1232                        );
1233
1234                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1235                        let unsize_to = fold_regions(tcx, ty, |r, _| {
1236                            if let ty::ReVar(_) = r.kind() { tcx.lifetimes.re_erased } else { r }
1237                        });
1238                        self.prove_trait_ref(
1239                            trait_ref,
1240                            location.to_locations(),
1241                            ConstraintCategory::Cast {
1242                                is_raw_ptr_dyn_type_cast: false,
1243                                is_implicit_coercion,
1244                                unsize_to: Some(unsize_to),
1245                            },
1246                        );
1247                    }
1248
1249                    CastKind::PointerCoercion(
1250                        PointerCoercion::MutToConstPointer,
1251                        coercion_source,
1252                    ) => {
1253                        let ty::RawPtr(ty_from, hir::Mutability::Mut) =
1254                            op.ty(self.body, tcx).kind()
1255                        else {
1256                            span_mirbug!(self, rvalue, "unexpected base type for cast {:?}", ty,);
1257                            return;
1258                        };
1259                        let ty::RawPtr(ty_to, hir::Mutability::Not) = ty.kind() else {
1260                            span_mirbug!(self, rvalue, "unexpected target type for cast {:?}", ty,);
1261                            return;
1262                        };
1263                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1264                        if let Err(terr) = self.sub_types(
1265                            *ty_from,
1266                            *ty_to,
1267                            location.to_locations(),
1268                            ConstraintCategory::Cast {
1269                                is_raw_ptr_dyn_type_cast: false,
1270                                is_implicit_coercion,
1271                                unsize_to: None,
1272                            },
1273                        ) {
1274                            span_mirbug!(
1275                                self,
1276                                rvalue,
1277                                "relating {:?} with {:?} yields {:?}",
1278                                ty_from,
1279                                ty_to,
1280                                terr
1281                            );
1282                        }
1283                    }
1284
1285                    CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, coercion_source) => {
1286                        let ty_from = op.ty(self.body, tcx);
1287
1288                        let opt_ty_elem_mut = match ty_from.kind() {
1289                            ty::RawPtr(array_ty, array_mut) => match array_ty.kind() {
1290                                ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
1291                                _ => None,
1292                            },
1293                            _ => None,
1294                        };
1295
1296                        let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
1297                            span_mirbug!(
1298                                self,
1299                                rvalue,
1300                                "ArrayToPointer cast from unexpected type {:?}",
1301                                ty_from,
1302                            );
1303                            return;
1304                        };
1305
1306                        let (ty_to, ty_to_mut) = match ty.kind() {
1307                            ty::RawPtr(ty_to, ty_to_mut) => (ty_to, *ty_to_mut),
1308                            _ => {
1309                                span_mirbug!(
1310                                    self,
1311                                    rvalue,
1312                                    "ArrayToPointer cast to unexpected type {:?}",
1313                                    ty,
1314                                );
1315                                return;
1316                            }
1317                        };
1318
1319                        if ty_to_mut.is_mut() && ty_mut.is_not() {
1320                            span_mirbug!(
1321                                self,
1322                                rvalue,
1323                                "ArrayToPointer cast from const {:?} to mut {:?}",
1324                                ty,
1325                                ty_to
1326                            );
1327                            return;
1328                        }
1329
1330                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1331                        if let Err(terr) = self.sub_types(
1332                            *ty_elem,
1333                            *ty_to,
1334                            location.to_locations(),
1335                            ConstraintCategory::Cast {
1336                                is_raw_ptr_dyn_type_cast: false,
1337                                is_implicit_coercion,
1338                                unsize_to: None,
1339                            },
1340                        ) {
1341                            span_mirbug!(
1342                                self,
1343                                rvalue,
1344                                "relating {:?} with {:?} yields {:?}",
1345                                ty_elem,
1346                                ty_to,
1347                                terr
1348                            )
1349                        }
1350                    }
1351
1352                    CastKind::PointerExposeProvenance => {
1353                        let ty_from = op.ty(self.body, tcx);
1354                        let cast_ty_from = CastTy::from_ty(ty_from);
1355                        let cast_ty_to = CastTy::from_ty(*ty);
1356                        match (cast_ty_from, cast_ty_to) {
1357                            (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
1358                            _ => {
1359                                span_mirbug!(
1360                                    self,
1361                                    rvalue,
1362                                    "Invalid PointerExposeProvenance cast {:?} -> {:?}",
1363                                    ty_from,
1364                                    ty
1365                                )
1366                            }
1367                        }
1368                    }
1369
1370                    CastKind::PointerWithExposedProvenance => {
1371                        let ty_from = op.ty(self.body, tcx);
1372                        let cast_ty_from = CastTy::from_ty(ty_from);
1373                        let cast_ty_to = CastTy::from_ty(*ty);
1374                        match (cast_ty_from, cast_ty_to) {
1375                            (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
1376                            _ => {
1377                                span_mirbug!(
1378                                    self,
1379                                    rvalue,
1380                                    "Invalid PointerWithExposedProvenance cast {:?} -> {:?}",
1381                                    ty_from,
1382                                    ty
1383                                )
1384                            }
1385                        }
1386                    }
1387                    CastKind::IntToInt => {
1388                        let ty_from = op.ty(self.body, tcx);
1389                        let cast_ty_from = CastTy::from_ty(ty_from);
1390                        let cast_ty_to = CastTy::from_ty(*ty);
1391                        match (cast_ty_from, cast_ty_to) {
1392                            (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
1393                            _ => {
1394                                span_mirbug!(
1395                                    self,
1396                                    rvalue,
1397                                    "Invalid IntToInt cast {:?} -> {:?}",
1398                                    ty_from,
1399                                    ty
1400                                )
1401                            }
1402                        }
1403                    }
1404                    CastKind::IntToFloat => {
1405                        let ty_from = op.ty(self.body, tcx);
1406                        let cast_ty_from = CastTy::from_ty(ty_from);
1407                        let cast_ty_to = CastTy::from_ty(*ty);
1408                        match (cast_ty_from, cast_ty_to) {
1409                            (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
1410                            _ => {
1411                                span_mirbug!(
1412                                    self,
1413                                    rvalue,
1414                                    "Invalid IntToFloat cast {:?} -> {:?}",
1415                                    ty_from,
1416                                    ty
1417                                )
1418                            }
1419                        }
1420                    }
1421                    CastKind::FloatToInt => {
1422                        let ty_from = op.ty(self.body, tcx);
1423                        let cast_ty_from = CastTy::from_ty(ty_from);
1424                        let cast_ty_to = CastTy::from_ty(*ty);
1425                        match (cast_ty_from, cast_ty_to) {
1426                            (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
1427                            _ => {
1428                                span_mirbug!(
1429                                    self,
1430                                    rvalue,
1431                                    "Invalid FloatToInt cast {:?} -> {:?}",
1432                                    ty_from,
1433                                    ty
1434                                )
1435                            }
1436                        }
1437                    }
1438                    CastKind::FloatToFloat => {
1439                        let ty_from = op.ty(self.body, tcx);
1440                        let cast_ty_from = CastTy::from_ty(ty_from);
1441                        let cast_ty_to = CastTy::from_ty(*ty);
1442                        match (cast_ty_from, cast_ty_to) {
1443                            (Some(CastTy::Float), Some(CastTy::Float)) => (),
1444                            _ => {
1445                                span_mirbug!(
1446                                    self,
1447                                    rvalue,
1448                                    "Invalid FloatToFloat cast {:?} -> {:?}",
1449                                    ty_from,
1450                                    ty
1451                                )
1452                            }
1453                        }
1454                    }
1455                    CastKind::FnPtrToPtr => {
1456                        let ty_from = op.ty(self.body, tcx);
1457                        let cast_ty_from = CastTy::from_ty(ty_from);
1458                        let cast_ty_to = CastTy::from_ty(*ty);
1459                        match (cast_ty_from, cast_ty_to) {
1460                            (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
1461                            _ => {
1462                                span_mirbug!(
1463                                    self,
1464                                    rvalue,
1465                                    "Invalid FnPtrToPtr cast {:?} -> {:?}",
1466                                    ty_from,
1467                                    ty
1468                                )
1469                            }
1470                        }
1471                    }
1472                    CastKind::PtrToPtr => {
1473                        let ty_from = op.ty(self.body, tcx);
1474                        let Some(CastTy::Ptr(src)) = CastTy::from_ty(ty_from) else {
1475                            unreachable!();
1476                        };
1477                        let Some(CastTy::Ptr(dst)) = CastTy::from_ty(*ty) else {
1478                            unreachable!();
1479                        };
1480
1481                        if self.infcx.type_is_sized_modulo_regions(self.infcx.param_env, dst.ty) {
1482                            // Wide to thin ptr cast. This may even occur in an env with
1483                            // impossible predicates, such as `where dyn Trait: Sized`.
1484                            // In this case, we don't want to fall into the case below,
1485                            // since the types may not actually be equatable, but it's
1486                            // fine to perform this operation in an impossible env.
1487                            let trait_ref = ty::TraitRef::new(
1488                                tcx,
1489                                tcx.require_lang_item(LangItem::Sized, self.last_span),
1490                                [dst.ty],
1491                            );
1492                            self.prove_trait_ref(
1493                                trait_ref,
1494                                location.to_locations(),
1495                                ConstraintCategory::Cast {
1496                                    is_raw_ptr_dyn_type_cast: false,
1497                                    is_implicit_coercion: true,
1498                                    unsize_to: None,
1499                                },
1500                            );
1501                        } else if let ty::Dynamic(src_tty, src_lt) =
1502                            *self.struct_tail(src.ty, location).kind()
1503                            && let ty::Dynamic(dst_tty, dst_lt) =
1504                                *self.struct_tail(dst.ty, location).kind()
1505                        {
1506                            match (src_tty.principal(), dst_tty.principal()) {
1507                                (Some(_), Some(_)) => {
1508                                    // This checks (lifetime part of) vtable validity for pointer casts,
1509                                    // which is irrelevant when there are aren't principal traits on
1510                                    // both sides (aka only auto traits).
1511                                    //
1512                                    // Note that other checks (such as denying `dyn Send` -> `dyn
1513                                    // Debug`) are in `rustc_hir_typeck`.
1514
1515                                    // Remove auto traits.
1516                                    // Auto trait checks are handled in `rustc_hir_typeck`.
1517                                    let src_obj = Ty::new_dynamic(
1518                                        tcx,
1519                                        tcx.mk_poly_existential_predicates(
1520                                            &src_tty.without_auto_traits().collect::<Vec<_>>(),
1521                                        ),
1522                                        src_lt,
1523                                    );
1524                                    let dst_obj = Ty::new_dynamic(
1525                                        tcx,
1526                                        tcx.mk_poly_existential_predicates(
1527                                            &dst_tty.without_auto_traits().collect::<Vec<_>>(),
1528                                        ),
1529                                        dst_lt,
1530                                    );
1531
1532                                    debug!(?src_tty, ?dst_tty, ?src_obj, ?dst_obj);
1533
1534                                    // Trait parameters are invariant, the only part that actually has
1535                                    // subtyping here is the lifetime bound of the dyn-type.
1536                                    //
1537                                    // For example in `dyn Trait<'a> + 'b <: dyn Trait<'c> + 'd`  we would
1538                                    // require that `'a == 'c` but only that `'b: 'd`.
1539                                    //
1540                                    // We must not allow freely casting lifetime bounds of dyn-types as it
1541                                    // may allow for inaccessible VTable methods being callable: #136702
1542                                    self.sub_types(
1543                                        src_obj,
1544                                        dst_obj,
1545                                        location.to_locations(),
1546                                        ConstraintCategory::Cast {
1547                                            is_raw_ptr_dyn_type_cast: true,
1548                                            is_implicit_coercion: false,
1549                                            unsize_to: None,
1550                                        },
1551                                    )
1552                                    .unwrap();
1553                                }
1554                                (None, None) => {
1555                                    // `struct_tail` returns regions which haven't been mapped
1556                                    // to nll vars yet so we do it here as `outlives_constraints`
1557                                    // expects nll vars.
1558                                    let src_lt = self.universal_regions.to_region_vid(src_lt);
1559                                    let dst_lt = self.universal_regions.to_region_vid(dst_lt);
1560
1561                                    // The principalless (no non-auto traits) case:
1562                                    // You can only cast `dyn Send + 'long` to `dyn Send + 'short`.
1563                                    self.constraints.outlives_constraints.push(
1564                                        OutlivesConstraint {
1565                                            sup: src_lt,
1566                                            sub: dst_lt,
1567                                            locations: location.to_locations(),
1568                                            span: location.to_locations().span(self.body),
1569                                            category: ConstraintCategory::Cast {
1570                                                is_raw_ptr_dyn_type_cast: true,
1571                                                is_implicit_coercion: false,
1572                                                unsize_to: None,
1573                                            },
1574                                            variance_info: ty::VarianceDiagInfo::default(),
1575                                            from_closure: false,
1576                                        },
1577                                    );
1578                                }
1579                                (None, Some(_)) => bug!(
1580                                    "introducing a principal should have errored in HIR typeck"
1581                                ),
1582                                (Some(_), None) => {
1583                                    bug!("dropping the principal should have been an unsizing cast")
1584                                }
1585                            }
1586                        }
1587                    }
1588                    CastKind::Transmute => {
1589                        let ty_from = op.ty(self.body, tcx);
1590                        match ty_from.kind() {
1591                            ty::Pat(base, _) if base == ty => {}
1592                            _ => span_mirbug!(
1593                                self,
1594                                rvalue,
1595                                "Unexpected CastKind::Transmute {ty_from:?} -> {ty:?}, which is not permitted in Analysis MIR",
1596                            ),
1597                        }
1598                    }
1599                    CastKind::Subtype => {
1600                        bug!("CastKind::Subtype shouldn't exist in borrowck")
1601                    }
1602                }
1603            }
1604
1605            Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1606                self.add_reborrow_constraint(location, *region, borrowed_place);
1607            }
1608
1609            Rvalue::Reborrow(target, mutability, borrowed_place) => {
1610                self.add_generic_reborrow_constraint(
1611                    *mutability,
1612                    location,
1613                    borrowed_place,
1614                    *target,
1615                );
1616            }
1617
1618            Rvalue::BinaryOp(
1619                BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
1620                (left, right),
1621            ) => {
1622                let ty_left = left.ty(self.body, tcx);
1623                match ty_left.kind() {
1624                    // Types with regions are comparable if they have a common super-type.
1625                    ty::RawPtr(_, _) | ty::FnPtr(..) => {
1626                        let ty_right = right.ty(self.body, tcx);
1627                        let common_ty =
1628                            self.infcx.next_ty_var(self.body.source_info(location).span);
1629                        self.sub_types(
1630                            ty_left,
1631                            common_ty,
1632                            location.to_locations(),
1633                            ConstraintCategory::CallArgument(None),
1634                        )
1635                        .unwrap_or_else(|err| {
1636                            bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
1637                        });
1638                        if let Err(terr) = self.sub_types(
1639                            ty_right,
1640                            common_ty,
1641                            location.to_locations(),
1642                            ConstraintCategory::CallArgument(None),
1643                        ) {
1644                            span_mirbug!(
1645                                self,
1646                                rvalue,
1647                                "unexpected comparison types {:?} and {:?} yields {:?}",
1648                                ty_left,
1649                                ty_right,
1650                                terr
1651                            )
1652                        }
1653                    }
1654                    // For types with no regions we can just check that the
1655                    // both operands have the same type.
1656                    ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
1657                        if ty_left == right.ty(self.body, tcx) => {}
1658                    // Other types are compared by trait methods, not by
1659                    // `Rvalue::BinaryOp`.
1660                    _ => span_mirbug!(
1661                        self,
1662                        rvalue,
1663                        "unexpected comparison types {:?} and {:?}",
1664                        ty_left,
1665                        right.ty(self.body, tcx)
1666                    ),
1667                }
1668            }
1669
1670            Rvalue::WrapUnsafeBinder(op, ty) => {
1671                let operand_ty = op.ty(self.body, self.tcx());
1672                let ty::UnsafeBinder(binder_ty) = *ty.kind() else {
1673                    unreachable!();
1674                };
1675                let expected_ty = self.infcx.instantiate_binder_with_fresh_vars(
1676                    self.body().source_info(location).span,
1677                    BoundRegionConversionTime::HigherRankedType,
1678                    binder_ty.into(),
1679                );
1680                self.sub_types(
1681                    operand_ty,
1682                    expected_ty,
1683                    location.to_locations(),
1684                    ConstraintCategory::Boring,
1685                )
1686                .unwrap();
1687            }
1688
1689            Rvalue::Use(_, _)
1690            | Rvalue::UnaryOp(_, _)
1691            | Rvalue::CopyForDeref(_)
1692            | Rvalue::BinaryOp(..)
1693            | Rvalue::RawPtr(..)
1694            | Rvalue::ThreadLocalRef(..)
1695            | Rvalue::Discriminant(..) => {}
1696        }
1697    }
1698
1699    #[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("visit_operand",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1699u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["op", "location"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&op)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_operand(op, location);
            if let Operand::Constant(constant) = op {
                let maybe_uneval =
                    match constant.const_ {
                        Const::Val(..) | Const::Ty(_, _) => None,
                        Const::Unevaluated(uv, _) => Some(uv),
                    };
                if let Some(uv) = maybe_uneval {
                    if uv.promoted.is_none() {
                        let tcx = self.tcx();
                        let def_id = uv.def;
                        if tcx.def_kind(def_id) == DefKind::AnonConst &&
                                tcx.anon_const_kind(def_id) ==
                                    ty::AnonConstKind::NonTypeSystemInline {
                            let def_id = def_id.expect_local();
                            let predicates =
                                self.prove_closure_bounds(tcx, def_id, uv.args, location);
                            self.normalize_and_prove_instantiated_predicates(def_id.to_def_id(),
                                predicates, location.to_locations());
                        }
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1700    fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1701        self.super_operand(op, location);
1702        if let Operand::Constant(constant) = op {
1703            let maybe_uneval = match constant.const_ {
1704                Const::Val(..) | Const::Ty(_, _) => None,
1705                Const::Unevaluated(uv, _) => Some(uv),
1706            };
1707
1708            if let Some(uv) = maybe_uneval {
1709                if uv.promoted.is_none() {
1710                    let tcx = self.tcx();
1711                    let def_id = uv.def;
1712                    if tcx.def_kind(def_id) == DefKind::AnonConst
1713                        && tcx.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline
1714                    {
1715                        let def_id = def_id.expect_local();
1716                        let predicates = self.prove_closure_bounds(tcx, def_id, uv.args, location);
1717                        self.normalize_and_prove_instantiated_predicates(
1718                            def_id.to_def_id(),
1719                            predicates,
1720                            location.to_locations(),
1721                        );
1722                    }
1723                }
1724            }
1725        }
1726    }
1727
1728    #[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("visit_const_operand",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1728u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["constant",
                                                    "location"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constant)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_const_operand(constant, location);
            let ty = constant.const_.ty();
            self.infcx.tcx.for_each_free_region(&ty,
                |live_region|
                    {
                        let live_region_vid =
                            self.universal_regions.to_region_vid(live_region);
                        self.constraints.liveness_constraints.add_location(live_region_vid,
                            location);
                    });
            let locations = location.to_locations();
            if let Some(annotation_index) = constant.user_ty {
                if let Err(terr) =
                        self.relate_type_and_user_type(constant.const_.ty(),
                            ty::Invariant,
                            &UserTypeProjection {
                                    base: annotation_index,
                                    projs: ::alloc::vec::Vec::new(),
                                }, locations,
                            ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg))
                    {
                    let annotation =
                        &self.user_type_annotations[annotation_index];
                    {
                        crate::type_check::mirbug(self.tcx(), self.last_span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                            self.body().source.def_id(), constant,
                                            format_args!("bad constant user type {0:?} vs {1:?}: {2:?}",
                                                annotation, constant.const_.ty(), terr)))
                                }))
                    };
                }
            } else {
                let tcx = self.tcx();
                let maybe_uneval =
                    match constant.const_ {
                        Const::Ty(_, ct) =>
                            match ct.kind() {
                                ty::ConstKind::Alias(_, alias_const) =>
                                    match alias_const.kind {
                                        ty::AliasConstKind::Projection { def_id } |
                                            ty::AliasConstKind::Inherent { def_id } |
                                            ty::AliasConstKind::Free { def_id } |
                                            ty::AliasConstKind::Anon { def_id } =>
                                            Some(UnevaluatedConst {
                                                    def: def_id,
                                                    args: alias_const.args,
                                                    promoted: None,
                                                }),
                                    },
                                _ => None,
                            },
                        Const::Unevaluated(uv, _) => Some(uv),
                        _ => None,
                    };
                if let Some(uv) = maybe_uneval {
                    if let Some(promoted) = uv.promoted {
                        let promoted_body = &self.promoted[promoted];
                        self.check_promoted(promoted_body, location);
                        let promoted_ty = promoted_body.return_ty();
                        if let Err(terr) =
                                self.eq_types(ty, promoted_ty, locations,
                                    ConstraintCategory::Boring) {
                            {
                                crate::type_check::mirbug(self.tcx(), self.last_span,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                    self.body().source.def_id(), promoted,
                                                    format_args!("bad promoted type ({0:?}: {1:?}): {2:?}", ty,
                                                        promoted_ty, terr)))
                                        }))
                            };
                        };
                    } else {
                        self.ascribe_user_type(constant.const_.ty(),
                            ty::UserType::new(ty::UserTypeKind::TypeOf(uv.def,
                                    UserArgs { args: uv.args, user_self_ty: None })),
                            locations.span(self.body));
                    }
                } else if let Some(static_def_id) =
                        constant.check_static_ptr(tcx) {
                    let unnormalized_ty =
                        tcx.type_of(static_def_id).instantiate_identity();
                    let normalized_ty =
                        self.normalize(unnormalized_ty, locations);
                    let literal_ty =
                        constant.const_.ty().builtin_deref(true).unwrap();
                    if let Err(terr) =
                            self.eq_types(literal_ty, normalized_ty, locations,
                                ConstraintCategory::Boring) {
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), constant,
                                                format_args!("bad static type {0:?} ({1:?})", constant,
                                                    terr)))
                                    }))
                        };
                    }
                } else if let Const::Ty(_, ct) = constant.const_ &&
                        let ty::ConstKind::Param(p) = ct.kind() {
                    let body_def_id =
                        self.universal_regions.defining_ty.def_id();
                    let const_param =
                        tcx.generics_of(body_def_id).const_param(p, tcx);
                    self.ascribe_user_type(constant.const_.ty(),
                        ty::UserType::new(ty::UserTypeKind::TypeOf(const_param.def_id,
                                UserArgs {
                                    args: self.universal_regions.defining_ty.args(),
                                    user_self_ty: None,
                                })), locations.span(self.body));
                }
                if let ty::FnDef(def_id, args) = *constant.const_.ty().kind()
                    {
                    let instantiated_predicates =
                        tcx.predicates_of(def_id).instantiate(tcx, args);
                    self.normalize_and_prove_instantiated_predicates(def_id,
                        instantiated_predicates, locations);
                    {
                        match (&tcx.trait_impl_of_assoc(def_id), &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);
                                }
                            }
                        }
                    };
                    self.prove_clauses(args.types().map(|ty|
                                ty::ClauseKind::WellFormed(ty.into())), locations,
                        ConstraintCategory::Boring);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1729    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, location: Location) {
1730        self.super_const_operand(constant, location);
1731        let ty = constant.const_.ty();
1732
1733        self.infcx.tcx.for_each_free_region(&ty, |live_region| {
1734            let live_region_vid = self.universal_regions.to_region_vid(live_region);
1735            self.constraints.liveness_constraints.add_location(live_region_vid, location);
1736        });
1737
1738        let locations = location.to_locations();
1739        if let Some(annotation_index) = constant.user_ty {
1740            if let Err(terr) = self.relate_type_and_user_type(
1741                constant.const_.ty(),
1742                ty::Invariant,
1743                &UserTypeProjection { base: annotation_index, projs: vec![] },
1744                locations,
1745                ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg),
1746            ) {
1747                let annotation = &self.user_type_annotations[annotation_index];
1748                span_mirbug!(
1749                    self,
1750                    constant,
1751                    "bad constant user type {:?} vs {:?}: {:?}",
1752                    annotation,
1753                    constant.const_.ty(),
1754                    terr,
1755                );
1756            }
1757        } else {
1758            let tcx = self.tcx();
1759            let maybe_uneval = match constant.const_ {
1760                Const::Ty(_, ct) => match ct.kind() {
1761                    ty::ConstKind::Alias(_, alias_const) => match alias_const.kind {
1762                        ty::AliasConstKind::Projection { def_id }
1763                        | ty::AliasConstKind::Inherent { def_id }
1764                        | ty::AliasConstKind::Free { def_id }
1765                        | ty::AliasConstKind::Anon { def_id } => Some(UnevaluatedConst {
1766                            def: def_id,
1767                            args: alias_const.args,
1768                            promoted: None,
1769                        }),
1770                    },
1771                    _ => None,
1772                },
1773                Const::Unevaluated(uv, _) => Some(uv),
1774                _ => None,
1775            };
1776
1777            if let Some(uv) = maybe_uneval {
1778                if let Some(promoted) = uv.promoted {
1779                    let promoted_body = &self.promoted[promoted];
1780                    self.check_promoted(promoted_body, location);
1781                    let promoted_ty = promoted_body.return_ty();
1782                    if let Err(terr) =
1783                        self.eq_types(ty, promoted_ty, locations, ConstraintCategory::Boring)
1784                    {
1785                        span_mirbug!(
1786                            self,
1787                            promoted,
1788                            "bad promoted type ({:?}: {:?}): {:?}",
1789                            ty,
1790                            promoted_ty,
1791                            terr
1792                        );
1793                    };
1794                } else {
1795                    self.ascribe_user_type(
1796                        constant.const_.ty(),
1797                        ty::UserType::new(ty::UserTypeKind::TypeOf(
1798                            uv.def,
1799                            UserArgs { args: uv.args, user_self_ty: None },
1800                        )),
1801                        locations.span(self.body),
1802                    );
1803                }
1804            } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
1805                let unnormalized_ty = tcx.type_of(static_def_id).instantiate_identity();
1806                let normalized_ty = self.normalize(unnormalized_ty, locations);
1807                let literal_ty = constant.const_.ty().builtin_deref(true).unwrap();
1808
1809                if let Err(terr) =
1810                    self.eq_types(literal_ty, normalized_ty, locations, ConstraintCategory::Boring)
1811                {
1812                    span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
1813                }
1814            } else if let Const::Ty(_, ct) = constant.const_
1815                && let ty::ConstKind::Param(p) = ct.kind()
1816            {
1817                let body_def_id = self.universal_regions.defining_ty.def_id();
1818                let const_param = tcx.generics_of(body_def_id).const_param(p, tcx);
1819                self.ascribe_user_type(
1820                    constant.const_.ty(),
1821                    ty::UserType::new(ty::UserTypeKind::TypeOf(
1822                        const_param.def_id,
1823                        UserArgs {
1824                            args: self.universal_regions.defining_ty.args(),
1825                            user_self_ty: None,
1826                        },
1827                    )),
1828                    locations.span(self.body),
1829                );
1830            }
1831
1832            if let ty::FnDef(def_id, args) = *constant.const_.ty().kind() {
1833                let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, args);
1834                self.normalize_and_prove_instantiated_predicates(
1835                    def_id,
1836                    instantiated_predicates,
1837                    locations,
1838                );
1839
1840                assert_eq!(tcx.trait_impl_of_assoc(def_id), None);
1841                self.prove_clauses(
1842                    args.types().map(|ty| ty::ClauseKind::WellFormed(ty.into())),
1843                    locations,
1844                    ConstraintCategory::Boring,
1845                );
1846            }
1847        }
1848    }
1849
1850    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1851        self.super_place(place, context, location);
1852        let tcx = self.tcx();
1853        let place_ty = place.ty(self.body, tcx);
1854        if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
1855            let trait_ref = ty::TraitRef::new(
1856                tcx,
1857                tcx.require_lang_item(LangItem::Copy, self.last_span),
1858                [place_ty.ty],
1859            );
1860
1861            // To have a `Copy` operand, the type `T` of the
1862            // value must be `Copy`. Note that we prove that `T: Copy`,
1863            // rather than using the `is_copy_modulo_regions`
1864            // test. This is important because
1865            // `is_copy_modulo_regions` ignores the resulting region
1866            // obligations and assumes they pass. This can result in
1867            // bounds from `Copy` impls being unsoundly ignored (e.g.,
1868            // #29149). Note that we decide to use `Copy` before knowing
1869            // whether the bounds fully apply: in effect, the rule is
1870            // that if a value of some type could implement `Copy`, then
1871            // it must.
1872            self.prove_trait_ref(trait_ref, location.to_locations(), ConstraintCategory::CopyBound);
1873        }
1874    }
1875
1876    fn visit_projection_elem(
1877        &mut self,
1878        place: PlaceRef<'tcx>,
1879        elem: PlaceElem<'tcx>,
1880        context: PlaceContext,
1881        location: Location,
1882    ) {
1883        let tcx = self.tcx();
1884        let base_ty = place.ty(self.body(), tcx);
1885        match elem {
1886            // All these projections don't add any constraints, so there's nothing to
1887            // do here. We check their invariants in the MIR validator after all.
1888            ProjectionElem::Deref
1889            | ProjectionElem::Index(_)
1890            | ProjectionElem::ConstantIndex { .. }
1891            | ProjectionElem::Subslice { .. }
1892            | ProjectionElem::Downcast(..) => {}
1893            ProjectionElem::Field(field, fty) => {
1894                let fty = self.normalize(ty::Unnormalized::new_wip(fty), location);
1895                let ty = PlaceTy::field_ty(tcx, base_ty.ty, base_ty.variant_index, field);
1896                let ty = self.normalize(ty, location);
1897                {
    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/type_check/mod.rs:1897",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1897u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["fty", "ty"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&fty) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&ty) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?fty, ?ty);
1898
1899                if let Err(terr) = self.relate_types(
1900                    ty,
1901                    context.ambient_variance(),
1902                    fty,
1903                    location.to_locations(),
1904                    ConstraintCategory::Boring,
1905                ) {
1906                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), place,
                        format_args!("bad field access ({0:?}: {1:?}): {2:?}", ty,
                            fty, terr)))
            }))
};span_mirbug!(self, place, "bad field access ({:?}: {:?}): {:?}", ty, fty, terr);
1907                }
1908            }
1909            ProjectionElem::OpaqueCast(ty) => {
1910                let ty = self.normalize(ty::Unnormalized::new_wip(ty), location);
1911                self.relate_types(
1912                    ty,
1913                    context.ambient_variance(),
1914                    base_ty.ty,
1915                    location.to_locations(),
1916                    ConstraintCategory::TypeAnnotation(AnnotationSource::OpaqueCast),
1917                )
1918                .unwrap();
1919            }
1920            ProjectionElem::UnwrapUnsafeBinder(ty) => {
1921                let ty::UnsafeBinder(binder_ty) = *base_ty.ty.kind() else {
1922                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1923                };
1924                let found_ty = self.infcx.instantiate_binder_with_fresh_vars(
1925                    self.body.source_info(location).span,
1926                    BoundRegionConversionTime::HigherRankedType,
1927                    binder_ty.into(),
1928                );
1929                self.relate_types(
1930                    ty,
1931                    context.ambient_variance(),
1932                    found_ty,
1933                    location.to_locations(),
1934                    ConstraintCategory::Boring,
1935                )
1936                .unwrap();
1937            }
1938        }
1939    }
1940}
1941
1942impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1943    fn check_call_dest(
1944        &mut self,
1945        term: &Terminator<'tcx>,
1946        sig: &ty::FnSig<'tcx>,
1947        destination: Place<'tcx>,
1948        is_diverging: bool,
1949        term_location: Location,
1950    ) {
1951        let tcx = self.tcx();
1952        if is_diverging {
1953            // The signature in this call can reference region variables,
1954            // so erase them before calling a query.
1955            let output_ty = self.tcx().erase_and_anonymize_regions(sig.output());
1956            if !output_ty
1957                .is_privately_uninhabited(self.tcx(), self.infcx.typing_env(self.infcx.param_env))
1958            {
1959                {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), term,
                        format_args!("call to non-diverging function {0:?} w/o dest",
                            sig)))
            }))
};span_mirbug!(self, term, "call to non-diverging function {:?} w/o dest", sig);
1960            }
1961        } else {
1962            let dest_ty = destination.ty(self.body, tcx).ty;
1963            let dest_ty = self.normalize(ty::Unnormalized::new_wip(dest_ty), term_location);
1964            let category = match destination.as_local() {
1965                Some(RETURN_PLACE) => {
1966                    if let DefiningTy::Const(def_id, _) | DefiningTy::InlineConst(def_id, _) =
1967                        self.universal_regions.defining_ty
1968                    {
1969                        if tcx.is_static(def_id) {
1970                            ConstraintCategory::UseAsStatic
1971                        } else {
1972                            ConstraintCategory::UseAsConst
1973                        }
1974                    } else {
1975                        ConstraintCategory::Return(ReturnConstraint::Normal)
1976                    }
1977                }
1978                Some(l) if !self.body.local_decls[l].is_user_variable() => {
1979                    ConstraintCategory::Boring
1980                }
1981                // The return type of a call is interesting for diagnostics.
1982                _ => ConstraintCategory::Assignment,
1983            };
1984
1985            let locations = term_location.to_locations();
1986
1987            if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1988                {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), term,
                        format_args!("call dest mismatch ({0:?} <- {1:?}): {2:?}",
                            dest_ty, sig.output(), terr)))
            }))
};span_mirbug!(
1989                    self,
1990                    term,
1991                    "call dest mismatch ({:?} <- {:?}): {:?}",
1992                    dest_ty,
1993                    sig.output(),
1994                    terr
1995                );
1996            }
1997
1998            // When `unsized_fn_params` is not enabled,
1999            // this check is done at `visit_local_decl`.
2000            if self.tcx().features().unsized_fn_params() {
2001                let span = term.source_info.span;
2002                self.ensure_place_sized(dest_ty, span);
2003            }
2004        }
2005    }
2006
2007    #[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("check_call_inputs",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2007u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["sig", "args"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if args.len() < sig.inputs().len() ||
                    (args.len() > sig.inputs().len() && !sig.c_variadic()) {
                {
                    crate::type_check::mirbug(self.tcx(), self.last_span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                        self.body().source.def_id(), term,
                                        format_args!("call to {0:?} with wrong # of args", sig)))
                            }))
                };
            }
            let func_ty = func.ty(self.body, self.infcx.tcx);
            if let ty::FnDef(def_id, _) = *func_ty.kind() {
                if let Some(name @
                        (sym::simd_shuffle | sym::simd_insert | sym::simd_extract))
                        = self.tcx().intrinsic(def_id).map(|i| i.name) {
                    let idx = match name { sym::simd_shuffle => 2, _ => 1, };
                    if !#[allow(non_exhaustive_omitted_patterns)] match args[idx]
                                {
                                Spanned { node: Operand::Constant(_), .. } => true,
                                _ => false,
                            } {
                        self.tcx().dcx().emit_err(SimdIntrinsicArgConst {
                                span: term.source_info.span,
                                arg: idx + 1,
                                intrinsic: name.to_string(),
                            });
                    }
                }
            }
            {
                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/type_check/mod.rs:2043",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2043u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["func_ty"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&debug(&func_ty) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            for (n, (fn_arg, op_arg)) in
                iter::zip(sig.inputs(), args).enumerate() {
                let op_arg_ty = op_arg.node.ty(self.body, self.tcx());
                let op_arg_ty =
                    self.normalize(ty::Unnormalized::new_wip(op_arg_ty),
                        term_location);
                let category =
                    if call_source.from_hir_call() {
                        ConstraintCategory::CallArgument(Some(self.infcx.tcx.erase_and_anonymize_regions(func_ty)))
                    } else { ConstraintCategory::Boring };
                if let Err(terr) =
                        self.sub_types(op_arg_ty, *fn_arg,
                            term_location.to_locations(), category) {
                    {
                        crate::type_check::mirbug(self.tcx(), self.last_span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                            self.body().source.def_id(), term,
                                            format_args!("bad arg #{0:?} ({1:?} <- {2:?}): {3:?}", n,
                                                fn_arg, op_arg_ty, terr)))
                                }))
                    };
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self, term, func, term_location, call_source))]
2008    fn check_call_inputs(
2009        &mut self,
2010        term: &Terminator<'tcx>,
2011        func: &Operand<'tcx>,
2012        sig: &ty::FnSig<'tcx>,
2013        args: &[Spanned<Operand<'tcx>>],
2014        term_location: Location,
2015        call_source: CallSource,
2016    ) {
2017        if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic())
2018        {
2019            span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
2020        }
2021
2022        let func_ty = func.ty(self.body, self.infcx.tcx);
2023        if let ty::FnDef(def_id, _) = *func_ty.kind() {
2024            // Some of the SIMD intrinsics are special: they need a particular argument to be a
2025            // constant. (Eventually this should use const-generics, but those are not up for the
2026            // task yet: https://github.com/rust-lang/rust/issues/85229.)
2027            if let Some(name @ (sym::simd_shuffle | sym::simd_insert | sym::simd_extract)) =
2028                self.tcx().intrinsic(def_id).map(|i| i.name)
2029            {
2030                let idx = match name {
2031                    sym::simd_shuffle => 2,
2032                    _ => 1,
2033                };
2034                if !matches!(args[idx], Spanned { node: Operand::Constant(_), .. }) {
2035                    self.tcx().dcx().emit_err(SimdIntrinsicArgConst {
2036                        span: term.source_info.span,
2037                        arg: idx + 1,
2038                        intrinsic: name.to_string(),
2039                    });
2040                }
2041            }
2042        }
2043        debug!(?func_ty);
2044
2045        for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
2046            let op_arg_ty = op_arg.node.ty(self.body, self.tcx());
2047
2048            let op_arg_ty = self.normalize(ty::Unnormalized::new_wip(op_arg_ty), term_location);
2049            let category = if call_source.from_hir_call() {
2050                ConstraintCategory::CallArgument(Some(
2051                    self.infcx.tcx.erase_and_anonymize_regions(func_ty),
2052                ))
2053            } else {
2054                ConstraintCategory::Boring
2055            };
2056            if let Err(terr) =
2057                self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
2058            {
2059                span_mirbug!(
2060                    self,
2061                    term,
2062                    "bad arg #{:?} ({:?} <- {:?}): {:?}",
2063                    n,
2064                    fn_arg,
2065                    op_arg_ty,
2066                    terr
2067                );
2068            }
2069        }
2070    }
2071
2072    fn check_iscleanup(&mut self, block_data: &BasicBlockData<'tcx>) {
2073        let is_cleanup = block_data.is_cleanup;
2074        match block_data.terminator().kind {
2075            TerminatorKind::Goto { target } => {
2076                self.assert_iscleanup(block_data, target, is_cleanup)
2077            }
2078            TerminatorKind::SwitchInt { ref targets, .. } => {
2079                for target in targets.all_targets() {
2080                    self.assert_iscleanup(block_data, *target, is_cleanup);
2081                }
2082            }
2083            TerminatorKind::UnwindResume => {
2084                if !is_cleanup {
2085                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("resume on non-cleanup block!")))
            }))
}span_mirbug!(self, block_data, "resume on non-cleanup block!")
2086                }
2087            }
2088            TerminatorKind::UnwindTerminate(_) => {
2089                if !is_cleanup {
2090                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("terminate on non-cleanup block!")))
            }))
}span_mirbug!(self, block_data, "terminate on non-cleanup block!")
2091                }
2092            }
2093            TerminatorKind::Return => {
2094                if is_cleanup {
2095                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("return on cleanup block")))
            }))
}span_mirbug!(self, block_data, "return on cleanup block")
2096                }
2097            }
2098            TerminatorKind::TailCall { .. } => {
2099                if is_cleanup {
2100                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("tailcall on cleanup block")))
            }))
}span_mirbug!(self, block_data, "tailcall on cleanup block")
2101                }
2102            }
2103            TerminatorKind::CoroutineDrop { .. } => {
2104                if is_cleanup {
2105                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("coroutine_drop in cleanup block")))
            }))
}span_mirbug!(self, block_data, "coroutine_drop in cleanup block")
2106                }
2107            }
2108            TerminatorKind::Yield { resume, drop, .. } => {
2109                if is_cleanup {
2110                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("yield in cleanup block")))
            }))
}span_mirbug!(self, block_data, "yield in cleanup block")
2111                }
2112                self.assert_iscleanup(block_data, resume, is_cleanup);
2113                if let Some(drop) = drop {
2114                    self.assert_iscleanup(block_data, drop, is_cleanup);
2115                }
2116            }
2117            TerminatorKind::Unreachable => {}
2118            TerminatorKind::Drop { target, unwind, drop, .. } => {
2119                self.assert_iscleanup(block_data, target, is_cleanup);
2120                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2121                if let Some(drop) = drop {
2122                    self.assert_iscleanup(block_data, drop, is_cleanup);
2123                }
2124            }
2125            TerminatorKind::Assert { target, unwind, .. } => {
2126                self.assert_iscleanup(block_data, target, is_cleanup);
2127                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2128            }
2129            TerminatorKind::Call { ref target, unwind, .. } => {
2130                if let &Some(target) = target {
2131                    self.assert_iscleanup(block_data, target, is_cleanup);
2132                }
2133                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2134            }
2135            TerminatorKind::FalseEdge { real_target, imaginary_target } => {
2136                self.assert_iscleanup(block_data, real_target, is_cleanup);
2137                self.assert_iscleanup(block_data, imaginary_target, is_cleanup);
2138            }
2139            TerminatorKind::FalseUnwind { real_target, unwind } => {
2140                self.assert_iscleanup(block_data, real_target, is_cleanup);
2141                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2142            }
2143            TerminatorKind::InlineAsm { ref targets, unwind, .. } => {
2144                for &target in targets {
2145                    self.assert_iscleanup(block_data, target, is_cleanup);
2146                }
2147                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2148            }
2149        }
2150    }
2151
2152    fn assert_iscleanup(&mut self, ctxt: &dyn fmt::Debug, bb: BasicBlock, iscleanuppad: bool) {
2153        if self.body[bb].is_cleanup != iscleanuppad {
2154            {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), ctxt,
                        format_args!("cleanuppad mismatch: {0:?} should be {1:?}",
                            bb, iscleanuppad)))
            }))
};span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
2155        }
2156    }
2157
2158    fn assert_iscleanup_unwind(
2159        &mut self,
2160        ctxt: &dyn fmt::Debug,
2161        unwind: UnwindAction,
2162        is_cleanup: bool,
2163    ) {
2164        match unwind {
2165            UnwindAction::Cleanup(unwind) => {
2166                if is_cleanup {
2167                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), ctxt,
                        format_args!("unwind on cleanup block")))
            }))
}span_mirbug!(self, ctxt, "unwind on cleanup block")
2168                }
2169                self.assert_iscleanup(ctxt, unwind, true);
2170            }
2171            UnwindAction::Continue => {
2172                if is_cleanup {
2173                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), ctxt,
                        format_args!("unwind on cleanup block")))
            }))
}span_mirbug!(self, ctxt, "unwind on cleanup block")
2174                }
2175            }
2176            UnwindAction::Unreachable | UnwindAction::Terminate(_) => (),
2177        }
2178    }
2179
2180    fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
2181        let tcx = self.tcx();
2182
2183        // Erase the regions from `ty` to get a global type. The
2184        // `Sized` bound in no way depends on precise regions, so this
2185        // shouldn't affect `is_sized`.
2186        let erased_ty = tcx.erase_and_anonymize_regions(ty);
2187        // FIXME(#132279): Using `Ty::is_sized` causes us to incorrectly handle opaques here.
2188        if !erased_ty.is_sized(tcx, self.infcx.typing_env(self.infcx.param_env)) {
2189            // in current MIR construction, all non-control-flow rvalue
2190            // expressions evaluate through `as_temp` or `into` a return
2191            // slot or local, so to find all unsized rvalues it is enough
2192            // to check all temps, return slots and locals.
2193            if self.reported_errors.replace((ty, span)).is_none() {
2194                // While this is located in `nll::typeck` this error is not
2195                // an NLL error, it's a required check to prevent creation
2196                // of unsized rvalues in a call expression.
2197                self.tcx().dcx().emit_err(MoveUnsized { ty, span });
2198            }
2199        }
2200    }
2201
2202    fn aggregate_field_ty(
2203        &mut self,
2204        ak: &AggregateKind<'tcx>,
2205        field_index: FieldIdx,
2206        location: Location,
2207    ) -> Result<Ty<'tcx>, FieldAccessError> {
2208        let tcx = self.tcx();
2209
2210        match *ak {
2211            AggregateKind::Adt(adt_did, variant_index, args, _, active_field_index) => {
2212                let def = tcx.adt_def(adt_did);
2213                let variant = &def.variant(variant_index);
2214                let adj_field_index = active_field_index.unwrap_or(field_index);
2215                if let Some(field) = variant.fields.get(adj_field_index) {
2216                    Ok(self.normalize(field.ty(tcx, args), location))
2217                } else {
2218                    Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
2219                }
2220            }
2221            AggregateKind::Closure(_, args) => {
2222                match args.as_closure().upvar_tys().get(field_index.as_usize()) {
2223                    Some(ty) => Ok(*ty),
2224                    None => Err(FieldAccessError::OutOfRange {
2225                        field_count: args.as_closure().upvar_tys().len(),
2226                    }),
2227                }
2228            }
2229            AggregateKind::Coroutine(_, args) => {
2230                // It doesn't make sense to look at a field beyond the prefix;
2231                // these require a variant index, and are not initialized in
2232                // aggregate rvalues.
2233                match args.as_coroutine().prefix_tys().get(field_index.as_usize()) {
2234                    Some(ty) => Ok(*ty),
2235                    None => Err(FieldAccessError::OutOfRange {
2236                        field_count: args.as_coroutine().prefix_tys().len(),
2237                    }),
2238                }
2239            }
2240            AggregateKind::CoroutineClosure(_, args) => {
2241                match args.as_coroutine_closure().upvar_tys().get(field_index.as_usize()) {
2242                    Some(ty) => Ok(*ty),
2243                    None => Err(FieldAccessError::OutOfRange {
2244                        field_count: args.as_coroutine_closure().upvar_tys().len(),
2245                    }),
2246                }
2247            }
2248            AggregateKind::Array(ty) => Ok(ty),
2249            AggregateKind::Tuple | AggregateKind::RawPtr(..) => {
2250                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("This should have been covered in check_rvalues")));
};unreachable!("This should have been covered in check_rvalues");
2251            }
2252        }
2253    }
2254
2255    /// If this rvalue supports a user-given type annotation, then
2256    /// extract and return it. This represents the final type of the
2257    /// rvalue and will be unified with the inferred type.
2258    fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2259        match rvalue {
2260            Rvalue::Use(..)
2261            | Rvalue::ThreadLocalRef(..)
2262            | Rvalue::Repeat(..)
2263            | Rvalue::Ref(..)
2264            | Rvalue::Reborrow(..)
2265            | Rvalue::RawPtr(..)
2266            | Rvalue::Cast(..)
2267            | Rvalue::BinaryOp(..)
2268            | Rvalue::CopyForDeref(..)
2269            | Rvalue::UnaryOp(..)
2270            | Rvalue::Discriminant(..)
2271            | Rvalue::WrapUnsafeBinder(..) => None,
2272
2273            Rvalue::Aggregate(aggregate, _) => match **aggregate {
2274                AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2275                AggregateKind::Array(_) => None,
2276                AggregateKind::Tuple => None,
2277                AggregateKind::Closure(_, _) => None,
2278                AggregateKind::Coroutine(_, _) => None,
2279                AggregateKind::CoroutineClosure(_, _) => None,
2280                AggregateKind::RawPtr(_, _) => None,
2281            },
2282        }
2283    }
2284
2285    fn check_aggregate_rvalue(
2286        &mut self,
2287        rvalue: &Rvalue<'tcx>,
2288        aggregate_kind: &AggregateKind<'tcx>,
2289        operands: &IndexSlice<FieldIdx, Operand<'tcx>>,
2290        location: Location,
2291    ) {
2292        let tcx = self.tcx();
2293
2294        self.prove_aggregate_predicates(aggregate_kind, location);
2295
2296        if *aggregate_kind == AggregateKind::Tuple {
2297            // tuple rvalue field type is always the type of the op. Nothing to check here.
2298            return;
2299        }
2300
2301        if let AggregateKind::RawPtr(..) = aggregate_kind {
2302            ::rustc_middle::util::bug::bug_fmt(format_args!("RawPtr should only be in runtime MIR"));bug!("RawPtr should only be in runtime MIR");
2303        }
2304
2305        for (i, operand) in operands.iter_enumerated() {
2306            let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2307                Ok(field_ty) => field_ty,
2308                Err(FieldAccessError::OutOfRange { field_count }) => {
2309                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), rvalue,
                        format_args!("accessed field #{0} but variant only has {1}",
                            i.as_u32(), field_count)))
            }))
};span_mirbug!(
2310                        self,
2311                        rvalue,
2312                        "accessed field #{} but variant only has {}",
2313                        i.as_u32(),
2314                        field_count,
2315                    );
2316                    continue;
2317                }
2318            };
2319            let operand_ty = operand.ty(self.body, tcx);
2320            let operand_ty = self.normalize(ty::Unnormalized::new_wip(operand_ty), location);
2321
2322            if let Err(terr) = self.sub_types(
2323                operand_ty,
2324                field_ty,
2325                location.to_locations(),
2326                ConstraintCategory::Boring,
2327            ) {
2328                {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), rvalue,
                        format_args!("{0:?} is not a subtype of {1:?}: {2:?}",
                            operand_ty, field_ty, terr)))
            }))
};span_mirbug!(
2329                    self,
2330                    rvalue,
2331                    "{:?} is not a subtype of {:?}: {:?}",
2332                    operand_ty,
2333                    field_ty,
2334                    terr
2335                );
2336            }
2337        }
2338    }
2339
2340    /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2341    ///
2342    /// # Parameters
2343    ///
2344    /// - `location`: the location `L` where the borrow expression occurs
2345    /// - `borrow_region`: the region `'a` associated with the borrow
2346    /// - `borrowed_place`: the place `P` being borrowed
2347    fn add_reborrow_constraint(
2348        &mut self,
2349        location: Location,
2350        borrow_region: ty::Region<'tcx>,
2351        borrowed_place: &Place<'tcx>,
2352    ) {
2353        // These constraints are only meaningful during borrowck:
2354        let Self { borrow_set, location_table, polonius_facts, constraints, .. } = self;
2355
2356        // In Polonius mode, we also push a `loan_issued_at` fact
2357        // linking the loan to the region (in some cases, though,
2358        // there is no loan associated with this borrow expression --
2359        // that occurs when we are borrowing an unsafe place, for
2360        // example).
2361        if let Some(polonius_facts) = polonius_facts {
2362            let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2363            if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2364                let region_vid = borrow_region.as_var();
2365                polonius_facts.loan_issued_at.push((
2366                    region_vid.into(),
2367                    borrow_index,
2368                    location_table.mid_index(location),
2369                ));
2370            }
2371        }
2372
2373        // If we are reborrowing the referent of another reference, we
2374        // need to add outlives relationships. In a case like `&mut
2375        // *p`, where the `p` has type `&'b mut Foo`, for example, we
2376        // need to ensure that `'b: 'a`.
2377
2378        {
    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/type_check/mod.rs:2378",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2378u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("add_reborrow_constraint({0:?}, {1:?}, {2:?})",
                                                    location, borrow_region, borrowed_place) as &dyn Value))])
            });
    } else { ; }
};debug!(
2379            "add_reborrow_constraint({:?}, {:?}, {:?})",
2380            location, borrow_region, borrowed_place
2381        );
2382
2383        let tcx = self.infcx.tcx;
2384        let def = self.body.source.def_id().expect_local();
2385        let upvars = tcx.closure_captures(def);
2386        let field =
2387            path_utils::is_upvar_field_projection(tcx, upvars, borrowed_place.as_ref(), self.body);
2388        let category = if let Some(field) = field {
2389            ConstraintCategory::ClosureUpvar(field)
2390        } else {
2391            ConstraintCategory::Boring
2392        };
2393
2394        for (base, elem) in borrowed_place.as_ref().iter_projections().rev() {
2395            {
    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/type_check/mod.rs:2395",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2395u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("add_reborrow_constraint - iteration {0:?}",
                                                    elem) as &dyn Value))])
            });
    } else { ; }
};debug!("add_reborrow_constraint - iteration {:?}", elem);
2396
2397            match elem {
2398                ProjectionElem::Deref => {
2399                    let base_ty = base.ty(self.body, tcx).ty;
2400
2401                    {
    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/type_check/mod.rs:2401",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2401u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("add_reborrow_constraint - base_ty = {0:?}",
                                                    base_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2402                    match base_ty.kind() {
2403                        ty::Ref(ref_region, _, mutbl) => {
2404                            constraints.outlives_constraints.push(OutlivesConstraint {
2405                                sup: ref_region.as_var(),
2406                                sub: borrow_region.as_var(),
2407                                locations: location.to_locations(),
2408                                span: location.to_locations().span(self.body),
2409                                category,
2410                                variance_info: ty::VarianceDiagInfo::default(),
2411                                from_closure: false,
2412                            });
2413
2414                            match mutbl {
2415                                hir::Mutability::Not => {
2416                                    // Immutable reference. We don't need the base
2417                                    // to be valid for the entire lifetime of
2418                                    // the borrow.
2419                                    break;
2420                                }
2421                                hir::Mutability::Mut => {
2422                                    // Mutable reference. We *do* need the base
2423                                    // to be valid, because after the base becomes
2424                                    // invalid, someone else can use our mutable deref.
2425
2426                                    // This is in order to make the following function
2427                                    // illegal:
2428                                    // ```
2429                                    // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2430                                    //     &mut *x
2431                                    // }
2432                                    // ```
2433                                    //
2434                                    // As otherwise you could clone `&mut T` using the
2435                                    // following function:
2436                                    // ```
2437                                    // fn bad(x: &mut T) -> (&mut T, &mut T) {
2438                                    //     let my_clone = unsafe_deref(&'a x);
2439                                    //     ENDREGION 'a;
2440                                    //     (my_clone, x)
2441                                    // }
2442                                    // ```
2443                                }
2444                            }
2445                        }
2446                        ty::RawPtr(..) => {
2447                            // deref of raw pointer, guaranteed to be valid
2448                            break;
2449                        }
2450                        ty::Adt(def, _) if def.is_box() => {
2451                            // deref of `Box`, need the base to be valid - propagate
2452                        }
2453                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected deref ty {0:?} in {1:?}",
        base_ty, borrowed_place))bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2454                    }
2455                }
2456                ProjectionElem::Field(..)
2457                | ProjectionElem::Downcast(..)
2458                | ProjectionElem::OpaqueCast(..)
2459                | ProjectionElem::Index(..)
2460                | ProjectionElem::ConstantIndex { .. }
2461                | ProjectionElem::Subslice { .. }
2462                | ProjectionElem::UnwrapUnsafeBinder(_) => {
2463                    // other field access
2464                }
2465            }
2466        }
2467    }
2468
2469    fn add_generic_reborrow_constraint(
2470        &mut self,
2471        mutability: Mutability,
2472        location: Location,
2473        borrowed_place: &Place<'tcx>,
2474        dest_ty: Ty<'tcx>,
2475    ) {
2476        let Self { borrow_set, location_table, polonius_facts, constraints, infcx, body, .. } =
2477            self;
2478
2479        {
    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/type_check/mod.rs:2479",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2479u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("add_generic_reborrow_constraint({0:?}, {1:?}, {2:?}, {3:?})",
                                                    mutability, location, borrowed_place, dest_ty) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
2480            "add_generic_reborrow_constraint({:?}, {:?}, {:?}, {:?})",
2481            mutability, location, borrowed_place, dest_ty
2482        );
2483
2484        let tcx = infcx.tcx;
2485        let def = body.source.def_id().expect_local();
2486        let upvars = tcx.closure_captures(def);
2487        let field =
2488            path_utils::is_upvar_field_projection(tcx, upvars, borrowed_place.as_ref(), body);
2489        let category = if let Some(field) = field {
2490            ConstraintCategory::ClosureUpvar(field)
2491        } else {
2492            ConstraintCategory::Boring
2493        };
2494
2495        let borrowed_ty = borrowed_place.ty(self.body, tcx).ty;
2496
2497        let ty::Adt(dest_adt, dest_args) = dest_ty.kind() else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2498        let [dest_arg, ..] = ***dest_args else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2499        let ty::GenericArgKind::Lifetime(dest_region) = dest_arg.kind() else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2500        constraints.liveness_constraints.add_location(dest_region.as_var(), location);
2501
2502        // In Polonius mode, we also push a `loan_issued_at` fact
2503        // linking the loan to the region.
2504        if let Some(polonius_facts) = polonius_facts {
2505            let _prof_timer = infcx.tcx.prof.generic_activity("polonius_fact_generation");
2506            if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2507                let region_vid = dest_region.as_var();
2508                polonius_facts.loan_issued_at.push((
2509                    region_vid.into(),
2510                    borrow_index,
2511                    location_table.mid_index(location),
2512                ));
2513            }
2514        }
2515
2516        if mutability.is_not() {
2517            // FIXME(reborrow): for CoerceShared we need to relate the types manually, field by
2518            // field. We cannot just attempt to relate `T` and `<T as CoerceShared>::Target` by
2519            // calling relate_types as they are (generally) two unrelated user-defined ADTs, such as
2520            // `CustomMut<'a>` and `CustomRef<'a>`, or `CustomMut<'a, T>` and `CustomRef<'a, T>`.
2521            // Field-by-field relate_types is expected to work based on the wf-checks that the
2522            // CoerceShared trait performs.
2523            let ty::Adt(borrowed_adt, borrowed_args) = borrowed_ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2524            let borrowed_fields = borrowed_adt.all_fields().collect::<Vec<_>>();
2525            for dest_field in dest_adt.all_fields() {
2526                let Some(borrowed_field) =
2527                    borrowed_fields.iter().find(|f| f.name == dest_field.name)
2528                else {
2529                    continue;
2530                };
2531                let dest_ty = dest_field.ty(tcx, dest_args).skip_norm_wip();
2532                let borrowed_ty = borrowed_field.ty(tcx, borrowed_args).skip_norm_wip();
2533                if let (
2534                    ty::Ref(borrow_region, _, Mutability::Mut),
2535                    ty::Ref(ref_region, _, Mutability::Not),
2536                ) = (borrowed_ty.kind(), dest_ty.kind())
2537                {
2538                    self.relate_types(
2539                        borrowed_ty.peel_refs(),
2540                        ty::Variance::Covariant,
2541                        dest_ty.peel_refs(),
2542                        location.to_locations(),
2543                        category,
2544                    )
2545                    .unwrap();
2546                    self.constraints.outlives_constraints.push(OutlivesConstraint {
2547                        sup: ref_region.as_var(),
2548                        sub: borrow_region.as_var(),
2549                        locations: location.to_locations(),
2550                        span: location.to_locations().span(self.body),
2551                        category,
2552                        variance_info: ty::VarianceDiagInfo::default(),
2553                        from_closure: false,
2554                    });
2555                } else {
2556                    self.relate_types(
2557                        borrowed_ty,
2558                        ty::Variance::Covariant,
2559                        dest_ty,
2560                        location.to_locations(),
2561                        category,
2562                    )
2563                    .unwrap();
2564                }
2565            }
2566        } else {
2567            // Exclusive reborrow
2568            self.relate_types(
2569                borrowed_ty,
2570                ty::Variance::Covariant,
2571                dest_ty,
2572                location.to_locations(),
2573                category,
2574            )
2575            .unwrap();
2576        }
2577    }
2578
2579    fn prove_aggregate_predicates(
2580        &mut self,
2581        aggregate_kind: &AggregateKind<'tcx>,
2582        location: Location,
2583    ) {
2584        let tcx = self.tcx();
2585
2586        {
    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/type_check/mod.rs:2586",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2586u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("prove_aggregate_predicates(aggregate_kind={0:?}, location={1:?})",
                                                    aggregate_kind, location) as &dyn Value))])
            });
    } else { ; }
};debug!(
2587            "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2588            aggregate_kind, location
2589        );
2590
2591        let (def_id, instantiated_predicates) = match *aggregate_kind {
2592            AggregateKind::Adt(adt_did, _, args, _, _) => {
2593                (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, args))
2594            }
2595
2596            // For closures, we have some **extra requirements** we
2597            // have to check. In particular, in their upvars and
2598            // signatures, closures often reference various regions
2599            // from the surrounding function -- we call those the
2600            // closure's free regions. When we borrow-check (and hence
2601            // region-check) closures, we may find that the closure
2602            // requires certain relationships between those free
2603            // regions. However, because those free regions refer to
2604            // portions of the CFG of their caller, the closure is not
2605            // in a position to verify those relationships. In that
2606            // case, the requirements get "propagated" to us, and so
2607            // we have to solve them here where we instantiate the
2608            // closure.
2609            //
2610            // Despite the opacity of the previous paragraph, this is
2611            // actually relatively easy to understand in terms of the
2612            // desugaring. A closure gets desugared to a struct, and
2613            // these extra requirements are basically like where
2614            // clauses on the struct.
2615            AggregateKind::Closure(def_id, args)
2616            | AggregateKind::CoroutineClosure(def_id, args)
2617            | AggregateKind::Coroutine(def_id, args) => {
2618                (def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), args, location))
2619            }
2620
2621            AggregateKind::Array(_) | AggregateKind::Tuple | AggregateKind::RawPtr(..) => {
2622                (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2623            }
2624        };
2625
2626        self.normalize_and_prove_instantiated_predicates(
2627            def_id,
2628            instantiated_predicates,
2629            location.to_locations(),
2630        );
2631    }
2632
2633    fn prove_closure_bounds(
2634        &mut self,
2635        tcx: TyCtxt<'tcx>,
2636        def_id: LocalDefId,
2637        args: GenericArgsRef<'tcx>,
2638        location: Location,
2639    ) -> ty::InstantiatedPredicates<'tcx> {
2640        let root_def_id = self.root_cx.root_def_id();
2641        // We will have to handle propagated closure requirements for this closure,
2642        // but need to defer this until the nested body has been fully borrow checked.
2643        self.deferred_closure_requirements.push((def_id, args, location.to_locations()));
2644
2645        // Equate closure args to regions inherited from `root_def_id`. Fixes #98589.
2646        let typeck_root_args = ty::GenericArgs::identity_for_item(tcx, root_def_id);
2647
2648        let parent_args = match tcx.def_kind(def_id) {
2649            // We don't want to dispatch on 3 different kind of closures here, so take
2650            // advantage of the fact that the `parent_args` is the same length as the
2651            // `typeck_root_args`.
2652            DefKind::Closure => {
2653                // FIXME(async_closures): It may be useful to add a debug assert here
2654                // to actually call `type_of` and check the `parent_args` are the same
2655                // length as the `typeck_root_args`.
2656                &args[..typeck_root_args.len()]
2657            }
2658            DefKind::AnonConst
2659                if tcx.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline =>
2660            {
2661                args.as_inline_const().parent_args()
2662            }
2663            other => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected item {0:?}",
        other))bug!("unexpected item {:?}", other),
2664        };
2665        let parent_args = tcx.mk_args(parent_args);
2666
2667        {
    match (&typeck_root_args.len(), &parent_args.len()) {
        (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!(typeck_root_args.len(), parent_args.len());
2668        if let Err(_) = self.eq_args(
2669            typeck_root_args,
2670            parent_args,
2671            location.to_locations(),
2672            ConstraintCategory::BoringNoLocation,
2673        ) {
2674            {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), def_id,
                        format_args!("could not relate closure to parent {0:?} != {1:?}",
                            typeck_root_args, parent_args)))
            }))
};span_mirbug!(
2675                self,
2676                def_id,
2677                "could not relate closure to parent {:?} != {:?}",
2678                typeck_root_args,
2679                parent_args
2680            );
2681        }
2682
2683        tcx.predicates_of(def_id).instantiate(tcx, args)
2684    }
2685}
2686
2687trait NormalizeLocation: fmt::Debug + Copy {
2688    fn to_locations(self) -> Locations;
2689}
2690
2691impl NormalizeLocation for Locations {
2692    fn to_locations(self) -> Locations {
2693        self
2694    }
2695}
2696
2697impl NormalizeLocation for Location {
2698    fn to_locations(self) -> Locations {
2699        Locations::Single(self)
2700    }
2701}
2702
2703/// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2704/// this is not canonicalized - it directly affects the main `InferCtxt`
2705/// that we use during MIR borrowchecking.
2706#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InstantiateOpaqueType<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "InstantiateOpaqueType", "base_universe", &self.base_universe,
            "region_constraints", &self.region_constraints, "obligations",
            &&self.obligations)
    }
}Debug)]
2707pub(super) struct InstantiateOpaqueType<'tcx> {
2708    pub base_universe: Option<ty::UniverseIndex>,
2709    pub region_constraints: Option<RegionConstraintData<'tcx>>,
2710    pub obligations: PredicateObligations<'tcx>,
2711}
2712
2713impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2714    type Output = ();
2715    /// We use this type itself to store the information used
2716    /// when reporting errors. Since this is not a query, we don't
2717    /// re-run anything during error reporting - we just use the information
2718    /// we saved to help extract an error from the already-existing region
2719    /// constraints in our `InferCtxt`
2720    type ErrorInfo = InstantiateOpaqueType<'tcx>;
2721
2722    fn fully_perform(
2723        mut self,
2724        infcx: &InferCtxt<'tcx>,
2725        root_def_id: LocalDefId,
2726        span: Span,
2727    ) -> Result<TypeOpOutput<'tcx, Self>, ErrorGuaranteed> {
2728        let (mut output, region_constraints) =
2729            scrape_region_constraints(infcx, root_def_id, "InstantiateOpaqueType", span, |ocx| {
2730                ocx.register_obligations(self.obligations.clone());
2731                Ok(())
2732            })?;
2733        self.region_constraints = Some(region_constraints);
2734        output.error_info = Some(self);
2735        Ok(output)
2736    }
2737}