rustc_type_ir/
fast_reject.rs

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/// See `simplify_type`.
19#[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    /// A trait object, all of whose components are markers
40    /// (e.g., `dyn Send + Sync`).
41    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/// Generic parameters are pretty much just bound variables, e.g.
66/// the type of `fn foo<'a, T>(x: &'a T) -> u32 { ... }` can be thought of as
67/// `for<'a, T> fn(&'a T) -> u32`.
68///
69/// Typecheck of `foo` has to succeed for all possible generic arguments, so
70/// during typeck, we have to treat its generic parameters as if they
71/// were placeholders.
72///
73/// But when calling `foo` we only have to provide a specific generic argument.
74/// In that case the generic parameters are instantiated with inference variables.
75/// As we use `simplify_type` before that instantiation happens, we just treat
76/// generic parameters as if they were inference variables in that case.
77#[derive(PartialEq, Eq, Debug, Clone, Copy)]
78pub enum TreatParams {
79    /// Treat parameters as infer vars. This is the correct mode for caching
80    /// an impl's type for lookup.
81    InstantiateWithInfer,
82    /// Treat parameters as placeholders in the given environment. This is the
83    /// correct mode for *lookup*, as during candidate selection.
84    ///
85    /// This also treats projections with inference variables as infer vars
86    /// since they could be further normalized.
87    // FIXME(@lcnr): This treats aliases as rigid. This is only correct if the
88    // type has been structurally normalized. We should reflect this requirement
89    // in the variant name. It is currently incorrectly used in diagnostics.
90    AsRigid,
91}
92
93/// Tries to simplify a type by only returning the outermost injective¹ layer, if one exists.
94///
95/// **This function should only be used if you need to store or retrieve the type from some
96/// hashmap. If you want to quickly decide whether two types may unify, use the [DeepRejectCtxt]
97/// instead.**
98///
99/// The idea is to get something simple that we can use to quickly decide if two types could unify,
100/// for example during method lookup. If this function returns `Some(x)` it can only unify with
101/// types for which this method returns either `Some(x)` as well or `None`.
102///
103/// A special case here are parameters and projections, which are only injective
104/// if they are treated as placeholders.
105///
106/// For example when storing impls based on their simplified self type, we treat
107/// generic parameters as if they were inference variables. We must not simplify them here,
108/// as they can unify with any other type.
109///
110/// With projections we have to be even more careful, as treating them as placeholders
111/// is only correct if they are fully normalized.
112///
113/// ¹ meaning that if the outermost layers are different, then the whole types are also different.
114pub 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            // When treating `ty::Param` as a placeholder, projections also
156            // don't unify with anything else as long as they are fully normalized.
157            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/// Given generic arguments, could they be unified after
185/// replacing parameters with inference variables or placeholders.
186/// This behavior is toggled using the const generics.
187///
188/// We use this to quickly reject impl/wc candidates without needing
189/// to instantiate generic arguments/having to enter a probe.
190///
191/// We also use this function during coherence. For coherence the
192/// impls only have to overlap for some value, so we treat parameters
193/// on both sides like inference variables.
194#[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    /// Treat parameters in both the lhs and the rhs as rigid.
205    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    /// Treat parameters in both the lhs and the rhs as infer vars.
212    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    /// Treat parameters in the lhs as rigid, and in rhs as infer vars.
219    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    // Quite arbitrary. Large enough to only affect a very tiny amount of impls/crates
228    // and small enough to prevent hangs.
229    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        // No need to decrement the depth here as this function is only
250        // recursively reachable via `types_may_unify_inner` which already
251        // increments the depth for us.
252        iter::zip(obligation_args.iter(), impl_args.iter()).all(|(obl, imp)| {
253            match (obl.kind(), imp.kind()) {
254                // We don't fast reject based on regions.
255                (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            // Start by checking whether the `rhs` type may unify with
274            // pretty much everything. Just return `true` in that case.
275            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            // These types only unify with inference variables or their own
284            // variant.
285            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        // The type system needs to support exponentially large types
312        // as long as they are self-similar. While most other folders
313        // use caching to handle them, this folder exists purely as a
314        // perf optimization and is incredibly hot. In pretty much all
315        // uses checking the cache is slower than simply recursing, so
316        // we instead just add an arbitrary depth cutoff.
317        //
318        // We only decrement the depth here as the match on `rhs`
319        // does not recurse.
320        let Some(depth) = depth.checked_sub(1) else {
321            return true;
322        };
323
324        // For purely rigid types, use structural equivalence.
325        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            // Depending on the value of const generics, we either treat generic parameters
341            // like placeholders or like inference variables.
342            ty::Param(lhs) => {
343                INSTANTIATE_LHS_WITH_INFER
344                    || match rhs.kind() {
345                        ty::Param(rhs) => lhs == rhs,
346                        _ => false,
347                    }
348            }
349
350            // Placeholder types don't unify with anything on their own.
351            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            // As we're walking the whole type, it may encounter projections
358            // inside of binders and what not, so we're just going to assume that
359            // projections can unify with other stuff.
360            //
361            // Looking forward to lazy normalization this is the safer strategy anyways.
362            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                // Ideally we would walk the existential predicates here or at least
403                // compare their length. But considering that the relevant `Relate` impl
404                // actually sorts and deduplicates these, that doesn't work.
405                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                // FIXME(pattern_types): take pattern into account
462                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    // Unlike `types_may_unify_inner`, this does not take a depth as
477    // we never recurse from this function.
478    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            // Placeholder consts don't unify with anything on their own
512            ty::ConstKind::Placeholder(lhs) => {
513                matches!(rhs.kind(), ty::ConstKind::Placeholder(rhs) if lhs == rhs)
514            }
515
516            // As we don't necessarily eagerly evaluate constants,
517            // they might unify with any value.
518            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}