]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/solve/mod.rs
solver comments + remove `TyCtxt::evaluate_goal`
[rust.git] / compiler / rustc_trait_selection / src / solve / mod.rs
1 //! The new trait solver, currently still WIP.
2 //!
3 //! As a user of the trait system, you can use `TyCtxt::evaluate_goal` to
4 //! interact with this solver.
5 //!
6 //! For a high-level overview of how this solver works, check out the relevant
7 //! section of the rustc-dev-guide.
8 //!
9 //! FIXME(@lcnr): Write that section. If you read this before then ask me
10 //! about it on zulip.
11
12 // FIXME: Instead of using `infcx.canonicalize_query` we have to add a new routine which
13 // preserves universes and creates a unique var (in the highest universe) for each
14 // appearance of a region.
15
16 // FIXME: `CanonicalVarValues` should be interned and `Copy`.
17
18 // FIXME: uses of `infcx.at` need to enable deferred projection equality once that's implemented.
19
20 use std::mem;
21
22 use rustc_hir::def_id::DefId;
23 use rustc_infer::infer::canonical::{Canonical, CanonicalVarKind, CanonicalVarValues};
24 use rustc_infer::infer::canonical::{OriginalQueryValues, QueryRegionConstraints, QueryResponse};
25 use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
26 use rustc_infer::traits::query::NoSolution;
27 use rustc_infer::traits::Obligation;
28 use rustc_middle::infer::canonical::Certainty as OldCertainty;
29 use rustc_middle::ty::{self, Ty, TyCtxt};
30 use rustc_middle::ty::{
31     CoercePredicate, RegionOutlivesPredicate, SubtypePredicate, ToPredicate, TypeOutlivesPredicate,
32 };
33 use rustc_span::DUMMY_SP;
34
35 use crate::traits::ObligationCause;
36
37 mod assembly;
38 mod fulfill;
39 mod infcx_ext;
40 mod project_goals;
41 mod search_graph;
42 mod trait_goals;
43
44 pub use fulfill::FulfillmentCtxt;
45
46 /// A goal is a statement, i.e. `predicate`, we want to prove
47 /// given some assumptions, i.e. `param_env`.
48 ///
49 /// Most of the time the `param_env` contains the `where`-bounds of the function
50 /// we're currently typechecking while the `predicate` is some trait bound.
51 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, TypeFoldable, TypeVisitable)]
52 pub struct Goal<'tcx, P> {
53     param_env: ty::ParamEnv<'tcx>,
54     predicate: P,
55 }
56
57 impl<'tcx, P> Goal<'tcx, P> {
58     pub fn new(
59         tcx: TyCtxt<'tcx>,
60         param_env: ty::ParamEnv<'tcx>,
61         predicate: impl ToPredicate<'tcx, P>,
62     ) -> Goal<'tcx, P> {
63         Goal { param_env, predicate: predicate.to_predicate(tcx) }
64     }
65
66     /// Updates the goal to one with a different `predicate` but the same `param_env`.
67     fn with<Q>(self, tcx: TyCtxt<'tcx>, predicate: impl ToPredicate<'tcx, Q>) -> Goal<'tcx, Q> {
68         Goal { param_env: self.param_env, predicate: predicate.to_predicate(tcx) }
69     }
70 }
71
72 impl<'tcx, P> From<Obligation<'tcx, P>> for Goal<'tcx, P> {
73     fn from(obligation: Obligation<'tcx, P>) -> Goal<'tcx, P> {
74         Goal { param_env: obligation.param_env, predicate: obligation.predicate }
75     }
76 }
77
78 #[derive(Debug, PartialEq, Eq, Clone, Hash, TypeFoldable, TypeVisitable)]
79 pub struct Response<'tcx> {
80     pub var_values: CanonicalVarValues<'tcx>,
81     /// Additional constraints returned by this query.
82     pub external_constraints: ExternalConstraints<'tcx>,
83     pub certainty: Certainty,
84 }
85
86 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, TypeFoldable, TypeVisitable)]
87 pub enum Certainty {
88     Yes,
89     Maybe(MaybeCause),
90 }
91
92 impl Certainty {
93     pub const AMBIGUOUS: Certainty = Certainty::Maybe(MaybeCause::Ambiguity);
94
95     /// When proving multiple goals using **AND**, e.g. nested obligations for an impl,
96     /// use this function to unify the certainty of these goals
97     pub fn unify_and(self, other: Certainty) -> Certainty {
98         match (self, other) {
99             (Certainty::Yes, Certainty::Yes) => Certainty::Yes,
100             (Certainty::Yes, Certainty::Maybe(_)) => other,
101             (Certainty::Maybe(_), Certainty::Yes) => self,
102             (Certainty::Maybe(MaybeCause::Overflow), Certainty::Maybe(MaybeCause::Overflow)) => {
103                 Certainty::Maybe(MaybeCause::Overflow)
104             }
105             // If at least one of the goals is ambiguous, hide the overflow as the ambiguous goal
106             // may still result in failure.
107             (Certainty::Maybe(MaybeCause::Ambiguity), Certainty::Maybe(_))
108             | (Certainty::Maybe(_), Certainty::Maybe(MaybeCause::Ambiguity)) => {
109                 Certainty::Maybe(MaybeCause::Ambiguity)
110             }
111         }
112     }
113 }
114
115 /// Why we failed to evaluate a goal.
116 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, TypeFoldable, TypeVisitable)]
117 pub enum MaybeCause {
118     /// We failed due to ambiguity. This ambiguity can either
119     /// be a true ambiguity, i.e. there are multiple different answers,
120     /// or we hit a case where we just don't bother, e.g. `?x: Trait` goals.
121     Ambiguity,
122     /// We gave up due to an overflow, most often by hitting the recursion limit.
123     Overflow,
124 }
125
126 /// Additional constraints returned on success.
127 #[derive(Debug, PartialEq, Eq, Clone, Hash, TypeFoldable, TypeVisitable, Default)]
128 pub struct ExternalConstraints<'tcx> {
129     // FIXME: implement this.
130     regions: (),
131     opaque_types: Vec<(Ty<'tcx>, Ty<'tcx>)>,
132 }
133
134 type CanonicalGoal<'tcx, T = ty::Predicate<'tcx>> = Canonical<'tcx, Goal<'tcx, T>>;
135 type CanonicalResponse<'tcx> = Canonical<'tcx, Response<'tcx>>;
136 /// The result of evaluating a canonical query.
137 ///
138 /// FIXME: We use a different type than the existing canonical queries. This is because
139 /// we need to add a `Certainty` for `overflow` and may want to restructure this code without
140 /// having to worry about changes to currently used code. Once we've made progress on this
141 /// solver, merge the two responses again.
142 pub type QueryResult<'tcx> = Result<CanonicalResponse<'tcx>, NoSolution>;
143
144 pub trait InferCtxtEvalExt<'tcx> {
145     /// Evaluates a goal from **outside** of the trait solver.
146     ///
147     /// Using this while inside of the solver is wrong as it uses a new
148     /// search graph which would break cycle detection.
149     fn evaluate_root_goal(
150         &self,
151         goal: Goal<'tcx, ty::Predicate<'tcx>>,
152     ) -> Result<(bool, Certainty), NoSolution>;
153 }
154
155 impl<'tcx> InferCtxtEvalExt<'tcx> for InferCtxt<'tcx> {
156     fn evaluate_root_goal(
157         &self,
158         goal: Goal<'tcx, ty::Predicate<'tcx>>,
159     ) -> Result<(bool, Certainty), NoSolution> {
160         let mut search_graph = search_graph::SearchGraph::new(self.tcx);
161
162         let result = EvalCtxt {
163             search_graph: &mut search_graph,
164             infcx: self,
165             var_values: CanonicalVarValues::dummy(),
166         }
167         .evaluate_goal(goal);
168
169         assert!(search_graph.is_empty());
170         result
171     }
172 }
173
174 struct EvalCtxt<'a, 'tcx> {
175     infcx: &'a InferCtxt<'tcx>,
176     var_values: CanonicalVarValues<'tcx>,
177
178     search_graph: &'a mut search_graph::SearchGraph<'tcx>,
179 }
180
181 impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
182     fn tcx(&self) -> TyCtxt<'tcx> {
183         self.infcx.tcx
184     }
185
186     /// The entry point of the solver.
187     ///
188     /// This function deals with (coinductive) cycles, overflow, and caching
189     /// and then calls [`EvalCtxt::compute_goal`] which contains the actual
190     /// logic of the solver.
191     ///
192     /// Instead of calling this function directly, use either [EvalCtxt::evaluate_goal]
193     /// if you're inside of the solver or [InferCtxtEvalExt::evaluate_root_goal] if you're
194     /// outside of it.
195     #[instrument(level = "debug", skip(tcx, search_graph), ret)]
196     fn evaluate_canonical_goal(
197         tcx: TyCtxt<'tcx>,
198         search_graph: &'a mut search_graph::SearchGraph<'tcx>,
199         canonical_goal: CanonicalGoal<'tcx>,
200     ) -> QueryResult<'tcx> {
201         match search_graph.try_push_stack(tcx, canonical_goal) {
202             Ok(()) => {}
203             // Our goal is already on the stack, eager return.
204             Err(response) => return response,
205         }
206
207         // We may have to repeatedly recompute the goal in case of coinductive cycles,
208         // check out the `cache` module for more information.
209         //
210         // FIXME: Similar to `evaluate_all`, this has to check for overflow.
211         loop {
212             let (ref infcx, goal, var_values) =
213                 tcx.infer_ctxt().build_with_canonical(DUMMY_SP, &canonical_goal);
214             let mut ecx = EvalCtxt { infcx, var_values, search_graph };
215             let result = ecx.compute_goal(goal);
216
217             // FIXME: `Response` should be `Copy`
218             if search_graph.try_finalize_goal(tcx, canonical_goal, result.clone()) {
219                 return result;
220             }
221         }
222     }
223
224     fn make_canonical_response(&self, certainty: Certainty) -> QueryResult<'tcx> {
225         let external_constraints = take_external_constraints(self.infcx)?;
226
227         Ok(self.infcx.canonicalize_response(Response {
228             var_values: self.var_values.clone(),
229             external_constraints,
230             certainty,
231         }))
232     }
233
234     /// Recursively evaluates `goal`, returning whether any inference vars have
235     /// been constrained and the certainty of the result.
236     fn evaluate_goal(
237         &mut self,
238         goal: Goal<'tcx, ty::Predicate<'tcx>>,
239     ) -> Result<(bool, Certainty), NoSolution> {
240         let mut orig_values = OriginalQueryValues::default();
241         let canonical_goal = self.infcx.canonicalize_query(goal, &mut orig_values);
242         let canonical_response =
243             EvalCtxt::evaluate_canonical_goal(self.tcx(), self.search_graph, canonical_goal)?;
244         Ok((
245             !canonical_response.value.var_values.is_identity(),
246             instantiate_canonical_query_response(self.infcx, &orig_values, canonical_response),
247         ))
248     }
249
250     fn compute_goal(&mut self, goal: Goal<'tcx, ty::Predicate<'tcx>>) -> QueryResult<'tcx> {
251         let Goal { param_env, predicate } = goal;
252         let kind = predicate.kind();
253         if let Some(kind) = kind.no_bound_vars() {
254             match kind {
255                 ty::PredicateKind::Clause(ty::Clause::Trait(predicate)) => {
256                     self.compute_trait_goal(Goal { param_env, predicate })
257                 }
258                 ty::PredicateKind::Clause(ty::Clause::Projection(predicate)) => {
259                     self.compute_projection_goal(Goal { param_env, predicate })
260                 }
261                 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(predicate)) => {
262                     self.compute_type_outlives_goal(Goal { param_env, predicate })
263                 }
264                 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(predicate)) => {
265                     self.compute_region_outlives_goal(Goal { param_env, predicate })
266                 }
267                 ty::PredicateKind::Subtype(predicate) => {
268                     self.compute_subtype_goal(Goal { param_env, predicate })
269                 }
270                 ty::PredicateKind::Coerce(predicate) => {
271                     self.compute_coerce_goal(Goal { param_env, predicate })
272                 }
273                 ty::PredicateKind::ClosureKind(def_id, substs, kind) => self
274                     .compute_closure_kind_goal(Goal {
275                         param_env,
276                         predicate: (def_id, substs, kind),
277                     }),
278                 ty::PredicateKind::ObjectSafe(trait_def_id) => {
279                     self.compute_object_safe_goal(trait_def_id)
280                 }
281                 ty::PredicateKind::WellFormed(arg) => {
282                     self.compute_well_formed_goal(Goal { param_env, predicate: arg })
283                 }
284                 ty::PredicateKind::Ambiguous => self.make_canonical_response(Certainty::AMBIGUOUS),
285                 // FIXME: implement these predicates :)
286                 ty::PredicateKind::ConstEvaluatable(_) | ty::PredicateKind::ConstEquate(_, _) => {
287                     self.make_canonical_response(Certainty::Yes)
288                 }
289                 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
290                     bug!("TypeWellFormedFromEnv is only used for Chalk")
291                 }
292             }
293         } else {
294             let kind = self.infcx.replace_bound_vars_with_placeholders(kind);
295             let goal = goal.with(self.tcx(), ty::Binder::dummy(kind));
296             let (_, certainty) = self.evaluate_goal(goal)?;
297             self.make_canonical_response(certainty)
298         }
299     }
300
301     fn compute_type_outlives_goal(
302         &mut self,
303         _goal: Goal<'tcx, TypeOutlivesPredicate<'tcx>>,
304     ) -> QueryResult<'tcx> {
305         self.make_canonical_response(Certainty::Yes)
306     }
307
308     fn compute_region_outlives_goal(
309         &mut self,
310         _goal: Goal<'tcx, RegionOutlivesPredicate<'tcx>>,
311     ) -> QueryResult<'tcx> {
312         self.make_canonical_response(Certainty::Yes)
313     }
314
315     fn compute_coerce_goal(
316         &mut self,
317         goal: Goal<'tcx, CoercePredicate<'tcx>>,
318     ) -> QueryResult<'tcx> {
319         self.compute_subtype_goal(Goal {
320             param_env: goal.param_env,
321             predicate: SubtypePredicate {
322                 a_is_expected: false,
323                 a: goal.predicate.a,
324                 b: goal.predicate.b,
325             },
326         })
327     }
328
329     fn compute_subtype_goal(
330         &mut self,
331         goal: Goal<'tcx, SubtypePredicate<'tcx>>,
332     ) -> QueryResult<'tcx> {
333         if goal.predicate.a.is_ty_var() && goal.predicate.b.is_ty_var() {
334             // FIXME: Do we want to register a subtype relation between these vars?
335             // That won't actually reflect in the query response, so it seems moot.
336             self.make_canonical_response(Certainty::AMBIGUOUS)
337         } else {
338             self.infcx.probe(|_| {
339                 let InferOk { value: (), obligations } = self
340                     .infcx
341                     .at(&ObligationCause::dummy(), goal.param_env)
342                     .sub(goal.predicate.a, goal.predicate.b)?;
343                 self.evaluate_all_and_make_canonical_response(
344                     obligations.into_iter().map(|pred| pred.into()).collect(),
345                 )
346             })
347         }
348     }
349
350     fn compute_closure_kind_goal(
351         &mut self,
352         goal: Goal<'tcx, (DefId, ty::SubstsRef<'tcx>, ty::ClosureKind)>,
353     ) -> QueryResult<'tcx> {
354         let (_, substs, expected_kind) = goal.predicate;
355         let found_kind = substs.as_closure().kind_ty().to_opt_closure_kind();
356
357         let Some(found_kind) = found_kind else {
358             return self.make_canonical_response(Certainty::AMBIGUOUS);
359         };
360         if found_kind.extends(expected_kind) {
361             self.make_canonical_response(Certainty::Yes)
362         } else {
363             Err(NoSolution)
364         }
365     }
366
367     fn compute_object_safe_goal(&mut self, trait_def_id: DefId) -> QueryResult<'tcx> {
368         if self.tcx().is_object_safe(trait_def_id) {
369             self.make_canonical_response(Certainty::Yes)
370         } else {
371             Err(NoSolution)
372         }
373     }
374
375     fn compute_well_formed_goal(
376         &mut self,
377         goal: Goal<'tcx, ty::GenericArg<'tcx>>,
378     ) -> QueryResult<'tcx> {
379         self.infcx.probe(|_| {
380             match crate::traits::wf::unnormalized_obligations(
381                 self.infcx,
382                 goal.param_env,
383                 goal.predicate,
384             ) {
385                 Some(obligations) => self.evaluate_all_and_make_canonical_response(
386                     obligations.into_iter().map(|o| o.into()).collect(),
387                 ),
388                 None => self.make_canonical_response(Certainty::AMBIGUOUS),
389             }
390         })
391     }
392 }
393
394 impl<'tcx> EvalCtxt<'_, 'tcx> {
395     fn evaluate_all(
396         &mut self,
397         mut goals: Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
398     ) -> Result<Certainty, NoSolution> {
399         let mut new_goals = Vec::new();
400         self.repeat_while_none(|this| {
401             let mut has_changed = Err(Certainty::Yes);
402             for goal in goals.drain(..) {
403                 let (changed, certainty) = match this.evaluate_goal(goal) {
404                     Ok(result) => result,
405                     Err(NoSolution) => return Some(Err(NoSolution)),
406                 };
407
408                 if changed {
409                     has_changed = Ok(());
410                 }
411
412                 match certainty {
413                     Certainty::Yes => {}
414                     Certainty::Maybe(_) => {
415                         new_goals.push(goal);
416                         has_changed = has_changed.map_err(|c| c.unify_and(certainty));
417                     }
418                 }
419             }
420
421             match has_changed {
422                 Ok(()) => {
423                     mem::swap(&mut new_goals, &mut goals);
424                     None
425                 }
426                 Err(certainty) => Some(Ok(certainty)),
427             }
428         })
429     }
430
431     fn evaluate_all_and_make_canonical_response(
432         &mut self,
433         goals: Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
434     ) -> QueryResult<'tcx> {
435         self.evaluate_all(goals).and_then(|certainty| self.make_canonical_response(certainty))
436     }
437 }
438
439 #[instrument(level = "debug", skip(infcx), ret)]
440 fn take_external_constraints<'tcx>(
441     infcx: &InferCtxt<'tcx>,
442 ) -> Result<ExternalConstraints<'tcx>, NoSolution> {
443     let region_obligations = infcx.take_registered_region_obligations();
444     let opaque_types = infcx.take_opaque_types_for_query_response();
445     Ok(ExternalConstraints {
446         // FIXME: Now that's definitely wrong :)
447         //
448         // Should also do the leak check here I think
449         regions: drop(region_obligations),
450         opaque_types,
451     })
452 }
453
454 fn instantiate_canonical_query_response<'tcx>(
455     infcx: &InferCtxt<'tcx>,
456     original_values: &OriginalQueryValues<'tcx>,
457     response: CanonicalResponse<'tcx>,
458 ) -> Certainty {
459     let Ok(InferOk { value, obligations }) = infcx
460         .instantiate_query_response_and_region_obligations(
461             &ObligationCause::dummy(),
462             ty::ParamEnv::empty(),
463             original_values,
464             &response.unchecked_map(|resp| QueryResponse {
465                 var_values: resp.var_values,
466                 region_constraints: QueryRegionConstraints::default(),
467                 certainty: match resp.certainty {
468                     Certainty::Yes => OldCertainty::Proven,
469                     Certainty::Maybe(_) => OldCertainty::Ambiguous,
470                 },
471                 opaque_types: resp.external_constraints.opaque_types,
472                 value: resp.certainty,
473             }),
474         ) else { bug!(); };
475     assert!(obligations.is_empty());
476     value
477 }
478
479 pub(super) fn response_no_constraints<'tcx>(
480     tcx: TyCtxt<'tcx>,
481     goal: Canonical<'tcx, impl Sized>,
482     certainty: Certainty,
483 ) -> QueryResult<'tcx> {
484     let var_values = goal
485         .variables
486         .iter()
487         .enumerate()
488         .map(|(i, info)| match info.kind {
489             CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) => {
490                 tcx.mk_ty(ty::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i).into())).into()
491             }
492             CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => {
493                 let br = ty::BoundRegion {
494                     var: ty::BoundVar::from_usize(i),
495                     kind: ty::BrAnon(i as u32, None),
496                 };
497                 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into()
498             }
499             CanonicalVarKind::Const(_, ty) | CanonicalVarKind::PlaceholderConst(_, ty) => tcx
500                 .mk_const(ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from_usize(i)), ty)
501                 .into(),
502         })
503         .collect();
504
505     Ok(Canonical {
506         max_universe: goal.max_universe,
507         variables: goal.variables,
508         value: Response {
509             var_values: CanonicalVarValues { var_values },
510             external_constraints: Default::default(),
511             certainty,
512         },
513     })
514 }