]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/solve/trait_goals.rs
cc68cfeea1d07fd40868759ce9cbef85ee4989d9
[rust.git] / compiler / rustc_trait_selection / src / solve / trait_goals.rs
1 //! Dealing with trait goals, i.e. `T: Trait<'a, U>`.
2
3 use std::iter;
4
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;
15
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`.
20     Impl(DefId),
21     /// The n-th caller bound in the `param_env` of our goal.
22     ///
23     /// This is pretty much always a bound from the `where`-clauses of the
24     /// currently checked item.
25     ParamEnv(usize),
26     /// A bound on the `self_ty` in case it is a projection or an opaque type.
27     ///
28     /// # Examples
29     ///
30     /// ```ignore (for syntax highlighting)
31     /// trait Trait {
32     ///     type Assoc: OtherTrait;
33     /// }
34     /// ```
35     ///
36     /// We know that `<Whatever as Trait>::Assoc: OtherTrait` holds by looking at
37     /// the bounds on `Trait::Assoc`.
38     AliasBound(usize),
39     /// A builtin implementation for some specific traits, used in cases
40     /// where we cannot rely an ordinary library implementations.
41     ///
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.
45     Builtin,
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.
49     AutoImpl,
50 }
51
52 type Candidate<'tcx> = assembly::Candidate<'tcx, TraitPredicate<'tcx>>;
53
54 impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> {
55     type CandidateSource = CandidateSource;
56
57     fn self_ty(self) -> Ty<'tcx> {
58         self.self_ty()
59     }
60
61     fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
62         self.with_self_ty(tcx, self_ty)
63     }
64
65     fn trait_def_id(self, _: TyCtxt<'tcx>) -> DefId {
66         self.def_id()
67     }
68
69     fn consider_impl_candidate(
70         acx: &mut AssemblyCtxt<'_, '_, 'tcx, Self>,
71         goal: Goal<'tcx, TraitPredicate<'tcx>>,
72         impl_def_id: DefId,
73     ) {
74         let tcx = acx.cx.tcx();
75         let infcx = acx.cx.infcx;
76
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))
81         {
82             return;
83         }
84
85         infcx.probe(|_| {
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);
88
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:?}"))
94             else {
95                 return
96             };
97             let where_clause_bounds = tcx
98                 .predicates_of(impl_def_id)
99                 .instantiate(tcx, impl_substs)
100                 .predicates
101                 .into_iter()
102                 .map(|pred| goal.with(tcx, pred));
103
104             let nested_goals =
105                 obligations.into_iter().map(|o| o.into()).chain(where_clause_bounds).collect();
106
107             let Ok(certainty) = acx.cx.evaluate_all(nested_goals) else { return };
108             acx.try_insert_candidate(CandidateSource::Impl(impl_def_id), certainty);
109         })
110     }
111 }
112
113 impl<'tcx> EvalCtxt<'_, 'tcx> {
114     pub(super) fn compute_trait_goal(
115         &mut self,
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)
120     }
121
122     #[instrument(level = "debug", skip(self), ret)]
123     pub(super) fn merge_trait_candidates_discard_reservation_impls(
124         &mut self,
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),
130             _ => {}
131         }
132
133         if candidates.len() > 1 {
134             let mut i = 0;
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(
138                         &candidates[i],
139                         &candidates[j],
140                     ) {
141                         debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
142                         candidates.swap_remove(i);
143                         continue 'outer;
144                     }
145                 }
146
147                 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
148                 // If there are *STILL* multiple candidates, give up
149                 // and report ambiguity.
150                 i += 1;
151                 if i > 1 {
152                     debug!("multiple matches, ambig");
153                     // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
154                     unimplemented!();
155                 }
156             }
157         }
158
159         Ok(self.discard_reservation_impl(candidates.pop().unwrap()).result)
160     }
161
162     fn trait_candidate_should_be_dropped_in_favor_of(
163         &self,
164         candidate: &Candidate<'tcx>,
165         other: &Candidate<'tcx>,
166     ) -> bool {
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!(),
174         }
175     }
176
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.
183                 unimplemented!()
184             }
185         }
186
187         candidate
188     }
189 }