rustc_next_trait_solver/solve/
mod.rs

1//! The next-generation trait solver, currently still WIP.
2//!
3//! As a user of rust, you can use `-Znext-solver` to enable the new trait solver.
4//!
5//! As a developer of rustc, you shouldn't be using the new trait
6//! solver without asking the trait-system-refactor-initiative, but it can
7//! be enabled with `InferCtxtBuilder::with_next_trait_solver`. This will
8//! ensure that trait solving using that inference context will be routed
9//! to the new trait solver.
10//!
11//! For a high-level overview of how this solver works, check out the relevant
12//! section of the rustc-dev-guide.
13
14mod alias_relate;
15mod assembly;
16mod effect_goals;
17mod eval_ctxt;
18pub mod inspect;
19mod normalizes_to;
20mod project_goals;
21mod search_graph;
22mod trait_goals;
23
24use derive_where::derive_where;
25use rustc_type_ir::inherent::*;
26pub use rustc_type_ir::solve::*;
27use rustc_type_ir::{self as ty, Interner, TypingMode};
28use tracing::instrument;
29
30pub use self::eval_ctxt::{EvalCtxt, GenerateProofTree, SolverDelegateEvalExt};
31use crate::delegate::SolverDelegate;
32use crate::solve::assembly::Candidate;
33
34/// How many fixpoint iterations we should attempt inside of the solver before bailing
35/// with overflow.
36///
37/// We previously used  `cx.recursion_limit().0.checked_ilog2().unwrap_or(0)` for this.
38/// However, it feels unlikely that uncreasing the recursion limit by a power of two
39/// to get one more itereation is every useful or desirable. We now instead used a constant
40/// here. If there ever ends up some use-cases where a bigger number of fixpoint iterations
41/// is required, we can add a new attribute for that or revert this to be dependant on the
42/// recursion limit again. However, this feels very unlikely.
43const FIXPOINT_STEP_LIMIT: usize = 8;
44
45#[derive(Debug, Copy, Clone, PartialEq, Eq)]
46enum GoalEvaluationKind {
47    Root,
48    Nested,
49}
50
51/// Whether evaluating this goal ended up changing the
52/// inference state.
53#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
54pub enum HasChanged {
55    Yes,
56    No,
57}
58
59// FIXME(trait-system-refactor-initiative#117): we don't detect whether a response
60// ended up pulling down any universes.
61fn has_no_inference_or_external_constraints<I: Interner>(
62    response: ty::Canonical<I, Response<I>>,
63) -> bool {
64    let ExternalConstraintsData {
65        ref region_constraints,
66        ref opaque_types,
67        ref normalization_nested_goals,
68    } = *response.value.external_constraints;
69    response.value.var_values.is_identity()
70        && region_constraints.is_empty()
71        && opaque_types.is_empty()
72        && normalization_nested_goals.is_empty()
73}
74
75fn has_only_region_constraints<I: Interner>(response: ty::Canonical<I, Response<I>>) -> bool {
76    let ExternalConstraintsData {
77        region_constraints: _,
78        ref opaque_types,
79        ref normalization_nested_goals,
80    } = *response.value.external_constraints;
81    response.value.var_values.is_identity_modulo_regions()
82        && opaque_types.is_empty()
83        && normalization_nested_goals.is_empty()
84}
85
86impl<'a, D, I> EvalCtxt<'a, D>
87where
88    D: SolverDelegate<Interner = I>,
89    I: Interner,
90{
91    #[instrument(level = "trace", skip(self))]
92    fn compute_type_outlives_goal(
93        &mut self,
94        goal: Goal<I, ty::OutlivesPredicate<I, I::Ty>>,
95    ) -> QueryResult<I> {
96        let ty::OutlivesPredicate(ty, lt) = goal.predicate;
97        self.register_ty_outlives(ty, lt);
98        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
99    }
100
101    #[instrument(level = "trace", skip(self))]
102    fn compute_region_outlives_goal(
103        &mut self,
104        goal: Goal<I, ty::OutlivesPredicate<I, I::Region>>,
105    ) -> QueryResult<I> {
106        let ty::OutlivesPredicate(a, b) = goal.predicate;
107        self.register_region_outlives(a, b);
108        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
109    }
110
111    #[instrument(level = "trace", skip(self))]
112    fn compute_coerce_goal(&mut self, goal: Goal<I, ty::CoercePredicate<I>>) -> QueryResult<I> {
113        self.compute_subtype_goal(Goal {
114            param_env: goal.param_env,
115            predicate: ty::SubtypePredicate {
116                a_is_expected: false,
117                a: goal.predicate.a,
118                b: goal.predicate.b,
119            },
120        })
121    }
122
123    #[instrument(level = "trace", skip(self))]
124    fn compute_subtype_goal(&mut self, goal: Goal<I, ty::SubtypePredicate<I>>) -> QueryResult<I> {
125        if goal.predicate.a.is_ty_var() && goal.predicate.b.is_ty_var() {
126            self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
127        } else {
128            self.sub(goal.param_env, goal.predicate.a, goal.predicate.b)?;
129            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
130        }
131    }
132
133    fn compute_dyn_compatible_goal(&mut self, trait_def_id: I::TraitId) -> QueryResult<I> {
134        if self.cx().trait_is_dyn_compatible(trait_def_id) {
135            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
136        } else {
137            Err(NoSolution)
138        }
139    }
140
141    #[instrument(level = "trace", skip(self))]
142    fn compute_well_formed_goal(&mut self, goal: Goal<I, I::Term>) -> QueryResult<I> {
143        match self.well_formed_goals(goal.param_env, goal.predicate) {
144            Some(goals) => {
145                self.add_goals(GoalSource::Misc, goals);
146                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
147            }
148            None => self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS),
149        }
150    }
151
152    fn compute_unstable_feature_goal(
153        &mut self,
154        param_env: <I as Interner>::ParamEnv,
155        symbol: <I as Interner>::Symbol,
156    ) -> QueryResult<I> {
157        if self.may_use_unstable_feature(param_env, symbol) {
158            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
159        } else {
160            self.evaluate_added_goals_and_make_canonical_response(Certainty::Maybe(
161                MaybeCause::Ambiguity,
162            ))
163        }
164    }
165
166    #[instrument(level = "trace", skip(self))]
167    fn compute_const_evaluatable_goal(
168        &mut self,
169        Goal { param_env, predicate: ct }: Goal<I, I::Const>,
170    ) -> QueryResult<I> {
171        match ct.kind() {
172            ty::ConstKind::Unevaluated(uv) => {
173                // We never return `NoSolution` here as `evaluate_const` emits an
174                // error itself when failing to evaluate, so emitting an additional fulfillment
175                // error in that case is unnecessary noise. This may change in the future once
176                // evaluation failures are allowed to impact selection, e.g. generic const
177                // expressions in impl headers or `where`-clauses.
178
179                // FIXME(generic_const_exprs): Implement handling for generic
180                // const expressions here.
181                if let Some(_normalized) = self.evaluate_const(param_env, uv) {
182                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
183                } else {
184                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
185                }
186            }
187            ty::ConstKind::Infer(_) => {
188                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
189            }
190            ty::ConstKind::Placeholder(_) | ty::ConstKind::Value(_) | ty::ConstKind::Error(_) => {
191                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
192            }
193            // We can freely ICE here as:
194            // - `Param` gets replaced with a placeholder during canonicalization
195            // - `Bound` cannot exist as we don't have a binder around the self Type
196            // - `Expr` is part of `feature(generic_const_exprs)` and is not implemented yet
197            ty::ConstKind::Param(_) | ty::ConstKind::Bound(_, _) | ty::ConstKind::Expr(_) => {
198                panic!("unexpected const kind: {:?}", ct)
199            }
200        }
201    }
202
203    #[instrument(level = "trace", skip(self), ret)]
204    fn compute_const_arg_has_type_goal(
205        &mut self,
206        goal: Goal<I, (I::Const, I::Ty)>,
207    ) -> QueryResult<I> {
208        let (ct, ty) = goal.predicate;
209        let ct = self.structurally_normalize_const(goal.param_env, ct)?;
210
211        let ct_ty = match ct.kind() {
212            ty::ConstKind::Infer(_) => {
213                return self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS);
214            }
215            ty::ConstKind::Error(_) => {
216                return self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes);
217            }
218            ty::ConstKind::Unevaluated(uv) => {
219                self.cx().type_of(uv.def).instantiate(self.cx(), uv.args)
220            }
221            ty::ConstKind::Expr(_) => unimplemented!(
222                "`feature(generic_const_exprs)` is not supported in the new trait solver"
223            ),
224            ty::ConstKind::Param(_) => {
225                unreachable!("`ConstKind::Param` should have been canonicalized to `Placeholder`")
226            }
227            ty::ConstKind::Bound(_, _) => panic!("escaping bound vars in {:?}", ct),
228            ty::ConstKind::Value(cv) => cv.ty(),
229            ty::ConstKind::Placeholder(placeholder) => {
230                placeholder.find_const_ty_from_env(goal.param_env)
231            }
232        };
233
234        self.eq(goal.param_env, ct_ty, ty)?;
235        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
236    }
237}
238
239#[derive(Debug)]
240enum MergeCandidateInfo {
241    AlwaysApplicable(usize),
242    EqualResponse,
243}
244
245impl<D, I> EvalCtxt<'_, D>
246where
247    D: SolverDelegate<Interner = I>,
248    I: Interner,
249{
250    /// Try to merge multiple possible ways to prove a goal, if that is not possible returns `None`.
251    ///
252    /// In this case we tend to flounder and return ambiguity by calling `[EvalCtxt::flounder]`.
253    #[instrument(level = "trace", skip(self), ret)]
254    fn try_merge_candidates(
255        &mut self,
256        candidates: &[Candidate<I>],
257    ) -> Option<(CanonicalResponse<I>, MergeCandidateInfo)> {
258        if candidates.is_empty() {
259            return None;
260        }
261
262        let always_applicable = candidates.iter().enumerate().find(|(_, candidate)| {
263            candidate.result.value.certainty == Certainty::Yes
264                && has_no_inference_or_external_constraints(candidate.result)
265        });
266        if let Some((i, c)) = always_applicable {
267            return Some((c.result, MergeCandidateInfo::AlwaysApplicable(i)));
268        }
269
270        let one: CanonicalResponse<I> = candidates[0].result;
271        if candidates[1..].iter().all(|candidate| candidate.result == one) {
272            return Some((one, MergeCandidateInfo::EqualResponse));
273        }
274
275        None
276    }
277
278    fn bail_with_ambiguity(&mut self, candidates: &[Candidate<I>]) -> CanonicalResponse<I> {
279        debug_assert!(candidates.len() > 1);
280        let maybe_cause =
281            candidates.iter().fold(MaybeCause::Ambiguity, |maybe_cause, candidates| {
282                // Pull down the certainty of `Certainty::Yes` to ambiguity when combining
283                // these responses, b/c we're combining more than one response and this we
284                // don't know which one applies.
285                let candidate = match candidates.result.value.certainty {
286                    Certainty::Yes => MaybeCause::Ambiguity,
287                    Certainty::Maybe(candidate) => candidate,
288                };
289                maybe_cause.or(candidate)
290            });
291        self.make_ambiguous_response_no_constraints(maybe_cause)
292    }
293
294    /// If we fail to merge responses we flounder and return overflow or ambiguity.
295    #[instrument(level = "trace", skip(self), ret)]
296    fn flounder(&mut self, candidates: &[Candidate<I>]) -> QueryResult<I> {
297        if candidates.is_empty() {
298            return Err(NoSolution);
299        } else {
300            Ok(self.bail_with_ambiguity(candidates))
301        }
302    }
303
304    /// Normalize a type for when it is structurally matched on.
305    ///
306    /// This function is necessary in nearly all cases before matching on a type.
307    /// Not doing so is likely to be incomplete and therefore unsound during
308    /// coherence.
309    #[instrument(level = "trace", skip(self, param_env), ret)]
310    fn structurally_normalize_ty(
311        &mut self,
312        param_env: I::ParamEnv,
313        ty: I::Ty,
314    ) -> Result<I::Ty, NoSolution> {
315        self.structurally_normalize_term(param_env, ty.into()).map(|term| term.expect_ty())
316    }
317
318    /// Normalize a const for when it is structurally matched on, or more likely
319    /// when it needs `.try_to_*` called on it (e.g. to turn it into a usize).
320    ///
321    /// This function is necessary in nearly all cases before matching on a const.
322    /// Not doing so is likely to be incomplete and therefore unsound during
323    /// coherence.
324    #[instrument(level = "trace", skip(self, param_env), ret)]
325    fn structurally_normalize_const(
326        &mut self,
327        param_env: I::ParamEnv,
328        ct: I::Const,
329    ) -> Result<I::Const, NoSolution> {
330        self.structurally_normalize_term(param_env, ct.into()).map(|term| term.expect_const())
331    }
332
333    /// Normalize a term for when it is structurally matched on.
334    ///
335    /// This function is necessary in nearly all cases before matching on a ty/const.
336    /// Not doing so is likely to be incomplete and therefore unsound during coherence.
337    fn structurally_normalize_term(
338        &mut self,
339        param_env: I::ParamEnv,
340        term: I::Term,
341    ) -> Result<I::Term, NoSolution> {
342        if let Some(_) = term.to_alias_term() {
343            let normalized_term = self.next_term_infer_of_kind(term);
344            let alias_relate_goal = Goal::new(
345                self.cx(),
346                param_env,
347                ty::PredicateKind::AliasRelate(
348                    term,
349                    normalized_term,
350                    ty::AliasRelationDirection::Equate,
351                ),
352            );
353            // We normalize the self type to be able to relate it with
354            // types from candidates.
355            self.add_goal(GoalSource::TypeRelating, alias_relate_goal);
356            self.try_evaluate_added_goals()?;
357            Ok(self.resolve_vars_if_possible(normalized_term))
358        } else {
359            Ok(term)
360        }
361    }
362
363    fn opaque_type_is_rigid(&self, def_id: I::DefId) -> bool {
364        match self.typing_mode() {
365            // Opaques are never rigid outside of analysis mode.
366            TypingMode::Coherence | TypingMode::PostAnalysis => false,
367            // During analysis, opaques are rigid unless they may be defined by
368            // the current body.
369            TypingMode::Analysis { defining_opaque_types_and_generators: non_rigid_opaques }
370            | TypingMode::Borrowck { defining_opaque_types: non_rigid_opaques }
371            | TypingMode::PostBorrowckAnalysis { defined_opaque_types: non_rigid_opaques } => {
372                !def_id.as_local().is_some_and(|def_id| non_rigid_opaques.contains(&def_id))
373            }
374        }
375    }
376}
377
378fn response_no_constraints_raw<I: Interner>(
379    cx: I,
380    max_universe: ty::UniverseIndex,
381    variables: I::CanonicalVarKinds,
382    certainty: Certainty,
383) -> CanonicalResponse<I> {
384    ty::Canonical {
385        max_universe,
386        variables,
387        value: Response {
388            var_values: ty::CanonicalVarValues::make_identity(cx, variables),
389            // FIXME: maybe we should store the "no response" version in cx, like
390            // we do for cx.types and stuff.
391            external_constraints: cx.mk_external_constraints(ExternalConstraintsData::default()),
392            certainty,
393        },
394    }
395}
396
397/// The result of evaluating a goal.
398pub struct GoalEvaluation<I: Interner> {
399    /// The goal we've evaluated. This is the input goal, but potentially with its
400    /// inference variables resolved. This never applies any inference constraints
401    /// from evaluating the goal.
402    ///
403    /// We rely on this to check whether root goals in HIR typeck had an unresolved
404    /// type inference variable in the input. We must not resolve this after evaluating
405    /// the goal as even if the inference variable has been resolved by evaluating the
406    /// goal itself, this goal may still end up failing due to region uniquification
407    /// later on.
408    ///
409    /// This is used as a minor optimization to avoid re-resolving inference variables
410    /// when reevaluating ambiguous goals. E.g. if we've got a goal `?x: Trait` with `?x`
411    /// already being constrained to `Vec<?y>`, then the first evaluation resolves it to
412    /// `Vec<?y>: Trait`. If this goal is still ambiguous and we later resolve `?y` to `u32`,
413    /// then reevaluating this goal now only needs to resolve `?y` while it would otherwise
414    /// have to resolve both `?x` and `?y`,
415    pub goal: Goal<I, I::Predicate>,
416    pub certainty: Certainty,
417    pub has_changed: HasChanged,
418    /// If the [`Certainty`] was `Maybe`, then keep track of whether the goal has changed
419    /// before rerunning it.
420    pub stalled_on: Option<GoalStalledOn<I>>,
421}
422
423/// The conditions that must change for a goal to warrant
424#[derive_where(Clone, Debug; I: Interner)]
425pub struct GoalStalledOn<I: Interner> {
426    pub num_opaques: usize,
427    pub stalled_vars: Vec<I::GenericArg>,
428    /// The cause that will be returned on subsequent evaluations if this goal remains stalled.
429    pub stalled_cause: MaybeCause,
430}