1use std::fmt::Debug;
2use std::hash::Hash;
3use std::iter;
4use std::marker::PhantomData;
5
6use rustc_ast_ir::Mutability;
7#[cfg(feature = "nightly")]
8use rustc_data_structures::fingerprint::Fingerprint;
9#[cfg(feature = "nightly")]
10use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
11#[cfg(feature = "nightly")]
12use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext};
13
14use crate::inherent::*;
15use crate::visit::TypeVisitableExt as _;
16use crate::{self as ty, Interner};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20#[cfg_attr(
21 feature = "nightly",
22 derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext)
23)]
24pub enum SimplifiedType<DefId> {
25 Bool,
26 Char,
27 Int(ty::IntTy),
28 Uint(ty::UintTy),
29 Float(ty::FloatTy),
30 Adt(DefId),
31 Foreign(DefId),
32 Str,
33 Array,
34 Slice,
35 Ref(Mutability),
36 Ptr(Mutability),
37 Never,
38 Tuple(usize),
39 MarkerTraitObject,
42 Trait(DefId),
43 Closure(DefId),
44 Coroutine(DefId),
45 CoroutineWitness(DefId),
46 Function(usize),
47 UnsafeBinder,
48 Placeholder,
49 Error,
50}
51
52#[cfg(feature = "nightly")]
53impl<HCX: Clone, DefId: HashStable<HCX>> ToStableHashKey<HCX> for SimplifiedType<DefId> {
54 type KeyType = Fingerprint;
55
56 #[inline]
57 fn to_stable_hash_key(&self, hcx: &HCX) -> Fingerprint {
58 let mut hasher = StableHasher::new();
59 let mut hcx: HCX = hcx.clone();
60 self.hash_stable(&mut hcx, &mut hasher);
61 hasher.finish()
62 }
63}
64
65#[derive(PartialEq, Eq, Debug, Clone, Copy)]
78pub enum TreatParams {
79 InstantiateWithInfer,
82 AsRigid,
91}
92
93pub fn simplify_type<I: Interner>(
115 cx: I,
116 ty: I::Ty,
117 treat_params: TreatParams,
118) -> Option<SimplifiedType<I::DefId>> {
119 match ty.kind() {
120 ty::Bool => Some(SimplifiedType::Bool),
121 ty::Char => Some(SimplifiedType::Char),
122 ty::Int(int_type) => Some(SimplifiedType::Int(int_type)),
123 ty::Uint(uint_type) => Some(SimplifiedType::Uint(uint_type)),
124 ty::Float(float_type) => Some(SimplifiedType::Float(float_type)),
125 ty::Adt(def, _) => Some(SimplifiedType::Adt(def.def_id())),
126 ty::Str => Some(SimplifiedType::Str),
127 ty::Array(..) => Some(SimplifiedType::Array),
128 ty::Slice(..) => Some(SimplifiedType::Slice),
129 ty::Pat(ty, ..) => simplify_type(cx, ty, treat_params),
130 ty::RawPtr(_, mutbl) => Some(SimplifiedType::Ptr(mutbl)),
131 ty::Dynamic(trait_info, ..) => match trait_info.principal_def_id() {
132 Some(principal_def_id) if !cx.trait_is_auto(principal_def_id) => {
133 Some(SimplifiedType::Trait(principal_def_id))
134 }
135 _ => Some(SimplifiedType::MarkerTraitObject),
136 },
137 ty::Ref(_, _, mutbl) => Some(SimplifiedType::Ref(mutbl)),
138 ty::FnDef(def_id, _) | ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _) => {
139 Some(SimplifiedType::Closure(def_id))
140 }
141 ty::Coroutine(def_id, _) => Some(SimplifiedType::Coroutine(def_id)),
142 ty::CoroutineWitness(def_id, _) => Some(SimplifiedType::CoroutineWitness(def_id)),
143 ty::Never => Some(SimplifiedType::Never),
144 ty::Tuple(tys) => Some(SimplifiedType::Tuple(tys.len())),
145 ty::FnPtr(sig_tys, _hdr) => {
146 Some(SimplifiedType::Function(sig_tys.skip_binder().inputs().len()))
147 }
148 ty::UnsafeBinder(_) => Some(SimplifiedType::UnsafeBinder),
149 ty::Placeholder(..) => Some(SimplifiedType::Placeholder),
150 ty::Param(_) => match treat_params {
151 TreatParams::AsRigid => Some(SimplifiedType::Placeholder),
152 TreatParams::InstantiateWithInfer => None,
153 },
154 ty::Alias(..) => match treat_params {
155 TreatParams::AsRigid
158 if !ty.has_non_region_infer() || cx.next_trait_solver_globally() =>
159 {
160 Some(SimplifiedType::Placeholder)
161 }
162 TreatParams::AsRigid | TreatParams::InstantiateWithInfer => None,
163 },
164 ty::Foreign(def_id) => Some(SimplifiedType::Foreign(def_id)),
165 ty::Error(_) => Some(SimplifiedType::Error),
166 ty::Bound(..) | ty::Infer(_) => None,
167 }
168}
169
170impl<DefId> SimplifiedType<DefId> {
171 pub fn def(self) -> Option<DefId> {
172 match self {
173 SimplifiedType::Adt(d)
174 | SimplifiedType::Foreign(d)
175 | SimplifiedType::Trait(d)
176 | SimplifiedType::Closure(d)
177 | SimplifiedType::Coroutine(d)
178 | SimplifiedType::CoroutineWitness(d) => Some(d),
179 _ => None,
180 }
181 }
182}
183
184#[derive(Debug, Clone, Copy)]
195pub struct DeepRejectCtxt<
196 I: Interner,
197 const INSTANTIATE_LHS_WITH_INFER: bool,
198 const INSTANTIATE_RHS_WITH_INFER: bool,
199> {
200 _interner: PhantomData<I>,
201}
202
203impl<I: Interner> DeepRejectCtxt<I, false, false> {
204 pub fn relate_rigid_rigid(_interner: I) -> DeepRejectCtxt<I, false, false> {
206 DeepRejectCtxt { _interner: PhantomData }
207 }
208}
209
210impl<I: Interner> DeepRejectCtxt<I, true, true> {
211 pub fn relate_infer_infer(_interner: I) -> DeepRejectCtxt<I, true, true> {
213 DeepRejectCtxt { _interner: PhantomData }
214 }
215}
216
217impl<I: Interner> DeepRejectCtxt<I, false, true> {
218 pub fn relate_rigid_infer(_interner: I) -> DeepRejectCtxt<I, false, true> {
220 DeepRejectCtxt { _interner: PhantomData }
221 }
222}
223
224impl<I: Interner, const INSTANTIATE_LHS_WITH_INFER: bool, const INSTANTIATE_RHS_WITH_INFER: bool>
225 DeepRejectCtxt<I, INSTANTIATE_LHS_WITH_INFER, INSTANTIATE_RHS_WITH_INFER>
226{
227 const STARTING_DEPTH: usize = 8;
230
231 pub fn args_may_unify(
232 self,
233 obligation_args: I::GenericArgs,
234 impl_args: I::GenericArgs,
235 ) -> bool {
236 self.args_may_unify_inner(obligation_args, impl_args, Self::STARTING_DEPTH)
237 }
238
239 pub fn types_may_unify(self, lhs: I::Ty, rhs: I::Ty) -> bool {
240 self.types_may_unify_inner(lhs, rhs, Self::STARTING_DEPTH)
241 }
242
243 fn args_may_unify_inner(
244 self,
245 obligation_args: I::GenericArgs,
246 impl_args: I::GenericArgs,
247 depth: usize,
248 ) -> bool {
249 iter::zip(obligation_args.iter(), impl_args.iter()).all(|(obl, imp)| {
253 match (obl.kind(), imp.kind()) {
254 (ty::GenericArgKind::Lifetime(_), ty::GenericArgKind::Lifetime(_)) => true,
256 (ty::GenericArgKind::Type(obl), ty::GenericArgKind::Type(imp)) => {
257 self.types_may_unify_inner(obl, imp, depth)
258 }
259 (ty::GenericArgKind::Const(obl), ty::GenericArgKind::Const(imp)) => {
260 self.consts_may_unify_inner(obl, imp)
261 }
262 _ => panic!("kind mismatch: {obl:?} {imp:?}"),
263 }
264 })
265 }
266
267 fn types_may_unify_inner(self, lhs: I::Ty, rhs: I::Ty, depth: usize) -> bool {
268 if lhs == rhs {
269 return true;
270 }
271
272 match rhs.kind() {
273 ty::Param(_) => {
276 if INSTANTIATE_RHS_WITH_INFER {
277 return true;
278 }
279 }
280 ty::Error(_) | ty::Alias(..) | ty::Bound(..) => return true,
281 ty::Infer(var) => return self.var_and_ty_may_unify(var, lhs),
282
283 ty::Bool
286 | ty::Char
287 | ty::Int(_)
288 | ty::Uint(_)
289 | ty::Float(_)
290 | ty::Adt(..)
291 | ty::Str
292 | ty::Array(..)
293 | ty::Slice(..)
294 | ty::RawPtr(..)
295 | ty::Dynamic(..)
296 | ty::Pat(..)
297 | ty::Ref(..)
298 | ty::Never
299 | ty::Tuple(..)
300 | ty::FnDef(..)
301 | ty::FnPtr(..)
302 | ty::Closure(..)
303 | ty::CoroutineClosure(..)
304 | ty::Coroutine(..)
305 | ty::CoroutineWitness(..)
306 | ty::Foreign(_)
307 | ty::Placeholder(_)
308 | ty::UnsafeBinder(_) => {}
309 };
310
311 let Some(depth) = depth.checked_sub(1) else {
321 return true;
322 };
323
324 match lhs.kind() {
326 ty::Ref(_, lhs_ty, lhs_mutbl) => match rhs.kind() {
327 ty::Ref(_, rhs_ty, rhs_mutbl) => {
328 lhs_mutbl == rhs_mutbl && self.types_may_unify_inner(lhs_ty, rhs_ty, depth)
329 }
330 _ => false,
331 },
332
333 ty::Adt(lhs_def, lhs_args) => match rhs.kind() {
334 ty::Adt(rhs_def, rhs_args) => {
335 lhs_def == rhs_def && self.args_may_unify_inner(lhs_args, rhs_args, depth)
336 }
337 _ => false,
338 },
339
340 ty::Param(lhs) => {
343 INSTANTIATE_LHS_WITH_INFER
344 || match rhs.kind() {
345 ty::Param(rhs) => lhs == rhs,
346 _ => false,
347 }
348 }
349
350 ty::Placeholder(lhs) => {
352 matches!(rhs.kind(), ty::Placeholder(rhs) if lhs == rhs)
353 }
354
355 ty::Infer(var) => self.var_and_ty_may_unify(var, rhs),
356
357 ty::Alias(..) => true,
363
364 ty::Int(_)
365 | ty::Uint(_)
366 | ty::Float(_)
367 | ty::Str
368 | ty::Bool
369 | ty::Char
370 | ty::Never
371 | ty::Foreign(_) => lhs == rhs,
372
373 ty::Tuple(lhs) => match rhs.kind() {
374 ty::Tuple(rhs) => {
375 lhs.len() == rhs.len()
376 && iter::zip(lhs.iter(), rhs.iter())
377 .all(|(lhs, rhs)| self.types_may_unify_inner(lhs, rhs, depth))
378 }
379 _ => false,
380 },
381
382 ty::Array(lhs_ty, lhs_len) => match rhs.kind() {
383 ty::Array(rhs_ty, rhs_len) => {
384 self.types_may_unify_inner(lhs_ty, rhs_ty, depth)
385 && self.consts_may_unify_inner(lhs_len, rhs_len)
386 }
387 _ => false,
388 },
389
390 ty::RawPtr(lhs_ty, lhs_mutbl) => match rhs.kind() {
391 ty::RawPtr(rhs_ty, rhs_mutbl) => {
392 lhs_mutbl == rhs_mutbl && self.types_may_unify_inner(lhs_ty, rhs_ty, depth)
393 }
394 _ => false,
395 },
396
397 ty::Slice(lhs_ty) => {
398 matches!(rhs.kind(), ty::Slice(rhs_ty) if self.types_may_unify_inner(lhs_ty, rhs_ty, depth))
399 }
400
401 ty::Dynamic(lhs_preds, ..) => {
402 matches!(rhs.kind(), ty::Dynamic(rhs_preds, ..) if
406 lhs_preds.principal_def_id() == rhs_preds.principal_def_id()
407 )
408 }
409
410 ty::FnPtr(lhs_sig_tys, lhs_hdr) => match rhs.kind() {
411 ty::FnPtr(rhs_sig_tys, rhs_hdr) => {
412 let lhs_sig_tys = lhs_sig_tys.skip_binder().inputs_and_output;
413 let rhs_sig_tys = rhs_sig_tys.skip_binder().inputs_and_output;
414
415 lhs_hdr == rhs_hdr
416 && lhs_sig_tys.len() == rhs_sig_tys.len()
417 && iter::zip(lhs_sig_tys.iter(), rhs_sig_tys.iter())
418 .all(|(lhs, rhs)| self.types_may_unify_inner(lhs, rhs, depth))
419 }
420 _ => false,
421 },
422
423 ty::Bound(..) => true,
424
425 ty::FnDef(lhs_def_id, lhs_args) => match rhs.kind() {
426 ty::FnDef(rhs_def_id, rhs_args) => {
427 lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
428 }
429 _ => false,
430 },
431
432 ty::Closure(lhs_def_id, lhs_args) => match rhs.kind() {
433 ty::Closure(rhs_def_id, rhs_args) => {
434 lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
435 }
436 _ => false,
437 },
438
439 ty::CoroutineClosure(lhs_def_id, lhs_args) => match rhs.kind() {
440 ty::CoroutineClosure(rhs_def_id, rhs_args) => {
441 lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
442 }
443 _ => false,
444 },
445
446 ty::Coroutine(lhs_def_id, lhs_args) => match rhs.kind() {
447 ty::Coroutine(rhs_def_id, rhs_args) => {
448 lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
449 }
450 _ => false,
451 },
452
453 ty::CoroutineWitness(lhs_def_id, lhs_args) => match rhs.kind() {
454 ty::CoroutineWitness(rhs_def_id, rhs_args) => {
455 lhs_def_id == rhs_def_id && self.args_may_unify_inner(lhs_args, rhs_args, depth)
456 }
457 _ => false,
458 },
459
460 ty::Pat(lhs_ty, _) => {
461 matches!(rhs.kind(), ty::Pat(rhs_ty, _) if self.types_may_unify_inner(lhs_ty, rhs_ty, depth))
463 }
464
465 ty::UnsafeBinder(lhs_ty) => match rhs.kind() {
466 ty::UnsafeBinder(rhs_ty) => {
467 self.types_may_unify(lhs_ty.skip_binder(), rhs_ty.skip_binder())
468 }
469 _ => false,
470 },
471
472 ty::Error(..) => true,
473 }
474 }
475
476 fn consts_may_unify_inner(self, lhs: I::Const, rhs: I::Const) -> bool {
479 match rhs.kind() {
480 ty::ConstKind::Param(_) => {
481 if INSTANTIATE_RHS_WITH_INFER {
482 return true;
483 }
484 }
485
486 ty::ConstKind::Expr(_)
487 | ty::ConstKind::Unevaluated(_)
488 | ty::ConstKind::Error(_)
489 | ty::ConstKind::Infer(_)
490 | ty::ConstKind::Bound(..) => {
491 return true;
492 }
493
494 ty::ConstKind::Value(..) | ty::ConstKind::Placeholder(_) => {}
495 };
496
497 match lhs.kind() {
498 ty::ConstKind::Value(lhs_val) => match rhs.kind() {
499 ty::ConstKind::Value(rhs_val) => lhs_val.valtree() == rhs_val.valtree(),
500 _ => false,
501 },
502
503 ty::ConstKind::Param(lhs) => {
504 INSTANTIATE_LHS_WITH_INFER
505 || match rhs.kind() {
506 ty::ConstKind::Param(rhs) => lhs == rhs,
507 _ => false,
508 }
509 }
510
511 ty::ConstKind::Placeholder(lhs) => {
513 matches!(rhs.kind(), ty::ConstKind::Placeholder(rhs) if lhs == rhs)
514 }
515
516 ty::ConstKind::Expr(_) | ty::ConstKind::Unevaluated(_) | ty::ConstKind::Error(_) => {
519 true
520 }
521
522 ty::ConstKind::Infer(_) | ty::ConstKind::Bound(..) => true,
523 }
524 }
525
526 fn var_and_ty_may_unify(self, var: ty::InferTy, ty: I::Ty) -> bool {
527 if !ty.is_known_rigid() {
528 return true;
529 }
530
531 match var {
532 ty::IntVar(_) => ty.is_integral(),
533 ty::FloatVar(_) => ty.is_floating_point(),
534 _ => true,
535 }
536 }
537}