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;
32
33const FIXPOINT_STEP_LIMIT: usize = 8;
43
44#[derive(Debug, Copy, Clone, PartialEq, Eq)]
45enum GoalEvaluationKind {
46 Root,
47 Nested,
48}
49
50#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
53pub enum HasChanged {
54 Yes,
55 No,
56}
57
58fn has_no_inference_or_external_constraints<I: Interner>(
61 response: ty::Canonical<I, Response<I>>,
62) -> bool {
63 let ExternalConstraintsData {
64 ref region_constraints,
65 ref opaque_types,
66 ref normalization_nested_goals,
67 } = *response.value.external_constraints;
68 response.value.var_values.is_identity()
69 && region_constraints.is_empty()
70 && opaque_types.is_empty()
71 && normalization_nested_goals.is_empty()
72}
73
74fn has_only_region_constraints<I: Interner>(response: ty::Canonical<I, Response<I>>) -> bool {
75 let ExternalConstraintsData {
76 region_constraints: _,
77 ref opaque_types,
78 ref normalization_nested_goals,
79 } = *response.value.external_constraints;
80 response.value.var_values.is_identity_modulo_regions()
81 && opaque_types.is_empty()
82 && normalization_nested_goals.is_empty()
83}
84
85impl<'a, D, I> EvalCtxt<'a, D>
86where
87 D: SolverDelegate<Interner = I>,
88 I: Interner,
89{
90 #[instrument(level = "trace", skip(self))]
91 fn compute_type_outlives_goal(
92 &mut self,
93 goal: Goal<I, ty::OutlivesPredicate<I, I::Ty>>,
94 ) -> QueryResult<I> {
95 let ty::OutlivesPredicate(ty, lt) = goal.predicate;
96 self.register_ty_outlives(ty, lt);
97 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
98 }
99
100 #[instrument(level = "trace", skip(self))]
101 fn compute_region_outlives_goal(
102 &mut self,
103 goal: Goal<I, ty::OutlivesPredicate<I, I::Region>>,
104 ) -> QueryResult<I> {
105 let ty::OutlivesPredicate(a, b) = goal.predicate;
106 self.register_region_outlives(a, b);
107 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
108 }
109
110 #[instrument(level = "trace", skip(self))]
111 fn compute_coerce_goal(&mut self, goal: Goal<I, ty::CoercePredicate<I>>) -> QueryResult<I> {
112 self.compute_subtype_goal(Goal {
113 param_env: goal.param_env,
114 predicate: ty::SubtypePredicate {
115 a_is_expected: false,
116 a: goal.predicate.a,
117 b: goal.predicate.b,
118 },
119 })
120 }
121
122 #[instrument(level = "trace", skip(self))]
123 fn compute_subtype_goal(&mut self, goal: Goal<I, ty::SubtypePredicate<I>>) -> QueryResult<I> {
124 if goal.predicate.a.is_ty_var() && goal.predicate.b.is_ty_var() {
125 self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
126 } else {
127 self.sub(goal.param_env, goal.predicate.a, goal.predicate.b)?;
128 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
129 }
130 }
131
132 fn compute_dyn_compatible_goal(&mut self, trait_def_id: I::DefId) -> QueryResult<I> {
133 if self.cx().trait_is_dyn_compatible(trait_def_id) {
134 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
135 } else {
136 Err(NoSolution)
137 }
138 }
139
140 #[instrument(level = "trace", skip(self))]
141 fn compute_well_formed_goal(&mut self, goal: Goal<I, I::Term>) -> QueryResult<I> {
142 match self.well_formed_goals(goal.param_env, goal.predicate) {
143 Some(goals) => {
144 self.add_goals(GoalSource::Misc, goals);
145 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
146 }
147 None => self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS),
148 }
149 }
150
151 fn compute_unstable_feature_goal(
152 &mut self,
153 param_env: <I as Interner>::ParamEnv,
154 symbol: <I as Interner>::Symbol,
155 ) -> QueryResult<I> {
156 if self.may_use_unstable_feature(param_env, symbol) {
157 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
158 } else {
159 self.evaluate_added_goals_and_make_canonical_response(Certainty::Maybe(
160 MaybeCause::Ambiguity,
161 ))
162 }
163 }
164
165 #[instrument(level = "trace", skip(self))]
166 fn compute_const_evaluatable_goal(
167 &mut self,
168 Goal { param_env, predicate: ct }: Goal<I, I::Const>,
169 ) -> QueryResult<I> {
170 match ct.kind() {
171 ty::ConstKind::Unevaluated(uv) => {
172 if let Some(_normalized) = self.evaluate_const(param_env, uv) {
181 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
182 } else {
183 self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
184 }
185 }
186 ty::ConstKind::Infer(_) => {
187 self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
188 }
189 ty::ConstKind::Placeholder(_) | ty::ConstKind::Value(_) | ty::ConstKind::Error(_) => {
190 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
191 }
192 ty::ConstKind::Param(_) | ty::ConstKind::Bound(_, _) | ty::ConstKind::Expr(_) => {
197 panic!("unexpected const kind: {:?}", ct)
198 }
199 }
200 }
201
202 #[instrument(level = "trace", skip(self), ret)]
203 fn compute_const_arg_has_type_goal(
204 &mut self,
205 goal: Goal<I, (I::Const, I::Ty)>,
206 ) -> QueryResult<I> {
207 let (ct, ty) = goal.predicate;
208 let ct = self.structurally_normalize_const(goal.param_env, ct)?;
209
210 let ct_ty = match ct.kind() {
211 ty::ConstKind::Infer(_) => {
212 return self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS);
213 }
214 ty::ConstKind::Error(_) => {
215 return self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes);
216 }
217 ty::ConstKind::Unevaluated(uv) => {
218 self.cx().type_of(uv.def).instantiate(self.cx(), uv.args)
219 }
220 ty::ConstKind::Expr(_) => unimplemented!(
221 "`feature(generic_const_exprs)` is not supported in the new trait solver"
222 ),
223 ty::ConstKind::Param(_) => {
224 unreachable!("`ConstKind::Param` should have been canonicalized to `Placeholder`")
225 }
226 ty::ConstKind::Bound(_, _) => panic!("escaping bound vars in {:?}", ct),
227 ty::ConstKind::Value(cv) => cv.ty(),
228 ty::ConstKind::Placeholder(placeholder) => {
229 placeholder.find_const_ty_from_env(goal.param_env)
230 }
231 };
232
233 self.eq(goal.param_env, ct_ty, ty)?;
234 self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
235 }
236}
237
238impl<D, I> EvalCtxt<'_, D>
239where
240 D: SolverDelegate<Interner = I>,
241 I: Interner,
242{
243 #[instrument(level = "trace", skip(self), ret)]
247 fn try_merge_responses(
248 &mut self,
249 responses: &[CanonicalResponse<I>],
250 ) -> Option<CanonicalResponse<I>> {
251 if responses.is_empty() {
252 return None;
253 }
254
255 let one = responses[0];
256 if responses[1..].iter().all(|&resp| resp == one) {
257 return Some(one);
258 }
259
260 responses
261 .iter()
262 .find(|response| {
263 response.value.certainty == Certainty::Yes
264 && has_no_inference_or_external_constraints(**response)
265 })
266 .copied()
267 }
268
269 fn bail_with_ambiguity(&mut self, responses: &[CanonicalResponse<I>]) -> CanonicalResponse<I> {
270 debug_assert!(responses.len() > 1);
271 let maybe_cause = responses.iter().fold(MaybeCause::Ambiguity, |maybe_cause, response| {
272 let candidate = match response.value.certainty {
276 Certainty::Yes => MaybeCause::Ambiguity,
277 Certainty::Maybe(candidate) => candidate,
278 };
279 maybe_cause.or(candidate)
280 });
281 self.make_ambiguous_response_no_constraints(maybe_cause)
282 }
283
284 #[instrument(level = "trace", skip(self), ret)]
286 fn flounder(&mut self, responses: &[CanonicalResponse<I>]) -> QueryResult<I> {
287 if responses.is_empty() {
288 return Err(NoSolution);
289 } else {
290 Ok(self.bail_with_ambiguity(responses))
291 }
292 }
293
294 #[instrument(level = "trace", skip(self, param_env), ret)]
300 fn structurally_normalize_ty(
301 &mut self,
302 param_env: I::ParamEnv,
303 ty: I::Ty,
304 ) -> Result<I::Ty, NoSolution> {
305 self.structurally_normalize_term(param_env, ty.into()).map(|term| term.expect_ty())
306 }
307
308 #[instrument(level = "trace", skip(self, param_env), ret)]
315 fn structurally_normalize_const(
316 &mut self,
317 param_env: I::ParamEnv,
318 ct: I::Const,
319 ) -> Result<I::Const, NoSolution> {
320 self.structurally_normalize_term(param_env, ct.into()).map(|term| term.expect_const())
321 }
322
323 fn structurally_normalize_term(
328 &mut self,
329 param_env: I::ParamEnv,
330 term: I::Term,
331 ) -> Result<I::Term, NoSolution> {
332 if let Some(_) = term.to_alias_term() {
333 let normalized_term = self.next_term_infer_of_kind(term);
334 let alias_relate_goal = Goal::new(
335 self.cx(),
336 param_env,
337 ty::PredicateKind::AliasRelate(
338 term,
339 normalized_term,
340 ty::AliasRelationDirection::Equate,
341 ),
342 );
343 self.add_goal(GoalSource::TypeRelating, alias_relate_goal);
346 self.try_evaluate_added_goals()?;
347 Ok(self.resolve_vars_if_possible(normalized_term))
348 } else {
349 Ok(term)
350 }
351 }
352
353 fn opaque_type_is_rigid(&self, def_id: I::DefId) -> bool {
354 match self.typing_mode() {
355 TypingMode::Coherence | TypingMode::PostAnalysis => false,
357 TypingMode::Analysis { defining_opaque_types_and_generators: non_rigid_opaques }
360 | TypingMode::Borrowck { defining_opaque_types: non_rigid_opaques }
361 | TypingMode::PostBorrowckAnalysis { defined_opaque_types: non_rigid_opaques } => {
362 !def_id.as_local().is_some_and(|def_id| non_rigid_opaques.contains(&def_id))
363 }
364 }
365 }
366}
367
368fn response_no_constraints_raw<I: Interner>(
369 cx: I,
370 max_universe: ty::UniverseIndex,
371 variables: I::CanonicalVarKinds,
372 certainty: Certainty,
373) -> CanonicalResponse<I> {
374 ty::Canonical {
375 max_universe,
376 variables,
377 value: Response {
378 var_values: ty::CanonicalVarValues::make_identity(cx, variables),
379 external_constraints: cx.mk_external_constraints(ExternalConstraintsData::default()),
382 certainty,
383 },
384 }
385}
386
387pub struct GoalEvaluation<I: Interner> {
389 pub goal: Goal<I, I::Predicate>,
406 pub certainty: Certainty,
407 pub has_changed: HasChanged,
408 pub stalled_on: Option<GoalStalledOn<I>>,
411}
412
413#[derive_where(Clone, Debug; I: Interner)]
415pub struct GoalStalledOn<I: Interner> {
416 pub num_opaques: usize,
417 pub stalled_vars: Vec<I::GenericArg>,
418 pub stalled_cause: MaybeCause,
420}