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#[derive(Debug, Copy, Clone)]
24pub enum StructurallyRelateAliases {
25 Yes,
26 No,
27}
28
29#[derive_where(Clone, Copy, PartialEq, Debug, Default; I: Interner)]
37pub enum VarianceDiagInfo<I: Interner> {
38 #[derive_where(default)]
41 None,
42 Invariant {
45 ty: I::Ty,
48 param_index: u32,
51 },
52}
53
54impl<I: Interner> Eq for VarianceDiagInfo<I> {}
55
56impl<I: Interner> VarianceDiagInfo<I> {
57 pub fn xform(self, other: VarianceDiagInfo<I>) -> VarianceDiagInfo<I> {
60 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 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 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 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#[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 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 c_variadic: a.c_variadic,
206 safety: a.safety,
207 abi: a.abi,
208 })
209 }
210}
211
212impl<I: Interner> Relate<I> for ty::AliasTy<I> {
213 fn relate<R: TypeRelation<I>>(
214 relation: &mut R,
215 a: ty::AliasTy<I>,
216 b: ty::AliasTy<I>,
217 ) -> RelateResult<I, ty::AliasTy<I>> {
218 if a.def_id != b.def_id {
219 Err(TypeError::ProjectionMismatched(ExpectedFound::new(a.def_id, b.def_id)))
220 } else {
221 let cx = relation.cx();
222 let args = if let Some(variances) = cx.opt_alias_variances(a.kind(cx), a.def_id) {
223 relate_args_with_variances(relation, variances, a.args, b.args)?
224 } else {
225 relate_args_invariantly(relation, a.args, b.args)?
226 };
227 Ok(ty::AliasTy::new_from_args(relation.cx(), a.def_id, args))
228 }
229 }
230}
231
232impl<I: Interner> Relate<I> for ty::AliasTerm<I> {
233 fn relate<R: TypeRelation<I>>(
234 relation: &mut R,
235 a: ty::AliasTerm<I>,
236 b: ty::AliasTerm<I>,
237 ) -> RelateResult<I, ty::AliasTerm<I>> {
238 if a.def_id != b.def_id {
239 Err(TypeError::ProjectionMismatched(ExpectedFound::new(a.def_id, b.def_id)))
240 } else {
241 let args = match a.kind(relation.cx()) {
242 ty::AliasTermKind::OpaqueTy => relate_args_with_variances(
243 relation,
244 relation.cx().variances_of(a.def_id),
245 a.args,
246 b.args,
247 )?,
248 ty::AliasTermKind::ProjectionTy
249 | ty::AliasTermKind::FreeConst
250 | ty::AliasTermKind::FreeTy
251 | ty::AliasTermKind::InherentTy
252 | ty::AliasTermKind::InherentConst
253 | ty::AliasTermKind::UnevaluatedConst
254 | ty::AliasTermKind::ProjectionConst => {
255 relate_args_invariantly(relation, a.args, b.args)?
256 }
257 };
258 Ok(ty::AliasTerm::new_from_args(relation.cx(), a.def_id, args))
259 }
260 }
261}
262
263impl<I: Interner> Relate<I> for ty::ExistentialProjection<I> {
264 fn relate<R: TypeRelation<I>>(
265 relation: &mut R,
266 a: ty::ExistentialProjection<I>,
267 b: ty::ExistentialProjection<I>,
268 ) -> RelateResult<I, ty::ExistentialProjection<I>> {
269 if a.def_id != b.def_id {
270 Err(TypeError::ProjectionMismatched(ExpectedFound::new(a.def_id, b.def_id)))
271 } else {
272 let term = relation.relate_with_variance(
273 ty::Invariant,
274 VarianceDiagInfo::default(),
275 a.term,
276 b.term,
277 )?;
278 let args = relation.relate_with_variance(
279 ty::Invariant,
280 VarianceDiagInfo::default(),
281 a.args,
282 b.args,
283 )?;
284 Ok(ty::ExistentialProjection::new_from_args(relation.cx(), a.def_id, args, term))
285 }
286 }
287}
288
289impl<I: Interner> Relate<I> for ty::TraitRef<I> {
290 fn relate<R: TypeRelation<I>>(
291 relation: &mut R,
292 a: ty::TraitRef<I>,
293 b: ty::TraitRef<I>,
294 ) -> RelateResult<I, ty::TraitRef<I>> {
295 if a.def_id != b.def_id {
297 Err(TypeError::Traits({
298 let a = a.def_id;
299 let b = b.def_id;
300 ExpectedFound::new(a, b)
301 }))
302 } else {
303 let args = relate_args_invariantly(relation, a.args, b.args)?;
304 Ok(ty::TraitRef::new_from_args(relation.cx(), a.def_id, args))
305 }
306 }
307}
308
309impl<I: Interner> Relate<I> for ty::ExistentialTraitRef<I> {
310 fn relate<R: TypeRelation<I>>(
311 relation: &mut R,
312 a: ty::ExistentialTraitRef<I>,
313 b: ty::ExistentialTraitRef<I>,
314 ) -> RelateResult<I, ty::ExistentialTraitRef<I>> {
315 if a.def_id != b.def_id {
317 Err(TypeError::Traits({
318 let a = a.def_id;
319 let b = b.def_id;
320 ExpectedFound::new(a, b)
321 }))
322 } else {
323 let args = relate_args_invariantly(relation, a.args, b.args)?;
324 Ok(ty::ExistentialTraitRef::new_from_args(relation.cx(), a.def_id, args))
325 }
326 }
327}
328
329#[instrument(level = "trace", skip(relation), ret)]
333pub fn structurally_relate_tys<I: Interner, R: TypeRelation<I>>(
334 relation: &mut R,
335 a: I::Ty,
336 b: I::Ty,
337) -> RelateResult<I, I::Ty> {
338 let cx = relation.cx();
339 match (a.kind(), b.kind()) {
340 (ty::Infer(_), _) | (_, ty::Infer(_)) => {
341 panic!("var types encountered in structurally_relate_tys")
343 }
344
345 (ty::Bound(..), _) | (_, ty::Bound(..)) => {
346 panic!("bound types encountered in structurally_relate_tys")
347 }
348
349 (ty::Error(guar), _) | (_, ty::Error(guar)) => Ok(Ty::new_error(cx, guar)),
350
351 (ty::Never, _)
352 | (ty::Char, _)
353 | (ty::Bool, _)
354 | (ty::Int(_), _)
355 | (ty::Uint(_), _)
356 | (ty::Float(_), _)
357 | (ty::Str, _)
358 if a == b =>
359 {
360 Ok(a)
361 }
362
363 (ty::Param(a_p), ty::Param(b_p)) if a_p.index() == b_p.index() => {
364 Ok(a)
367 }
368
369 (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a),
370
371 (ty::Adt(a_def, a_args), ty::Adt(b_def, b_args)) if a_def == b_def => {
372 if a_args.is_empty() {
373 Ok(a)
374 } else {
375 relation.relate_ty_args(a, b, a_def.def_id().into(), a_args, b_args, |args| {
376 Ty::new_adt(cx, a_def, args)
377 })
378 }
379 }
380
381 (ty::Foreign(a_id), ty::Foreign(b_id)) if a_id == b_id => Ok(Ty::new_foreign(cx, a_id)),
382
383 (ty::Dynamic(a_obj, a_region), ty::Dynamic(b_obj, b_region)) => Ok(Ty::new_dynamic(
384 cx,
385 relation.relate(a_obj, b_obj)?,
386 relation.relate(a_region, b_region)?,
387 )),
388
389 (ty::Coroutine(a_id, a_args), ty::Coroutine(b_id, b_args)) if a_id == b_id => {
390 let args = relate_args_invariantly(relation, a_args, b_args)?;
394 Ok(Ty::new_coroutine(cx, a_id, args))
395 }
396
397 (ty::CoroutineWitness(a_id, a_args), ty::CoroutineWitness(b_id, b_args))
398 if a_id == b_id =>
399 {
400 let args = relate_args_invariantly(relation, a_args, b_args)?;
404 Ok(Ty::new_coroutine_witness(cx, a_id, args))
405 }
406
407 (ty::Closure(a_id, a_args), ty::Closure(b_id, b_args)) if a_id == b_id => {
408 let args = relate_args_invariantly(relation, a_args, b_args)?;
412 Ok(Ty::new_closure(cx, a_id, args))
413 }
414
415 (ty::CoroutineClosure(a_id, a_args), ty::CoroutineClosure(b_id, b_args))
416 if a_id == b_id =>
417 {
418 let args = relate_args_invariantly(relation, a_args, b_args)?;
419 Ok(Ty::new_coroutine_closure(cx, a_id, args))
420 }
421
422 (ty::RawPtr(a_ty, a_mutbl), ty::RawPtr(b_ty, b_mutbl)) => {
423 if a_mutbl != b_mutbl {
424 return Err(TypeError::Mutability);
425 }
426
427 let (variance, info) = match a_mutbl {
428 Mutability::Not => (ty::Covariant, VarianceDiagInfo::None),
429 Mutability::Mut => {
430 (ty::Invariant, VarianceDiagInfo::Invariant { ty: a, param_index: 0 })
431 }
432 };
433
434 let ty = relation.relate_with_variance(variance, info, a_ty, b_ty)?;
435
436 Ok(Ty::new_ptr(cx, ty, a_mutbl))
437 }
438
439 (ty::Ref(a_r, a_ty, a_mutbl), ty::Ref(b_r, b_ty, b_mutbl)) => {
440 if a_mutbl != b_mutbl {
441 return Err(TypeError::Mutability);
442 }
443
444 let (variance, info) = match a_mutbl {
445 Mutability::Not => (ty::Covariant, VarianceDiagInfo::None),
446 Mutability::Mut => {
447 (ty::Invariant, VarianceDiagInfo::Invariant { ty: a, param_index: 0 })
448 }
449 };
450
451 let r = relation.relate(a_r, b_r)?;
452 let ty = relation.relate_with_variance(variance, info, a_ty, b_ty)?;
453
454 Ok(Ty::new_ref(cx, r, ty, a_mutbl))
455 }
456
457 (ty::Array(a_t, sz_a), ty::Array(b_t, sz_b)) => {
458 let t = relation.relate(a_t, b_t)?;
459 match relation.relate(sz_a, sz_b) {
460 Ok(sz) => Ok(Ty::new_array_with_const_len(cx, t, sz)),
461 Err(TypeError::ConstMismatch(_)) => {
462 Err(TypeError::ArraySize(ExpectedFound::new(sz_a, sz_b)))
463 }
464 Err(e) => Err(e),
465 }
466 }
467
468 (ty::Slice(a_t), ty::Slice(b_t)) => {
469 let t = relation.relate(a_t, b_t)?;
470 Ok(Ty::new_slice(cx, t))
471 }
472
473 (ty::Tuple(as_), ty::Tuple(bs)) => {
474 if as_.len() == bs.len() {
475 Ok(Ty::new_tup_from_iter(
476 cx,
477 iter::zip(as_.iter(), bs.iter()).map(|(a, b)| relation.relate(a, b)),
478 )?)
479 } else if !(as_.is_empty() || bs.is_empty()) {
480 Err(TypeError::TupleSize(ExpectedFound::new(as_.len(), bs.len())))
481 } else {
482 Err(TypeError::Sorts(ExpectedFound::new(a, b)))
483 }
484 }
485
486 (ty::FnDef(a_def_id, a_args), ty::FnDef(b_def_id, b_args)) if a_def_id == b_def_id => {
487 if a_args.is_empty() {
488 Ok(a)
489 } else {
490 relation.relate_ty_args(a, b, a_def_id.into(), a_args, b_args, |args| {
491 Ty::new_fn_def(cx, a_def_id, args)
492 })
493 }
494 }
495
496 (ty::FnPtr(a_sig_tys, a_hdr), ty::FnPtr(b_sig_tys, b_hdr)) => {
497 let fty = relation.relate(a_sig_tys.with(a_hdr), b_sig_tys.with(b_hdr))?;
498 Ok(Ty::new_fn_ptr(cx, fty))
499 }
500
501 (ty::Alias(a_kind, a_data), ty::Alias(b_kind, b_data)) => {
503 let alias_ty = relation.relate(a_data, b_data)?;
504 assert_eq!(a_kind, b_kind);
505 Ok(Ty::new_alias(cx, a_kind, alias_ty))
506 }
507
508 (ty::Pat(a_ty, a_pat), ty::Pat(b_ty, b_pat)) => {
509 let ty = relation.relate(a_ty, b_ty)?;
510 let pat = relation.relate(a_pat, b_pat)?;
511 Ok(Ty::new_pat(cx, ty, pat))
512 }
513
514 (ty::UnsafeBinder(a_binder), ty::UnsafeBinder(b_binder)) => {
515 Ok(Ty::new_unsafe_binder(cx, relation.binders(*a_binder, *b_binder)?))
516 }
517
518 _ => Err(TypeError::Sorts(ExpectedFound::new(a, b))),
519 }
520}
521
522pub fn structurally_relate_consts<I: Interner, R: TypeRelation<I>>(
529 relation: &mut R,
530 mut a: I::Const,
531 mut b: I::Const,
532) -> RelateResult<I, I::Const> {
533 trace!(
534 "structurally_relate_consts::<{}>(a = {:?}, b = {:?})",
535 std::any::type_name::<R>(),
536 a,
537 b
538 );
539 let cx = relation.cx();
540
541 if cx.features().generic_const_exprs() {
542 a = cx.expand_abstract_consts(a);
543 b = cx.expand_abstract_consts(b);
544 }
545
546 trace!(
547 "structurally_relate_consts::<{}>(normed_a = {:?}, normed_b = {:?})",
548 std::any::type_name::<R>(),
549 a,
550 b
551 );
552
553 let is_match = match (a.kind(), b.kind()) {
557 (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => {
558 panic!("var types encountered in structurally_relate_consts: {:?} {:?}", a, b)
560 }
561
562 (ty::ConstKind::Error(_), _) => return Ok(a),
563 (_, ty::ConstKind::Error(_)) => return Ok(b),
564
565 (ty::ConstKind::Param(a_p), ty::ConstKind::Param(b_p)) if a_p.index() == b_p.index() => {
566 true
569 }
570 (ty::ConstKind::Placeholder(p1), ty::ConstKind::Placeholder(p2)) => p1 == p2,
571 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
572 match (a_val.valtree().kind(), b_val.valtree().kind()) {
573 (ty::ValTreeKind::Leaf(scalar_a), ty::ValTreeKind::Leaf(scalar_b)) => {
574 scalar_a == scalar_b
575 }
576 (ty::ValTreeKind::Branch(branches_a), ty::ValTreeKind::Branch(branches_b))
577 if branches_a.len() == branches_b.len() =>
578 {
579 branches_a
580 .into_iter()
581 .zip(branches_b)
582 .all(|(a, b)| relation.relate(*a, *b).is_ok())
583 }
584 _ => false,
585 }
586 }
587
588 (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu)) if au.def == bu.def => {
592 if cfg!(debug_assertions) {
594 let a_ty = cx.type_of(au.def.into()).instantiate(cx, au.args);
595 let b_ty = cx.type_of(bu.def.into()).instantiate(cx, bu.args);
596 assert_eq!(a_ty, b_ty);
597 }
598
599 let args = relation.relate_with_variance(
600 ty::Invariant,
601 VarianceDiagInfo::default(),
602 au.args,
603 bu.args,
604 )?;
605 return Ok(Const::new_unevaluated(cx, ty::UnevaluatedConst { def: au.def, args }));
606 }
607 (ty::ConstKind::Expr(ae), ty::ConstKind::Expr(be)) => {
608 let expr = relation.relate(ae, be)?;
609 return Ok(Const::new_expr(cx, expr));
610 }
611 _ => false,
612 };
613 if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(ExpectedFound::new(a, b))) }
614}
615
616impl<I: Interner, T: Relate<I>> Relate<I> for ty::Binder<I, T> {
617 fn relate<R: TypeRelation<I>>(
618 relation: &mut R,
619 a: ty::Binder<I, T>,
620 b: ty::Binder<I, T>,
621 ) -> RelateResult<I, ty::Binder<I, T>> {
622 relation.binders(a, b)
623 }
624}
625
626impl<I: Interner> Relate<I> for ty::TraitPredicate<I> {
627 fn relate<R: TypeRelation<I>>(
628 relation: &mut R,
629 a: ty::TraitPredicate<I>,
630 b: ty::TraitPredicate<I>,
631 ) -> RelateResult<I, ty::TraitPredicate<I>> {
632 let trait_ref = relation.relate(a.trait_ref, b.trait_ref)?;
633 if a.polarity != b.polarity {
634 return Err(TypeError::PolarityMismatch(ExpectedFound::new(a.polarity, b.polarity)));
635 }
636 Ok(ty::TraitPredicate { trait_ref, polarity: a.polarity })
637 }
638}