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, TyVid, 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        match (goal.predicate.a.kind(), goal.predicate.b.kind()) {
123            (ty::Infer(ty::TyVar(a_vid)), ty::Infer(ty::TyVar(b_vid))) => {
124                self.sub_unify_ty_vids_raw(a_vid, b_vid);
125                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
126            }
127            _ => {
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
134    fn compute_dyn_compatible_goal(&mut self, trait_def_id: I::TraitId) -> QueryResult<I> {
135        if self.cx().trait_is_dyn_compatible(trait_def_id) {
136            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
137        } else {
138            Err(NoSolution)
139        }
140    }
141
142    #[instrument(level = "trace", skip(self))]
143    fn compute_well_formed_goal(&mut self, goal: Goal<I, I::Term>) -> QueryResult<I> {
144        match self.well_formed_goals(goal.param_env, goal.predicate) {
145            Some(goals) => {
146                self.add_goals(GoalSource::Misc, goals);
147                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
148            }
149            None => self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS),
150        }
151    }
152
153    fn compute_unstable_feature_goal(
154        &mut self,
155        param_env: <I as Interner>::ParamEnv,
156        symbol: <I as Interner>::Symbol,
157    ) -> QueryResult<I> {
158        if self.may_use_unstable_feature(param_env, symbol) {
159            self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
160        } else {
161            self.evaluate_added_goals_and_make_canonical_response(Certainty::Maybe(
162                MaybeCause::Ambiguity,
163            ))
164        }
165    }
166
167    #[instrument(level = "trace", skip(self))]
168    fn compute_const_evaluatable_goal(
169        &mut self,
170        Goal { param_env, predicate: ct }: Goal<I, I::Const>,
171    ) -> QueryResult<I> {
172        match ct.kind() {
173            ty::ConstKind::Unevaluated(uv) => {
174                // We never return `NoSolution` here as `evaluate_const` emits an
175                // error itself when failing to evaluate, so emitting an additional fulfillment
176                // error in that case is unnecessary noise. This may change in the future once
177                // evaluation failures are allowed to impact selection, e.g. generic const
178                // expressions in impl headers or `where`-clauses.
179
180                // FIXME(generic_const_exprs): Implement handling for generic
181                // const expressions here.
182                if let Some(_normalized) = self.evaluate_const(param_env, uv) {
183                    self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
184                } else {
185                    self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
186                }
187            }
188            ty::ConstKind::Infer(_) => {
189                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
190            }
191            ty::ConstKind::Placeholder(_) | ty::ConstKind::Value(_) | ty::ConstKind::Error(_) => {
192                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
193            }
194            // We can freely ICE here as:
195            // - `Param` gets replaced with a placeholder during canonicalization
196            // - `Bound` cannot exist as we don't have a binder around the self Type
197            // - `Expr` is part of `feature(generic_const_exprs)` and is not implemented yet
198            ty::ConstKind::Param(_) | ty::ConstKind::Bound(_, _) | ty::ConstKind::Expr(_) => {
199                panic!("unexpected const kind: {:?}", ct)
200            }
201        }
202    }
203
204    #[instrument(level = "trace", skip(self), ret)]
205    fn compute_const_arg_has_type_goal(
206        &mut self,
207        goal: Goal<I, (I::Const, I::Ty)>,
208    ) -> QueryResult<I> {
209        let (ct, ty) = goal.predicate;
210        let ct = self.structurally_normalize_const(goal.param_env, ct)?;
211
212        let ct_ty = match ct.kind() {
213            ty::ConstKind::Infer(_) => {
214                return self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS);
215            }
216            ty::ConstKind::Error(_) => {
217                return self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes);
218            }
219            ty::ConstKind::Unevaluated(uv) => {
220                self.cx().type_of(uv.def).instantiate(self.cx(), uv.args)
221            }
222            ty::ConstKind::Expr(_) => unimplemented!(
223                "`feature(generic_const_exprs)` is not supported in the new trait solver"
224            ),
225            ty::ConstKind::Param(_) => {
226                unreachable!("`ConstKind::Param` should have been canonicalized to `Placeholder`")
227            }
228            ty::ConstKind::Bound(_, _) => panic!("escaping bound vars in {:?}", ct),
229            ty::ConstKind::Value(cv) => cv.ty(),
230            ty::ConstKind::Placeholder(placeholder) => {
231                placeholder.find_const_ty_from_env(goal.param_env)
232            }
233        };
234
235        self.eq(goal.param_env, ct_ty, ty)?;
236        self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
237    }
238}
239
240#[derive(Debug)]
241enum MergeCandidateInfo {
242    AlwaysApplicable(usize),
243    EqualResponse,
244}
245
246impl<D, I> EvalCtxt<'_, D>
247where
248    D: SolverDelegate<Interner = I>,
249    I: Interner,
250{
251    /// Try to merge multiple possible ways to prove a goal, if that is not possible returns `None`.
252    ///
253    /// In this case we tend to flounder and return ambiguity by calling `[EvalCtxt::flounder]`.
254    #[instrument(level = "trace", skip(self), ret)]
255    fn try_merge_candidates(
256        &mut self,
257        candidates: &[Candidate<I>],
258    ) -> Option<(CanonicalResponse<I>, MergeCandidateInfo)> {
259        if candidates.is_empty() {
260            return None;
261        }
262
263        let always_applicable = candidates.iter().enumerate().find(|(_, candidate)| {
264            candidate.result.value.certainty == Certainty::Yes
265                && has_no_inference_or_external_constraints(candidate.result)
266        });
267        if let Some((i, c)) = always_applicable {
268            return Some((c.result, MergeCandidateInfo::AlwaysApplicable(i)));
269        }
270
271        let one: CanonicalResponse<I> = candidates[0].result;
272        if candidates[1..].iter().all(|candidate| candidate.result == one) {
273            return Some((one, MergeCandidateInfo::EqualResponse));
274        }
275
276        None
277    }
278
279    fn bail_with_ambiguity(&mut self, candidates: &[Candidate<I>]) -> CanonicalResponse<I> {
280        debug_assert!(candidates.len() > 1);
281        let maybe_cause =
282            candidates.iter().fold(MaybeCause::Ambiguity, |maybe_cause, candidates| {
283                // Pull down the certainty of `Certainty::Yes` to ambiguity when combining
284                // these responses, b/c we're combining more than one response and this we
285                // don't know which one applies.
286                let candidate = match candidates.result.value.certainty {
287                    Certainty::Yes => MaybeCause::Ambiguity,
288                    Certainty::Maybe(candidate) => candidate,
289                };
290                maybe_cause.or(candidate)
291            });
292        self.make_ambiguous_response_no_constraints(maybe_cause)
293    }
294
295    /// If we fail to merge responses we flounder and return overflow or ambiguity.
296    #[instrument(level = "trace", skip(self), ret)]
297    fn flounder(&mut self, candidates: &[Candidate<I>]) -> QueryResult<I> {
298        if candidates.is_empty() {
299            return Err(NoSolution);
300        } else {
301            Ok(self.bail_with_ambiguity(candidates))
302        }
303    }
304
305    /// Normalize a type for when it is structurally matched on.
306    ///
307    /// This function is necessary in nearly all cases before matching on a type.
308    /// Not doing so is likely to be incomplete and therefore unsound during
309    /// coherence.
310    #[instrument(level = "trace", skip(self, param_env), ret)]
311    fn structurally_normalize_ty(
312        &mut self,
313        param_env: I::ParamEnv,
314        ty: I::Ty,
315    ) -> Result<I::Ty, NoSolution> {
316        self.structurally_normalize_term(param_env, ty.into()).map(|term| term.expect_ty())
317    }
318
319    /// Normalize a const for when it is structurally matched on, or more likely
320    /// when it needs `.try_to_*` called on it (e.g. to turn it into a usize).
321    ///
322    /// This function is necessary in nearly all cases before matching on a const.
323    /// Not doing so is likely to be incomplete and therefore unsound during
324    /// coherence.
325    #[instrument(level = "trace", skip(self, param_env), ret)]
326    fn structurally_normalize_const(
327        &mut self,
328        param_env: I::ParamEnv,
329        ct: I::Const,
330    ) -> Result<I::Const, NoSolution> {
331        self.structurally_normalize_term(param_env, ct.into()).map(|term| term.expect_const())
332    }
333
334    /// Normalize a term for when it is structurally matched on.
335    ///
336    /// This function is necessary in nearly all cases before matching on a ty/const.
337    /// Not doing so is likely to be incomplete and therefore unsound during coherence.
338    fn structurally_normalize_term(
339        &mut self,
340        param_env: I::ParamEnv,
341        term: I::Term,
342    ) -> Result<I::Term, NoSolution> {
343        if let Some(_) = term.to_alias_term() {
344            let normalized_term = self.next_term_infer_of_kind(term);
345            let alias_relate_goal = Goal::new(
346                self.cx(),
347                param_env,
348                ty::PredicateKind::AliasRelate(
349                    term,
350                    normalized_term,
351                    ty::AliasRelationDirection::Equate,
352                ),
353            );
354            // We normalize the self type to be able to relate it with
355            // types from candidates.
356            self.add_goal(GoalSource::TypeRelating, alias_relate_goal);
357            self.try_evaluate_added_goals()?;
358            Ok(self.resolve_vars_if_possible(normalized_term))
359        } else {
360            Ok(term)
361        }
362    }
363
364    fn opaque_type_is_rigid(&self, def_id: I::DefId) -> bool {
365        match self.typing_mode() {
366            // Opaques are never rigid outside of analysis mode.
367            TypingMode::Coherence | TypingMode::PostAnalysis => false,
368            // During analysis, opaques are rigid unless they may be defined by
369            // the current body.
370            TypingMode::Analysis { defining_opaque_types_and_generators: non_rigid_opaques }
371            | TypingMode::Borrowck { defining_opaque_types: non_rigid_opaques }
372            | TypingMode::PostBorrowckAnalysis { defined_opaque_types: non_rigid_opaques } => {
373                !def_id.as_local().is_some_and(|def_id| non_rigid_opaques.contains(&def_id))
374            }
375        }
376    }
377}
378
379fn response_no_constraints_raw<I: Interner>(
380    cx: I,
381    max_universe: ty::UniverseIndex,
382    variables: I::CanonicalVarKinds,
383    certainty: Certainty,
384) -> CanonicalResponse<I> {
385    ty::Canonical {
386        max_universe,
387        variables,
388        value: Response {
389            var_values: ty::CanonicalVarValues::make_identity(cx, variables),
390            // FIXME: maybe we should store the "no response" version in cx, like
391            // we do for cx.types and stuff.
392            external_constraints: cx.mk_external_constraints(ExternalConstraintsData::default()),
393            certainty,
394        },
395    }
396}
397
398/// The result of evaluating a goal.
399pub struct GoalEvaluation<I: Interner> {
400    /// The goal we've evaluated. This is the input goal, but potentially with its
401    /// inference variables resolved. This never applies any inference constraints
402    /// from evaluating the goal.
403    ///
404    /// We rely on this to check whether root goals in HIR typeck had an unresolved
405    /// type inference variable in the input. We must not resolve this after evaluating
406    /// the goal as even if the inference variable has been resolved by evaluating the
407    /// goal itself, this goal may still end up failing due to region uniquification
408    /// later on.
409    ///
410    /// This is used as a minor optimization to avoid re-resolving inference variables
411    /// when reevaluating ambiguous goals. E.g. if we've got a goal `?x: Trait` with `?x`
412    /// already being constrained to `Vec<?y>`, then the first evaluation resolves it to
413    /// `Vec<?y>: Trait`. If this goal is still ambiguous and we later resolve `?y` to `u32`,
414    /// then reevaluating this goal now only needs to resolve `?y` while it would otherwise
415    /// have to resolve both `?x` and `?y`,
416    pub goal: Goal<I, I::Predicate>,
417    pub certainty: Certainty,
418    pub has_changed: HasChanged,
419    /// If the [`Certainty`] was `Maybe`, then keep track of whether the goal has changed
420    /// before rerunning it.
421    pub stalled_on: Option<GoalStalledOn<I>>,
422}
423
424/// The conditions that must change for a goal to warrant
425#[derive_where(Clone, Debug; I: Interner)]
426pub struct GoalStalledOn<I: Interner> {
427    pub num_opaques: usize,
428    pub stalled_vars: Vec<I::GenericArg>,
429    pub sub_roots: Vec<TyVid>,
430    /// The cause that will be returned on subsequent evaluations if this goal remains stalled.
431    pub stalled_cause: MaybeCause,
432}