Skip to main content

rustc_type_ir/
relate.rs

1use std::iter;
2
3use derive_where::derive_where;
4use rustc_ast_ir::Mutability;
5use tracing::{instrument, trace};
6
7use crate::error::{ExpectedFound, TypeError};
8use crate::fold::TypeFoldable;
9use crate::inherent::*;
10use crate::{self as ty, Interner};
11
12pub mod combine;
13pub mod solver_relating;
14
15pub type RelateResult<I, T> = Result<T, TypeError<I>>;
16
17/// Whether aliases should be related structurally or not. Used
18/// to adjust the behavior of generalization and combine.
19///
20/// This should always be `No` unless in a few special-cases when
21/// instantiating canonical responses and in the new solver. Each
22/// such case should have a comment explaining why it is used.
23#[derive(#[automatically_derived]
impl ::core::fmt::Debug for StructurallyRelateAliases {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                StructurallyRelateAliases::Yes => "Yes",
                StructurallyRelateAliases::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for StructurallyRelateAliases { }Copy, #[automatically_derived]
impl ::core::clone::Clone for StructurallyRelateAliases {
    #[inline]
    fn clone(&self) -> StructurallyRelateAliases { *self }
}Clone)]
24pub enum StructurallyRelateAliases {
25    Yes,
26    No,
27}
28
29/// Extra information about why we ended up with a particular variance.
30/// This is only used to add more information to error messages, and
31/// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo`
32/// may lead to confusing notes in error messages, it will never cause
33/// a miscompilation or unsoundness.
34///
35/// When in doubt, use `VarianceDiagInfo::default()`
36#[automatically_derived]
impl<I: Interner> ::core::default::Default for VarianceDiagInfo<I> where
    I: Interner {
    fn default() -> Self { VarianceDiagInfo::None }
}#[derive_where(Clone, Copy, PartialEq, Debug, Default; I: Interner)]
37pub enum VarianceDiagInfo<I: Interner> {
38    /// No additional information - this is the default.
39    /// We will not add any additional information to error messages.
40    #[derive_where(default)]
41    None,
42    /// We switched our variance because a generic argument occurs inside
43    /// the invariant generic argument of another type.
44    Invariant {
45        /// The generic type containing the generic parameter
46        /// that changes the variance (e.g. `*mut T`, `MyStruct<T>`)
47        ty: I::Ty,
48        /// The index of the generic parameter being used
49        /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`)
50        param_index: u32,
51    },
52}
53
54impl<I: Interner> Eq for VarianceDiagInfo<I> {}
55
56impl<I: Interner> VarianceDiagInfo<I> {
57    /// Mirrors `Variance::xform` - used to 'combine' the existing
58    /// and new `VarianceDiagInfo`s when our variance changes.
59    pub fn xform(self, other: VarianceDiagInfo<I>) -> VarianceDiagInfo<I> {
60        // For now, just use the first `VarianceDiagInfo::Invariant` that we see
61        match self {
62            VarianceDiagInfo::None => other,
63            VarianceDiagInfo::Invariant { .. } => self,
64        }
65    }
66}
67
68pub trait TypeRelation<I: Interner>: Sized {
69    fn cx(&self) -> I;
70
71    /// Generic relation routine suitable for most anything.
72    fn relate<T: Relate<I>>(&mut self, a: T, b: T) -> RelateResult<I, T> {
73        Relate::relate(self, a, b)
74    }
75
76    fn relate_ty_args(
77        &mut self,
78        a_ty: I::Ty,
79        b_ty: I::Ty,
80        ty_def_id: I::DefId,
81        a_arg: I::GenericArgs,
82        b_arg: I::GenericArgs,
83        mk: impl FnOnce(I::GenericArgs) -> I::Ty,
84    ) -> RelateResult<I, I::Ty>;
85
86    /// Switch variance for the purpose of relating `a` and `b`.
87    fn relate_with_variance<T: Relate<I>>(
88        &mut self,
89        variance: ty::Variance,
90        info: VarianceDiagInfo<I>,
91        a: T,
92        b: T,
93    ) -> RelateResult<I, T>;
94
95    // Overridable relations. You shouldn't typically call these
96    // directly, instead call `relate()`, which in turn calls
97    // these. This is both more uniform but also allows us to add
98    // additional hooks for other types in the future if needed
99    // without making older code, which called `relate`, obsolete.
100
101    fn tys(&mut self, a: I::Ty, b: I::Ty) -> RelateResult<I, I::Ty>;
102
103    fn regions(&mut self, a: I::Region, b: I::Region) -> RelateResult<I, I::Region>;
104
105    fn consts(&mut self, a: I::Const, b: I::Const) -> RelateResult<I, I::Const>;
106
107    fn binders<T>(
108        &mut self,
109        a: ty::Binder<I, T>,
110        b: ty::Binder<I, T>,
111    ) -> RelateResult<I, ty::Binder<I, T>>
112    where
113        T: Relate<I>;
114}
115
116pub trait Relate<I: Interner>: TypeFoldable<I> + PartialEq + Copy {
117    fn relate<R: TypeRelation<I>>(relation: &mut R, a: Self, b: Self) -> RelateResult<I, Self>;
118}
119
120///////////////////////////////////////////////////////////////////////////
121// Relate impls
122
123#[inline]
124pub fn relate_args_invariantly<I: Interner, R: TypeRelation<I>>(
125    relation: &mut R,
126    a_arg: I::GenericArgs,
127    b_arg: I::GenericArgs,
128) -> RelateResult<I, I::GenericArgs> {
129    relation.cx().mk_args_from_iter(iter::zip(a_arg.iter(), b_arg.iter()).map(|(a, b)| {
130        relation.relate_with_variance(ty::Invariant, VarianceDiagInfo::default(), a, b)
131    }))
132}
133
134pub fn relate_args_with_variances<I: Interner, R: TypeRelation<I>>(
135    relation: &mut R,
136    variances: I::VariancesOf,
137    a_args: I::GenericArgs,
138    b_args: I::GenericArgs,
139) -> RelateResult<I, I::GenericArgs> {
140    let cx = relation.cx();
141    let args = iter::zip(a_args.iter(), b_args.iter()).enumerate().map(|(i, (a, b))| {
142        let variance = variances.get(i).unwrap();
143        relation.relate_with_variance(variance, VarianceDiagInfo::None, a, b)
144    });
145    // FIXME: We can probably try to reuse `a_args` here if it did not change.
146    cx.mk_args_from_iter(args)
147}
148
149impl<I: Interner> Relate<I> for ty::FnSig<I> {
150    fn relate<R: TypeRelation<I>>(
151        relation: &mut R,
152        a: ty::FnSig<I>,
153        b: ty::FnSig<I>,
154    ) -> RelateResult<I, ty::FnSig<I>> {
155        let cx = relation.cx();
156
157        if a.c_variadic() != b.c_variadic() {
158            return Err(TypeError::VariadicMismatch(ExpectedFound::new(
159                a.c_variadic(),
160                b.c_variadic(),
161            )));
162        }
163
164        if a.safety() != b.safety() {
165            return Err(TypeError::SafetyMismatch(ExpectedFound::new(a.safety(), b.safety())));
166        }
167
168        if a.abi() != b.abi() {
169            return Err(TypeError::AbiMismatch(ExpectedFound::new(a.abi(), b.abi())));
170        };
171
172        let a_inputs = a.inputs();
173        let b_inputs = b.inputs();
174        if a_inputs.len() != b_inputs.len() {
175            return Err(TypeError::ArgCount);
176        }
177
178        let inputs_and_output = iter::zip(a_inputs.iter(), b_inputs.iter())
179            .map(|(a, b)| ((a, b), false))
180            .chain(iter::once(((a.output(), b.output()), true)))
181            .map(|((a, b), is_output)| {
182                if is_output {
183                    relation.relate(a, b)
184                } else {
185                    relation.relate_with_variance(
186                        ty::Contravariant,
187                        VarianceDiagInfo::default(),
188                        a,
189                        b,
190                    )
191                }
192            })
193            .enumerate()
194            .map(|(i, r)| match r {
195                Err(TypeError::Sorts(exp_found) | TypeError::ArgumentSorts(exp_found, _)) => {
196                    Err(TypeError::ArgumentSorts(exp_found, i))
197                }
198                Err(TypeError::Mutability | TypeError::ArgumentMutability(_)) => {
199                    Err(TypeError::ArgumentMutability(i))
200                }
201                r => r,
202            });
203        Ok(ty::FnSig {
204            inputs_and_output: cx.mk_type_list_from_iter(inputs_and_output)?,
205            fn_sig_kind: a.fn_sig_kind,
206        })
207    }
208}
209
210impl<I: Interner> Relate<I> for ty::AliasTy<I> {
211    fn relate<R: TypeRelation<I>>(
212        relation: &mut R,
213        a: ty::AliasTy<I>,
214        b: ty::AliasTy<I>,
215    ) -> RelateResult<I, ty::AliasTy<I>> {
216        if a.kind.def_id() != b.kind.def_id() {
217            Err(TypeError::ProjectionMismatched(ExpectedFound::new(
218                a.kind.def_id(),
219                b.kind.def_id(),
220            )))
221        } else {
222            let cx = relation.cx();
223            let args = if let Some(variances) = cx.opt_alias_variances(a.kind) {
224                relate_args_with_variances(relation, variances, a.args, b.args)?
225            } else {
226                relate_args_invariantly(relation, a.args, b.args)?
227            };
228            Ok(ty::AliasTy::new_from_args(relation.cx(), a.kind, args))
229        }
230    }
231}
232
233impl<I: Interner> Relate<I> for ty::AliasTerm<I> {
234    fn relate<R: TypeRelation<I>>(
235        relation: &mut R,
236        a: ty::AliasTerm<I>,
237        b: ty::AliasTerm<I>,
238    ) -> RelateResult<I, ty::AliasTerm<I>> {
239        if a.def_id() != b.def_id() {
240            Err(TypeError::ProjectionMismatched(ExpectedFound::new(a.def_id(), b.def_id())))
241        } else {
242            let args = match a.kind(relation.cx()) {
243                ty::AliasTermKind::OpaqueTy { .. } => relate_args_with_variances(
244                    relation,
245                    relation.cx().variances_of(a.def_id()),
246                    a.args,
247                    b.args,
248                )?,
249                ty::AliasTermKind::ProjectionTy { .. }
250                | ty::AliasTermKind::FreeConst { .. }
251                | ty::AliasTermKind::FreeTy { .. }
252                | ty::AliasTermKind::InherentTy { .. }
253                | ty::AliasTermKind::InherentConst { .. }
254                | ty::AliasTermKind::UnevaluatedConst { .. }
255                | ty::AliasTermKind::ProjectionConst { .. } => {
256                    relate_args_invariantly(relation, a.args, b.args)?
257                }
258            };
259            Ok(a.with_args(relation.cx(), args))
260        }
261    }
262}
263
264impl<I: Interner> Relate<I> for ty::ExistentialProjection<I> {
265    fn relate<R: TypeRelation<I>>(
266        relation: &mut R,
267        a: ty::ExistentialProjection<I>,
268        b: ty::ExistentialProjection<I>,
269    ) -> RelateResult<I, ty::ExistentialProjection<I>> {
270        if a.def_id != b.def_id {
271            Err(TypeError::ProjectionMismatched(ExpectedFound::new(
272                a.def_id.into(),
273                b.def_id.into(),
274            )))
275        } else {
276            let term = relation.relate_with_variance(
277                ty::Invariant,
278                VarianceDiagInfo::default(),
279                a.term,
280                b.term,
281            )?;
282            let args = relation.relate_with_variance(
283                ty::Invariant,
284                VarianceDiagInfo::default(),
285                a.args,
286                b.args,
287            )?;
288            Ok(ty::ExistentialProjection::new_from_args(relation.cx(), a.def_id, args, term))
289        }
290    }
291}
292
293impl<I: Interner> Relate<I> for ty::TraitRef<I> {
294    fn relate<R: TypeRelation<I>>(
295        relation: &mut R,
296        a: ty::TraitRef<I>,
297        b: ty::TraitRef<I>,
298    ) -> RelateResult<I, ty::TraitRef<I>> {
299        // Different traits cannot be related.
300        if a.def_id != b.def_id {
301            Err(TypeError::Traits({
302                let a = a.def_id;
303                let b = b.def_id;
304                ExpectedFound::new(a, b)
305            }))
306        } else {
307            let args = relate_args_invariantly(relation, a.args, b.args)?;
308            Ok(ty::TraitRef::new_from_args(relation.cx(), a.def_id, args))
309        }
310    }
311}
312
313impl<I: Interner> Relate<I> for ty::ExistentialTraitRef<I> {
314    fn relate<R: TypeRelation<I>>(
315        relation: &mut R,
316        a: ty::ExistentialTraitRef<I>,
317        b: ty::ExistentialTraitRef<I>,
318    ) -> RelateResult<I, ty::ExistentialTraitRef<I>> {
319        // Different traits cannot be related.
320        if a.def_id != b.def_id {
321            Err(TypeError::Traits({
322                let a = a.def_id;
323                let b = b.def_id;
324                ExpectedFound::new(a, b)
325            }))
326        } else {
327            let args = relate_args_invariantly(relation, a.args, b.args)?;
328            Ok(ty::ExistentialTraitRef::new_from_args(relation.cx(), a.def_id, args))
329        }
330    }
331}
332
333/// Relates `a` and `b` structurally, calling the relation for all nested values.
334/// Any semantic equality, e.g. of projections, and inference variables have to be
335/// handled by the caller.
336x;#[instrument(level = "trace", skip(relation), ret)]
337pub fn structurally_relate_tys<I: Interner, R: TypeRelation<I>>(
338    relation: &mut R,
339    a: I::Ty,
340    b: I::Ty,
341) -> RelateResult<I, I::Ty> {
342    let cx = relation.cx();
343    match (a.kind(), b.kind()) {
344        (ty::Infer(_), _) | (_, ty::Infer(_)) => {
345            // The caller should handle these cases!
346            panic!("var types encountered in structurally_relate_tys")
347        }
348
349        (ty::Bound(..), _) | (_, ty::Bound(..)) => {
350            panic!("bound types encountered in structurally_relate_tys")
351        }
352
353        (ty::Error(guar), _) | (_, ty::Error(guar)) => Ok(Ty::new_error(cx, guar)),
354
355        (ty::Never, _)
356        | (ty::Char, _)
357        | (ty::Bool, _)
358        | (ty::Int(_), _)
359        | (ty::Uint(_), _)
360        | (ty::Float(_), _)
361        | (ty::Str, _)
362            if a == b =>
363        {
364            Ok(a)
365        }
366
367        (ty::Param(a_p), ty::Param(b_p)) if a_p.index() == b_p.index() => {
368            // FIXME: Put this back
369            //debug_assert_eq!(a_p.name(), b_p.name(), "param types with same index differ in name");
370            Ok(a)
371        }
372
373        (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
374
375        (ty::Adt(a_def, a_args), ty::Adt(b_def, b_args)) if a_def == b_def => {
376            if a_args.is_empty() {
377                Ok(a)
378            } else {
379                relation.relate_ty_args(a, b, a_def.def_id().into(), a_args, b_args, |args| {
380                    Ty::new_adt(cx, a_def, args)
381                })
382            }
383        }
384
385        (ty::Foreign(a_id), ty::Foreign(b_id)) if a_id == b_id => Ok(Ty::new_foreign(cx, a_id)),
386
387        (ty::Dynamic(a_obj, a_region), ty::Dynamic(b_obj, b_region)) => Ok(Ty::new_dynamic(
388            cx,
389            relation.relate(a_obj, b_obj)?,
390            relation.relate(a_region, b_region)?,
391        )),
392
393        (ty::Coroutine(a_id, a_args), ty::Coroutine(b_id, b_args)) if a_id == b_id => {
394            // All Coroutine types with the same id represent
395            // the (anonymous) type of the same coroutine expression. So
396            // all of their regions should be equated.
397            let args = relate_args_invariantly(relation, a_args, b_args)?;
398            Ok(Ty::new_coroutine(cx, a_id, args))
399        }
400
401        (ty::CoroutineWitness(a_id, a_args), ty::CoroutineWitness(b_id, b_args))
402            if a_id == b_id =>
403        {
404            // All CoroutineWitness types with the same id represent
405            // the (anonymous) type of the same coroutine expression. So
406            // all of their regions should be equated.
407            let args = relate_args_invariantly(relation, a_args, b_args)?;
408            Ok(Ty::new_coroutine_witness(cx, a_id, args))
409        }
410
411        (ty::Closure(a_id, a_args), ty::Closure(b_id, b_args)) if a_id == b_id => {
412            // All Closure types with the same id represent
413            // the (anonymous) type of the same closure expression. So
414            // all of their regions should be equated.
415            let args = relate_args_invariantly(relation, a_args, b_args)?;
416            Ok(Ty::new_closure(cx, a_id, args))
417        }
418
419        (ty::CoroutineClosure(a_id, a_args), ty::CoroutineClosure(b_id, b_args))
420            if a_id == b_id =>
421        {
422            let args = relate_args_invariantly(relation, a_args, b_args)?;
423            Ok(Ty::new_coroutine_closure(cx, a_id, args))
424        }
425
426        (ty::RawPtr(a_ty, a_mutbl), ty::RawPtr(b_ty, b_mutbl)) => {
427            if a_mutbl != b_mutbl {
428                return Err(TypeError::Mutability);
429            }
430
431            let (variance, info) = match a_mutbl {
432                Mutability::Not => (ty::Covariant, VarianceDiagInfo::None),
433                Mutability::Mut => {
434                    (ty::Invariant, VarianceDiagInfo::Invariant { ty: a, param_index: 0 })
435                }
436            };
437
438            let ty = relation.relate_with_variance(variance, info, a_ty, b_ty)?;
439
440            Ok(Ty::new_ptr(cx, ty, a_mutbl))
441        }
442
443        (ty::Ref(a_r, a_ty, a_mutbl), ty::Ref(b_r, b_ty, b_mutbl)) => {
444            if a_mutbl != b_mutbl {
445                return Err(TypeError::Mutability);
446            }
447
448            let (variance, info) = match a_mutbl {
449                Mutability::Not => (ty::Covariant, VarianceDiagInfo::None),
450                Mutability::Mut => {
451                    (ty::Invariant, VarianceDiagInfo::Invariant { ty: a, param_index: 0 })
452                }
453            };
454
455            let r = relation.relate(a_r, b_r)?;
456            let ty = relation.relate_with_variance(variance, info, a_ty, b_ty)?;
457
458            Ok(Ty::new_ref(cx, r, ty, a_mutbl))
459        }
460
461        (ty::Array(a_t, sz_a), ty::Array(b_t, sz_b)) => {
462            let t = relation.relate(a_t, b_t)?;
463            match relation.relate(sz_a, sz_b) {
464                Ok(sz) => Ok(Ty::new_array_with_const_len(cx, t, sz)),
465                Err(TypeError::ConstMismatch(_)) => {
466                    Err(TypeError::ArraySize(ExpectedFound::new(sz_a, sz_b)))
467                }
468                Err(e) => Err(e),
469            }
470        }
471
472        (ty::Slice(a_t), ty::Slice(b_t)) => {
473            let t = relation.relate(a_t, b_t)?;
474            Ok(Ty::new_slice(cx, t))
475        }
476
477        (ty::Tuple(as_), ty::Tuple(bs)) => {
478            if as_.len() == bs.len() {
479                Ok(Ty::new_tup_from_iter(
480                    cx,
481                    iter::zip(as_.iter(), bs.iter()).map(|(a, b)| relation.relate(a, b)),
482                )?)
483            } else if !(as_.is_empty() || bs.is_empty()) {
484                Err(TypeError::TupleSize(ExpectedFound::new(as_.len(), bs.len())))
485            } else {
486                Err(TypeError::Sorts(ExpectedFound::new(a, b)))
487            }
488        }
489
490        (ty::FnDef(a_def_id, a_args), ty::FnDef(b_def_id, b_args)) if a_def_id == b_def_id => {
491            if a_args.is_empty() {
492                Ok(a)
493            } else {
494                relation.relate_ty_args(a, b, a_def_id.into(), a_args, b_args, |args| {
495                    Ty::new_fn_def(cx, a_def_id, args)
496                })
497            }
498        }
499
500        (ty::FnPtr(a_sig_tys, a_hdr), ty::FnPtr(b_sig_tys, b_hdr)) => {
501            let fty = relation.relate(a_sig_tys.with(a_hdr), b_sig_tys.with(b_hdr))?;
502            Ok(Ty::new_fn_ptr(cx, fty))
503        }
504
505        // Alias tend to mostly already be handled downstream due to normalization.
506        (ty::Alias(a), ty::Alias(b)) => {
507            let alias_ty = relation.relate(a, b)?;
508            Ok(Ty::new_alias(cx, alias_ty))
509        }
510
511        (ty::Pat(a_ty, a_pat), ty::Pat(b_ty, b_pat)) => {
512            let ty = relation.relate(a_ty, b_ty)?;
513            let pat = relation.relate(a_pat, b_pat)?;
514            Ok(Ty::new_pat(cx, ty, pat))
515        }
516
517        (ty::UnsafeBinder(a_binder), ty::UnsafeBinder(b_binder)) => {
518            Ok(Ty::new_unsafe_binder(cx, relation.binders(*a_binder, *b_binder)?))
519        }
520
521        _ => Err(TypeError::Sorts(ExpectedFound::new(a, b))),
522    }
523}
524
525/// Relates `a` and `b` structurally, calling the relation for all nested values.
526/// Any semantic equality, e.g. of unevaluated consts, and inference variables have
527/// to be handled by the caller.
528///
529/// FIXME: This is not totally structural, which probably should be fixed.
530/// See the HACKs below.
531pub fn structurally_relate_consts<I: Interner, R: TypeRelation<I>>(
532    relation: &mut R,
533    mut a: I::Const,
534    mut b: I::Const,
535) -> RelateResult<I, I::Const> {
536    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/relate.rs:536",
                        "rustc_type_ir::relate", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/relate.rs"),
                        ::tracing_core::__macro_support::Option::Some(536u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::relate"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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(&format_args!("structurally_relate_consts::<{0}>(a = {1:?}, b = {2:?})",
                                                    std::any::type_name::<R>(), a, b) as &dyn Value))])
            });
    } else { ; }
};trace!(
537        "structurally_relate_consts::<{}>(a = {:?}, b = {:?})",
538        std::any::type_name::<R>(),
539        a,
540        b
541    );
542    let cx = relation.cx();
543
544    if cx.features().generic_const_exprs() {
545        a = cx.expand_abstract_consts(a);
546        b = cx.expand_abstract_consts(b);
547    }
548
549    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/relate.rs:549",
                        "rustc_type_ir::relate", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/relate.rs"),
                        ::tracing_core::__macro_support::Option::Some(549u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::relate"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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(&format_args!("structurally_relate_consts::<{0}>(normed_a = {1:?}, normed_b = {2:?})",
                                                    std::any::type_name::<R>(), a, b) as &dyn Value))])
            });
    } else { ; }
};trace!(
550        "structurally_relate_consts::<{}>(normed_a = {:?}, normed_b = {:?})",
551        std::any::type_name::<R>(),
552        a,
553        b
554    );
555
556    // Currently, the values that can be unified are primitive types,
557    // and those that derive both `PartialEq` and `Eq`, corresponding
558    // to structural-match types.
559    let is_match = match (a.kind(), b.kind()) {
560        (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
561            // The caller should handle these cases!
562            {
    ::core::panicking::panic_fmt(format_args!("var types encountered in structurally_relate_consts: {0:?} {1:?}",
            a, b));
}panic!("var types encountered in structurally_relate_consts: {:?} {:?}", a, b)
563        }
564
565        (ty::ConstKind::Error(_), _) => return Ok(a),
566        (_, ty::ConstKind::Error(_)) => return Ok(b),
567
568        (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) if a_p.index() == b_p.index() => {
569            // FIXME: Put this back
570            // debug_assert_eq!(a_p.name, b_p.name, "param types with same index differ in name");
571            true
572        }
573        (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
574        (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
575            match (a_val.valtree().kind(), b_val.valtree().kind()) {
576                (ty::ValTreeKind::Leaf(scalar_a), ty::ValTreeKind::Leaf(scalar_b)) => {
577                    scalar_a == scalar_b
578                }
579                (ty::ValTreeKind::Branch(branches_a), ty::ValTreeKind::Branch(branches_b))
580                    if branches_a.len() == branches_b.len() =>
581                {
582                    branches_a
583                        .iter()
584                        .zip(branches_b.iter())
585                        .all(|(a, b)| relation.relate(a, b).is_ok())
586                }
587                _ => false,
588            }
589        }
590
591        // While this is slightly incorrect, it shouldn't matter for `min_const_generics`
592        // and is the better alternative to waiting until `generic_const_exprs` can
593        // be stabilized.
594        (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu)) if au.def == bu.def => {
595            // FIXME(mgca): remove this
596            if truecfg!(debug_assertions) {
597                let a_ty = cx.type_of(au.def.into()).instantiate(cx, au.args).skip_norm_wip();
598                let b_ty = cx.type_of(bu.def.into()).instantiate(cx, bu.args).skip_norm_wip();
599                match (&a_ty, &b_ty) {
    (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!(a_ty, b_ty);
600            }
601
602            let args = relation.relate_with_variance(
603                ty::Invariant,
604                VarianceDiagInfo::default(),
605                au.args,
606                bu.args,
607            )?;
608            return Ok(Const::new_unevaluated(cx, ty::UnevaluatedConst { def: au.def, args }));
609        }
610        (ty::ConstKind::Expr(ae), ty::ConstKind::Expr(be)) => {
611            let expr = relation.relate(ae, be)?;
612            return Ok(Const::new_expr(cx, expr));
613        }
614        _ => false,
615    };
616    if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(ExpectedFound::new(a, b))) }
617}
618
619impl<I: Interner, T: Relate<I>> Relate<I> for ty::Binder<I, T> {
620    fn relate<R: TypeRelation<I>>(
621        relation: &mut R,
622        a: ty::Binder<I, T>,
623        b: ty::Binder<I, T>,
624    ) -> RelateResult<I, ty::Binder<I, T>> {
625        relation.binders(a, b)
626    }
627}
628
629impl<I: Interner> Relate<I> for ty::TraitPredicate<I> {
630    fn relate<R: TypeRelation<I>>(
631        relation: &mut R,
632        a: ty::TraitPredicate<I>,
633        b: ty::TraitPredicate<I>,
634    ) -> RelateResult<I, ty::TraitPredicate<I>> {
635        let trait_ref = relation.relate(a.trait_ref, b.trait_ref)?;
636        if a.polarity != b.polarity {
637            return Err(TypeError::PolarityMismatch(ExpectedFound::new(a.polarity, b.polarity)));
638        }
639        Ok(ty::TraitPredicate { trait_ref, polarity: a.polarity })
640    }
641}