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