1 //! Dealing with trait goals, i.e. `T: Trait<'a, U>`.
5 use super::assembly::{self, AssemblyCtxt};
6 use super::{EvalCtxt, Goal, QueryResult};
7 use rustc_hir::def_id::DefId;
8 use rustc_infer::infer::InferOk;
9 use rustc_infer::traits::query::NoSolution;
10 use rustc_infer::traits::ObligationCause;
11 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
12 use rustc_middle::ty::TraitPredicate;
13 use rustc_middle::ty::{self, Ty, TyCtxt};
14 use rustc_span::DUMMY_SP;
16 #[allow(dead_code)] // FIXME: implement and use all variants.
17 #[derive(Debug, Clone, Copy)]
18 pub(super) enum CandidateSource {
19 /// Some user-defined impl with the given `DefId`.
21 /// The n-th caller bound in the `param_env` of our goal.
23 /// This is pretty much always a bound from the `where`-clauses of the
24 /// currently checked item.
26 /// A bound on the `self_ty` in case it is a projection or an opaque type.
30 /// ```ignore (for syntax highlighting)
32 /// type Assoc: OtherTrait;
36 /// We know that `<Whatever as Trait>::Assoc: OtherTrait` holds by looking at
37 /// the bounds on `Trait::Assoc`.
39 /// A builtin implementation for some specific traits, used in cases
40 /// where we cannot rely an ordinary library implementations.
42 /// The most notable examples are `Sized`, `Copy` and `Clone`. This is also
43 /// used for the `DiscriminantKind` and `Pointee` trait, both of which have
44 /// an associated type.
46 /// An automatic impl for an auto trait, e.g. `Send`. These impls recursively look
47 /// at the constituent types of the `self_ty` to check whether the auto trait
48 /// is implemented for those.
52 type Candidate<'tcx> = assembly::Candidate<'tcx, TraitPredicate<'tcx>>;
54 impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> {
55 type CandidateSource = CandidateSource;
57 fn self_ty(self) -> Ty<'tcx> {
61 fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
62 self.with_self_ty(tcx, self_ty)
65 fn trait_def_id(self, _: TyCtxt<'tcx>) -> DefId {
69 fn consider_impl_candidate(
70 acx: &mut AssemblyCtxt<'_, '_, 'tcx, Self>,
71 goal: Goal<'tcx, TraitPredicate<'tcx>>,
74 let tcx = acx.cx.tcx();
75 let infcx = acx.cx.infcx;
77 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
78 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
79 if iter::zip(goal.predicate.trait_ref.substs, impl_trait_ref.skip_binder().substs)
80 .any(|(goal, imp)| !drcx.generic_args_may_unify(goal, imp))
86 let impl_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
87 let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
89 let Ok(InferOk { obligations, .. }) = infcx
90 .at(&ObligationCause::dummy(), goal.param_env)
91 .define_opaque_types(false)
92 .eq(goal.predicate.trait_ref, impl_trait_ref)
93 .map_err(|e| debug!("failed to equate trait refs: {e:?}"))
97 let where_clause_bounds = tcx
98 .predicates_of(impl_def_id)
99 .instantiate(tcx, impl_substs)
102 .map(|pred| goal.with(tcx, pred));
105 obligations.into_iter().map(|o| o.into()).chain(where_clause_bounds).collect();
107 let Ok(certainty) = acx.cx.evaluate_all(nested_goals) else { return };
108 acx.try_insert_candidate(CandidateSource::Impl(impl_def_id), certainty);
113 impl<'tcx> EvalCtxt<'_, 'tcx> {
114 pub(super) fn compute_trait_goal(
116 goal: Goal<'tcx, TraitPredicate<'tcx>>,
117 ) -> QueryResult<'tcx> {
118 let candidates = AssemblyCtxt::assemble_and_evaluate_candidates(self, goal);
119 self.merge_trait_candidates_discard_reservation_impls(candidates)
122 #[instrument(level = "debug", skip(self), ret)]
123 pub(super) fn merge_trait_candidates_discard_reservation_impls(
125 mut candidates: Vec<Candidate<'tcx>>,
126 ) -> QueryResult<'tcx> {
127 match candidates.len() {
128 0 => return Err(NoSolution),
129 1 => return Ok(self.discard_reservation_impl(candidates.pop().unwrap()).result),
133 if candidates.len() > 1 {
135 'outer: while i < candidates.len() {
136 for j in (0..candidates.len()).filter(|&j| i != j) {
137 if self.trait_candidate_should_be_dropped_in_favor_of(
141 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
142 candidates.swap_remove(i);
147 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
148 // If there are *STILL* multiple candidates, give up
149 // and report ambiguity.
152 debug!("multiple matches, ambig");
153 // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
159 Ok(self.discard_reservation_impl(candidates.pop().unwrap()).result)
162 fn trait_candidate_should_be_dropped_in_favor_of(
164 candidate: &Candidate<'tcx>,
165 other: &Candidate<'tcx>,
167 // FIXME: implement this
168 match (candidate.source, other.source) {
169 (CandidateSource::Impl(_), _)
170 | (CandidateSource::ParamEnv(_), _)
171 | (CandidateSource::AliasBound(_), _)
172 | (CandidateSource::Builtin, _)
173 | (CandidateSource::AutoImpl, _) => unimplemented!(),
177 fn discard_reservation_impl(&self, candidate: Candidate<'tcx>) -> Candidate<'tcx> {
178 if let CandidateSource::Impl(def_id) = candidate.source {
179 if let ty::ImplPolarity::Reservation = self.tcx().impl_polarity(def_id) {
180 debug!("Selected reservation impl");
181 // FIXME: reduce candidate to ambiguous
182 // FIXME: replace `var_values` with identity, yeet external constraints.