rustc_type_ir/solve/
mod.rs

1pub mod inspect;
2
3use std::fmt;
4use std::hash::Hash;
5
6use derive_where::derive_where;
7#[cfg(feature = "nightly")]
8use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext};
9use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic};
10
11use crate::search_graph::PathKind;
12use crate::{self as ty, Canonical, CanonicalVarValues, Interner, Upcast};
13
14pub type CanonicalInput<I, T = <I as Interner>::Predicate> =
15    ty::CanonicalQueryInput<I, QueryInput<I, T>>;
16pub type CanonicalResponse<I> = Canonical<I, Response<I>>;
17/// The result of evaluating a canonical query.
18///
19/// FIXME: We use a different type than the existing canonical queries. This is because
20/// we need to add a `Certainty` for `overflow` and may want to restructure this code without
21/// having to worry about changes to currently used code. Once we've made progress on this
22/// solver, merge the two responses again.
23pub type QueryResult<I> = Result<CanonicalResponse<I>, NoSolution>;
24
25#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
26#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
27pub struct NoSolution;
28
29/// A goal is a statement, i.e. `predicate`, we want to prove
30/// given some assumptions, i.e. `param_env`.
31///
32/// Most of the time the `param_env` contains the `where`-bounds of the function
33/// we're currently typechecking while the `predicate` is some trait bound.
34#[derive_where(Clone; I: Interner, P: Clone)]
35#[derive_where(Copy; I: Interner, P: Copy)]
36#[derive_where(Hash; I: Interner, P: Hash)]
37#[derive_where(PartialEq; I: Interner, P: PartialEq)]
38#[derive_where(Eq; I: Interner, P: Eq)]
39#[derive_where(Debug; I: Interner, P: fmt::Debug)]
40#[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)]
41#[cfg_attr(
42    feature = "nightly",
43    derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext)
44)]
45pub struct Goal<I: Interner, P> {
46    pub param_env: I::ParamEnv,
47    pub predicate: P,
48}
49
50impl<I: Interner, P> Goal<I, P> {
51    pub fn new(cx: I, param_env: I::ParamEnv, predicate: impl Upcast<I, P>) -> Goal<I, P> {
52        Goal { param_env, predicate: predicate.upcast(cx) }
53    }
54
55    /// Updates the goal to one with a different `predicate` but the same `param_env`.
56    pub fn with<Q>(self, cx: I, predicate: impl Upcast<I, Q>) -> Goal<I, Q> {
57        Goal { param_env: self.param_env, predicate: predicate.upcast(cx) }
58    }
59}
60
61/// Why a specific goal has to be proven.
62///
63/// This is necessary as we treat nested goals different depending on
64/// their source. This is used to decide whether a cycle is coinductive.
65/// See the documentation of `EvalCtxt::step_kind_for_source` for more details
66/// about this.
67///
68/// It is also used by proof tree visitors, e.g. for diagnostics purposes.
69#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
70#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
71pub enum GoalSource {
72    Misc,
73    /// A nested goal required to prove that types are equal/subtypes.
74    /// This is always an unproductive step.
75    ///
76    /// This is also used for all `NormalizesTo` goals as we they are used
77    /// to relate types in `AliasRelate`.
78    TypeRelating,
79    /// We're proving a where-bound of an impl.
80    ImplWhereBound,
81    /// Const conditions that need to hold for `~const` alias bounds to hold.
82    AliasBoundConstCondition,
83    /// Instantiating a higher-ranked goal and re-proving it.
84    InstantiateHigherRanked,
85    /// Predicate required for an alias projection to be well-formed.
86    /// This is used in three places:
87    /// 1. projecting to an opaque whose hidden type is already registered in
88    ///    the opaque type storage,
89    /// 2. for rigid projections's trait goal,
90    /// 3. for GAT where clauses.
91    AliasWellFormed,
92    /// In case normalizing aliases in nested goals cycles, eagerly normalizing these
93    /// aliases in the context of the parent may incorrectly change the cycle kind.
94    /// Normalizing aliases in goals therefore tracks the original path kind for this
95    /// nested goal. See the comment of the `ReplaceAliasWithInfer` visitor for more
96    /// details.
97    NormalizeGoal(PathKind),
98}
99
100#[derive_where(Clone; I: Interner, Goal<I, P>: Clone)]
101#[derive_where(Copy; I: Interner, Goal<I, P>: Copy)]
102#[derive_where(Hash; I: Interner, Goal<I, P>: Hash)]
103#[derive_where(PartialEq; I: Interner, Goal<I, P>: PartialEq)]
104#[derive_where(Eq; I: Interner, Goal<I, P>: Eq)]
105#[derive_where(Debug; I: Interner, Goal<I, P>: fmt::Debug)]
106#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
107#[cfg_attr(
108    feature = "nightly",
109    derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext)
110)]
111pub struct QueryInput<I: Interner, P> {
112    pub goal: Goal<I, P>,
113    pub predefined_opaques_in_body: I::PredefinedOpaques,
114}
115
116/// Opaques that are defined in the inference context before a query is called.
117#[derive_where(Clone, Hash, PartialEq, Eq, Debug, Default; I: Interner)]
118#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
119#[cfg_attr(
120    feature = "nightly",
121    derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext)
122)]
123pub struct PredefinedOpaquesData<I: Interner> {
124    pub opaque_types: Vec<(ty::OpaqueTypeKey<I>, I::Ty)>,
125}
126
127/// Possible ways the given goal can be proven.
128#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)]
129pub enum CandidateSource<I: Interner> {
130    /// A user written impl.
131    ///
132    /// ## Examples
133    ///
134    /// ```rust
135    /// fn main() {
136    ///     let x: Vec<u32> = Vec::new();
137    ///     // This uses the impl from the standard library to prove `Vec<T>: Clone`.
138    ///     let y = x.clone();
139    /// }
140    /// ```
141    Impl(I::DefId),
142    /// A builtin impl generated by the compiler. When adding a new special
143    /// trait, try to use actual impls whenever possible. Builtin impls should
144    /// only be used in cases where the impl cannot be manually be written.
145    ///
146    /// Notable examples are auto traits, `Sized`, and `DiscriminantKind`.
147    /// For a list of all traits with builtin impls, check out the
148    /// `EvalCtxt::assemble_builtin_impl_candidates` method.
149    BuiltinImpl(BuiltinImplSource),
150    /// An assumption from the environment. Stores a [`ParamEnvSource`], since we
151    /// prefer non-global param-env candidates in candidate assembly.
152    ///
153    /// ## Examples
154    ///
155    /// ```rust
156    /// fn is_clone<T: Clone>(x: T) -> (T, T) {
157    ///     // This uses the assumption `T: Clone` from the `where`-bounds
158    ///     // to prove `T: Clone`.
159    ///     (x.clone(), x)
160    /// }
161    /// ```
162    ParamEnv(ParamEnvSource),
163    /// If the self type is an alias type, e.g. an opaque type or a projection,
164    /// we know the bounds on that alias to hold even without knowing its concrete
165    /// underlying type.
166    ///
167    /// More precisely this candidate is using the `n-th` bound in the `item_bounds` of
168    /// the self type.
169    ///
170    /// ## Examples
171    ///
172    /// ```rust
173    /// trait Trait {
174    ///     type Assoc: Clone;
175    /// }
176    ///
177    /// fn foo<T: Trait>(x: <T as Trait>::Assoc) {
178    ///     // We prove `<T as Trait>::Assoc` by looking at the bounds on `Assoc` in
179    ///     // in the trait definition.
180    ///     let _y = x.clone();
181    /// }
182    /// ```
183    AliasBound,
184    /// A candidate that is registered only during coherence to represent some
185    /// yet-unknown impl that could be produced downstream without violating orphan
186    /// rules.
187    // FIXME: Merge this with the forced ambiguity candidates, so those don't use `Misc`.
188    CoherenceUnknowable,
189}
190
191#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
192pub enum ParamEnvSource {
193    /// Preferred eagerly.
194    NonGlobal,
195    // Not considered unless there are non-global param-env candidates too.
196    Global,
197}
198
199#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
200#[cfg_attr(
201    feature = "nightly",
202    derive(HashStable_NoContext, Encodable_NoContext, Decodable_NoContext)
203)]
204pub enum BuiltinImplSource {
205    /// A built-in impl that is considered trivial, without any nested requirements. They
206    /// are preferred over where-clauses, and we want to track them explicitly.
207    Trivial,
208    /// Some built-in impl we don't need to differentiate. This should be used
209    /// unless more specific information is necessary.
210    Misc,
211    /// A built-in impl for trait objects. The index is only used in winnowing.
212    Object(usize),
213    /// A built-in implementation of `Upcast` for trait objects to other trait objects.
214    ///
215    /// The index is only used for winnowing.
216    TraitUpcasting(usize),
217}
218
219#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)]
220#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
221#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
222pub struct Response<I: Interner> {
223    pub certainty: Certainty,
224    pub var_values: CanonicalVarValues<I>,
225    /// Additional constraints returned by this query.
226    pub external_constraints: I::ExternalConstraints,
227}
228
229/// Additional constraints returned on success.
230#[derive_where(Clone, Hash, PartialEq, Eq, Debug, Default; I: Interner)]
231#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
232#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
233pub struct ExternalConstraintsData<I: Interner> {
234    pub region_constraints: Vec<ty::OutlivesPredicate<I, I::GenericArg>>,
235    pub opaque_types: Vec<(ty::OpaqueTypeKey<I>, I::Ty)>,
236    pub normalization_nested_goals: NestedNormalizationGoals<I>,
237}
238
239#[derive_where(Clone, Hash, PartialEq, Eq, Debug, Default; I: Interner)]
240#[derive(TypeVisitable_Generic, TypeFoldable_Generic)]
241#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
242pub struct NestedNormalizationGoals<I: Interner>(pub Vec<(GoalSource, Goal<I, I::Predicate>)>);
243
244impl<I: Interner> NestedNormalizationGoals<I> {
245    pub fn empty() -> Self {
246        NestedNormalizationGoals(vec![])
247    }
248
249    pub fn is_empty(&self) -> bool {
250        self.0.is_empty()
251    }
252}
253
254#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
255#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
256pub enum Certainty {
257    Yes,
258    Maybe(MaybeCause),
259}
260
261impl Certainty {
262    pub const AMBIGUOUS: Certainty = Certainty::Maybe(MaybeCause::Ambiguity);
263
264    /// Use this function to merge the certainty of multiple nested subgoals.
265    ///
266    /// Given an impl like `impl<T: Foo + Bar> Baz for T {}`, we have 2 nested
267    /// subgoals whenever we use the impl as a candidate: `T: Foo` and `T: Bar`.
268    /// If evaluating `T: Foo` results in ambiguity and `T: Bar` results in
269    /// success, we merge these two responses. This results in ambiguity.
270    ///
271    /// If we unify ambiguity with overflow, we return overflow. This doesn't matter
272    /// inside of the solver as we do not distinguish ambiguity from overflow. It does
273    /// however matter for diagnostics. If `T: Foo` resulted in overflow and `T: Bar`
274    /// in ambiguity without changing the inference state, we still want to tell the
275    /// user that `T: Baz` results in overflow.
276    pub fn and(self, other: Certainty) -> Certainty {
277        match (self, other) {
278            (Certainty::Yes, Certainty::Yes) => Certainty::Yes,
279            (Certainty::Yes, Certainty::Maybe(_)) => other,
280            (Certainty::Maybe(_), Certainty::Yes) => self,
281            (Certainty::Maybe(a), Certainty::Maybe(b)) => Certainty::Maybe(a.and(b)),
282        }
283    }
284
285    pub const fn overflow(suggest_increasing_limit: bool) -> Certainty {
286        Certainty::Maybe(MaybeCause::Overflow { suggest_increasing_limit, keep_constraints: false })
287    }
288}
289
290/// Why we failed to evaluate a goal.
291#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
292#[cfg_attr(feature = "nightly", derive(HashStable_NoContext))]
293pub enum MaybeCause {
294    /// We failed due to ambiguity. This ambiguity can either
295    /// be a true ambiguity, i.e. there are multiple different answers,
296    /// or we hit a case where we just don't bother, e.g. `?x: Trait` goals.
297    Ambiguity,
298    /// We gave up due to an overflow, most often by hitting the recursion limit.
299    Overflow { suggest_increasing_limit: bool, keep_constraints: bool },
300}
301
302impl MaybeCause {
303    fn and(self, other: MaybeCause) -> MaybeCause {
304        match (self, other) {
305            (MaybeCause::Ambiguity, MaybeCause::Ambiguity) => MaybeCause::Ambiguity,
306            (MaybeCause::Ambiguity, MaybeCause::Overflow { .. }) => other,
307            (MaybeCause::Overflow { .. }, MaybeCause::Ambiguity) => self,
308            (
309                MaybeCause::Overflow {
310                    suggest_increasing_limit: limit_a,
311                    keep_constraints: keep_a,
312                },
313                MaybeCause::Overflow {
314                    suggest_increasing_limit: limit_b,
315                    keep_constraints: keep_b,
316                },
317            ) => MaybeCause::Overflow {
318                suggest_increasing_limit: limit_a && limit_b,
319                keep_constraints: keep_a && keep_b,
320            },
321        }
322    }
323
324    pub fn or(self, other: MaybeCause) -> MaybeCause {
325        match (self, other) {
326            (MaybeCause::Ambiguity, MaybeCause::Ambiguity) => MaybeCause::Ambiguity,
327
328            // When combining ambiguity + overflow, we can keep constraints.
329            (
330                MaybeCause::Ambiguity,
331                MaybeCause::Overflow { suggest_increasing_limit, keep_constraints: _ },
332            ) => MaybeCause::Overflow { suggest_increasing_limit, keep_constraints: true },
333            (
334                MaybeCause::Overflow { suggest_increasing_limit, keep_constraints: _ },
335                MaybeCause::Ambiguity,
336            ) => MaybeCause::Overflow { suggest_increasing_limit, keep_constraints: true },
337
338            (
339                MaybeCause::Overflow {
340                    suggest_increasing_limit: limit_a,
341                    keep_constraints: keep_a,
342                },
343                MaybeCause::Overflow {
344                    suggest_increasing_limit: limit_b,
345                    keep_constraints: keep_b,
346                },
347            ) => MaybeCause::Overflow {
348                suggest_increasing_limit: limit_a || limit_b,
349                keep_constraints: keep_a || keep_b,
350            },
351        }
352    }
353}
354
355/// Indicates that a `impl Drop for Adt` is `const` or not.
356#[derive(Debug)]
357pub enum AdtDestructorKind {
358    NotConst,
359    Const,
360}