1 //! Code shared by trait and projection goals for candidate assembly.
3 use super::infcx_ext::InferCtxtExt;
4 use super::{CanonicalResponse, Certainty, EvalCtxt, Goal};
5 use rustc_hir::def_id::DefId;
6 use rustc_infer::traits::query::NoSolution;
7 use rustc_middle::ty::TypeFoldable;
8 use rustc_middle::ty::{self, Ty, TyCtxt};
11 /// A candidate is a possible way to prove a goal.
13 /// It consists of both the `source`, which describes how that goal would be proven,
14 /// and the `result` when using the given `source`.
15 #[derive(Debug, Clone)]
16 pub(super) struct Candidate<'tcx> {
17 pub(super) source: CandidateSource,
18 pub(super) result: CanonicalResponse<'tcx>,
21 /// Possible ways the given goal can be proven.
22 #[derive(Debug, Clone, Copy)]
23 pub(super) enum CandidateSource {
24 /// A user written impl.
30 /// let x: Vec<u32> = Vec::new();
31 /// // This uses the impl from the standard library to prove `Vec<T>: Clone`.
32 /// let y = x.clone();
36 /// A builtin impl generated by the compiler. When adding a new special
37 /// trait, try to use actual impls whenever possible. Builtin impls should
38 /// only be used in cases where the impl cannot be manually be written.
40 /// Notable examples are auto traits, `Sized`, and `DiscriminantKind`.
41 /// For a list of all traits with builtin impls, check out the
42 /// [`EvalCtxt::assemble_builtin_impl_candidates`] method. Not
44 /// An assumption from the environment.
46 /// More precicely we've used the `n-th` assumption in the `param_env`.
51 /// fn is_clone<T: Clone>(x: T) -> (T, T) {
52 /// // This uses the assumption `T: Clone` from the `where`-bounds
53 /// // to prove `T: Clone`.
58 /// If the self type is an alias type, e.g. an opaque type or a projection,
59 /// we know the bounds on that alias to hold even without knowing its concrete
62 /// More precisely this candidate is using the `n-th` bound in the `item_bounds` of
69 /// type Assoc: Clone;
72 /// fn foo<T: Trait>(x: <T as Trait>::Assoc) {
73 /// // We prove `<T as Trait>::Assoc` by looking at the bounds on `Assoc` in
74 /// // in the trait definition.
75 /// let _y = x.clone();
81 pub(super) trait GoalKind<'tcx>: TypeFoldable<'tcx> + Copy {
82 fn self_ty(self) -> Ty<'tcx>;
84 fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self;
86 fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId;
88 fn consider_impl_candidate(
89 ecx: &mut EvalCtxt<'_, 'tcx>,
90 goal: Goal<'tcx, Self>,
92 ) -> Result<Certainty, NoSolution>;
94 fn consider_builtin_sized_candidate(
95 ecx: &mut EvalCtxt<'_, 'tcx>,
96 goal: Goal<'tcx, Self>,
97 ) -> Result<Certainty, NoSolution>;
99 fn consider_assumption(
100 ecx: &mut EvalCtxt<'_, 'tcx>,
101 goal: Goal<'tcx, Self>,
102 assumption: ty::Predicate<'tcx>,
103 ) -> Result<Certainty, NoSolution>;
105 impl<'tcx> EvalCtxt<'_, 'tcx> {
106 pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<'tcx>>(
109 ) -> Vec<Candidate<'tcx>> {
110 let mut candidates = Vec::new();
112 self.assemble_candidates_after_normalizing_self_ty(goal, &mut candidates);
114 self.assemble_impl_candidates(goal, &mut candidates);
116 self.assemble_builtin_impl_candidates(goal, &mut candidates);
118 self.assemble_param_env_candidates(goal, &mut candidates);
120 self.assemble_alias_bound_candidates(goal, &mut candidates);
125 /// If the self type of a goal is a projection, computing the relevant candidates is difficult.
127 /// To deal with this, we first try to normalize the self type and add the candidates for the normalized
128 /// self type to the list of candidates in case that succeeds. Note that we can't just eagerly return in
129 /// this case as projections as self types add `
130 fn assemble_candidates_after_normalizing_self_ty<G: GoalKind<'tcx>>(
133 candidates: &mut Vec<Candidate<'tcx>>,
135 let tcx = self.tcx();
136 // FIXME: We also have to normalize opaque types, not sure where to best fit that in.
137 let &ty::Alias(ty::Projection, projection_ty) = goal.predicate.self_ty().kind() else {
140 self.infcx.probe(|_| {
141 let normalized_ty = self.infcx.next_ty_infer();
142 let normalizes_to_goal = goal.with(
144 ty::Binder::dummy(ty::ProjectionPredicate {
146 term: normalized_ty.into(),
149 let normalization_certainty = match self.evaluate_goal(normalizes_to_goal) {
150 Ok((_, certainty)) => certainty,
151 Err(NoSolution) => return,
154 // NOTE: Alternatively we could call `evaluate_goal` here and only have a `Normalized` candidate.
155 // This doesn't work as long as we use `CandidateSource` in winnowing.
156 let goal = goal.with(tcx, goal.predicate.with_self_ty(tcx, normalized_ty));
157 // FIXME: This is broken if we care about the `usize` of `AliasBound` because the self type
158 // could be normalized to yet another projection with different item bounds.
159 let normalized_candidates = self.assemble_and_evaluate_candidates(goal);
160 for mut normalized_candidate in normalized_candidates {
161 normalized_candidate.result =
162 normalized_candidate.result.unchecked_map(|mut response| {
163 // FIXME: This currently hides overflow in the normalization step of the self type
164 // which is probably wrong. Maybe `unify_and` should actually keep overflow as
165 // we treat it as non-fatal anyways.
166 response.certainty = response.certainty.unify_and(normalization_certainty);
169 candidates.push(normalized_candidate);
174 fn assemble_impl_candidates<G: GoalKind<'tcx>>(
177 candidates: &mut Vec<Candidate<'tcx>>,
179 let tcx = self.tcx();
180 tcx.for_each_relevant_impl(
181 goal.predicate.trait_def_id(tcx),
182 goal.predicate.self_ty(),
183 |impl_def_id| match G::consider_impl_candidate(self, goal, impl_def_id)
184 .and_then(|certainty| self.make_canonical_response(certainty))
186 Ok(result) => candidates
187 .push(Candidate { source: CandidateSource::Impl(impl_def_id), result }),
188 Err(NoSolution) => (),
193 fn assemble_builtin_impl_candidates<G: GoalKind<'tcx>>(
196 candidates: &mut Vec<Candidate<'tcx>>,
198 let lang_items = self.tcx().lang_items();
199 let trait_def_id = goal.predicate.trait_def_id(self.tcx());
200 let result = if lang_items.sized_trait() == Some(trait_def_id) {
201 G::consider_builtin_sized_candidate(self, goal)
206 match result.and_then(|certainty| self.make_canonical_response(certainty)) {
208 candidates.push(Candidate { source: CandidateSource::BuiltinImpl, result })
210 Err(NoSolution) => (),
214 fn assemble_param_env_candidates<G: GoalKind<'tcx>>(
217 candidates: &mut Vec<Candidate<'tcx>>,
219 for (i, assumption) in goal.param_env.caller_bounds().iter().enumerate() {
220 match G::consider_assumption(self, goal, assumption)
221 .and_then(|certainty| self.make_canonical_response(certainty))
224 candidates.push(Candidate { source: CandidateSource::ParamEnv(i), result })
226 Err(NoSolution) => (),
231 fn assemble_alias_bound_candidates<G: GoalKind<'tcx>>(
234 candidates: &mut Vec<Candidate<'tcx>>,
236 let alias_ty = match goal.predicate.self_ty().kind() {
254 | ty::GeneratorWitness(_)
258 | ty::Placeholder(..)
260 | ty::Error(_) => return,
261 ty::Bound(..) => bug!("unexpected bound type: {goal:?}"),
262 ty::Alias(_, alias_ty) => alias_ty,
265 for (i, (assumption, _)) in self
267 .bound_explicit_item_bounds(alias_ty.def_id)
268 .subst_iter_copied(self.tcx(), alias_ty.substs)
271 match G::consider_assumption(self, goal, assumption)
272 .and_then(|certainty| self.make_canonical_response(certainty))
275 candidates.push(Candidate { source: CandidateSource::AliasBound(i), result })
277 Err(NoSolution) => (),