rustc_next_trait_solver/solve/
mod.rs1mod 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
34const FIXPOINT_STEP_LIMIT: usize = 8;
44
45#[derive(Debug, Copy, Clone, PartialEq, Eq)]
46enum GoalEvaluationKind {
47 Root,
48 Nested,
49}
50
51#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
54pub enum HasChanged {
55 Yes,
56 No,
57}
58
59fn 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::DefId) -> 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 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 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
239impl<D, I> EvalCtxt<'_, D>
240where
241 D: SolverDelegate<Interner = I>,
242 I: Interner,
243{
244 #[instrument(level = "trace", skip(self), ret)]
248 fn try_merge_candidates(
249 &mut self,
250 candidates: &[Candidate<I>],
251 ) -> Option<CanonicalResponse<I>> {
252 if candidates.is_empty() {
253 return None;
254 }
255
256 let one: CanonicalResponse<I> = candidates[0].result;
257 if candidates[1..].iter().all(|candidate| candidate.result == one) {
258 return Some(one);
259 }
260
261 candidates
262 .iter()
263 .find(|candidate| {
264 candidate.result.value.certainty == Certainty::Yes
265 && has_no_inference_or_external_constraints(candidate.result)
266 })
267 .map(|candidate| candidate.result)
268 }
269
270 fn bail_with_ambiguity(&mut self, candidates: &[Candidate<I>]) -> CanonicalResponse<I> {
271 debug_assert!(candidates.len() > 1);
272 let maybe_cause =
273 candidates.iter().fold(MaybeCause::Ambiguity, |maybe_cause, candidates| {
274 let candidate = match candidates.result.value.certainty {
278 Certainty::Yes => MaybeCause::Ambiguity,
279 Certainty::Maybe(candidate) => candidate,
280 };
281 maybe_cause.or(candidate)
282 });
283 self.make_ambiguous_response_no_constraints(maybe_cause)
284 }
285
286 #[instrument(level = "trace", skip(self), ret)]
288 fn flounder(&mut self, candidates: &[Candidate<I>]) -> QueryResult<I> {
289 if candidates.is_empty() {
290 return Err(NoSolution);
291 } else {
292 Ok(self.bail_with_ambiguity(candidates))
293 }
294 }
295
296 #[instrument(level = "trace", skip(self, param_env), ret)]
302 fn structurally_normalize_ty(
303 &mut self,
304 param_env: I::ParamEnv,
305 ty: I::Ty,
306 ) -> Result<I::Ty, NoSolution> {
307 self.structurally_normalize_term(param_env, ty.into()).map(|term| term.expect_ty())
308 }
309
310 #[instrument(level = "trace", skip(self, param_env), ret)]
317 fn structurally_normalize_const(
318 &mut self,
319 param_env: I::ParamEnv,
320 ct: I::Const,
321 ) -> Result<I::Const, NoSolution> {
322 self.structurally_normalize_term(param_env, ct.into()).map(|term| term.expect_const())
323 }
324
325 fn structurally_normalize_term(
330 &mut self,
331 param_env: I::ParamEnv,
332 term: I::Term,
333 ) -> Result<I::Term, NoSolution> {
334 if let Some(_) = term.to_alias_term() {
335 let normalized_term = self.next_term_infer_of_kind(term);
336 let alias_relate_goal = Goal::new(
337 self.cx(),
338 param_env,
339 ty::PredicateKind::AliasRelate(
340 term,
341 normalized_term,
342 ty::AliasRelationDirection::Equate,
343 ),
344 );
345 self.add_goal(GoalSource::TypeRelating, alias_relate_goal);
348 self.try_evaluate_added_goals()?;
349 Ok(self.resolve_vars_if_possible(normalized_term))
350 } else {
351 Ok(term)
352 }
353 }
354
355 fn opaque_type_is_rigid(&self, def_id: I::DefId) -> bool {
356 match self.typing_mode() {
357 TypingMode::Coherence | TypingMode::PostAnalysis => false,
359 TypingMode::Analysis { defining_opaque_types_and_generators: non_rigid_opaques }
362 | TypingMode::Borrowck { defining_opaque_types: non_rigid_opaques }
363 | TypingMode::PostBorrowckAnalysis { defined_opaque_types: non_rigid_opaques } => {
364 !def_id.as_local().is_some_and(|def_id| non_rigid_opaques.contains(&def_id))
365 }
366 }
367 }
368}
369
370fn response_no_constraints_raw<I: Interner>(
371 cx: I,
372 max_universe: ty::UniverseIndex,
373 variables: I::CanonicalVarKinds,
374 certainty: Certainty,
375) -> CanonicalResponse<I> {
376 ty::Canonical {
377 max_universe,
378 variables,
379 value: Response {
380 var_values: ty::CanonicalVarValues::make_identity(cx, variables),
381 external_constraints: cx.mk_external_constraints(ExternalConstraintsData::default()),
384 certainty,
385 },
386 }
387}
388
389pub struct GoalEvaluation<I: Interner> {
391 pub goal: Goal<I, I::Predicate>,
408 pub certainty: Certainty,
409 pub has_changed: HasChanged,
410 pub stalled_on: Option<GoalStalledOn<I>>,
413}
414
415#[derive_where(Clone, Debug; I: Interner)]
417pub struct GoalStalledOn<I: Interner> {
418 pub num_opaques: usize,
419 pub stalled_vars: Vec<I::GenericArg>,
420 pub stalled_cause: MaybeCause,
422}