]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/solve/assembly.rs
Test drop_tracking_mir before querying generator.
[rust.git] / compiler / rustc_trait_selection / src / solve / assembly.rs
1 //! Code shared by trait and projection goals for candidate assembly.
2
3 use super::infcx_ext::InferCtxtExt;
4 #[cfg(doc)]
5 use super::trait_goals::structural_traits::*;
6 use super::{CanonicalResponse, Certainty, EvalCtxt, Goal, QueryResult};
7 use rustc_hir::def_id::DefId;
8 use rustc_infer::traits::query::NoSolution;
9 use rustc_infer::traits::util::elaborate_predicates;
10 use rustc_middle::ty::TypeFoldable;
11 use rustc_middle::ty::{self, Ty, TyCtxt};
12 use std::fmt::Debug;
13
14 /// A candidate is a possible way to prove a goal.
15 ///
16 /// It consists of both the `source`, which describes how that goal would be proven,
17 /// and the `result` when using the given `source`.
18 #[derive(Debug, Clone)]
19 pub(super) struct Candidate<'tcx> {
20     pub(super) source: CandidateSource,
21     pub(super) result: CanonicalResponse<'tcx>,
22 }
23
24 /// Possible ways the given goal can be proven.
25 #[derive(Debug, Clone, Copy)]
26 pub(super) enum CandidateSource {
27     /// A user written impl.
28     ///
29     /// ## Examples
30     ///
31     /// ```rust
32     /// fn main() {
33     ///     let x: Vec<u32> = Vec::new();
34     ///     // This uses the impl from the standard library to prove `Vec<T>: Clone`.
35     ///     let y = x.clone();
36     /// }
37     /// ```
38     Impl(DefId),
39     /// A builtin impl generated by the compiler. When adding a new special
40     /// trait, try to use actual impls whenever possible. Builtin impls should
41     /// only be used in cases where the impl cannot be manually be written.
42     ///
43     /// Notable examples are auto traits, `Sized`, and `DiscriminantKind`.
44     /// For a list of all traits with builtin impls, check out the
45     /// [`EvalCtxt::assemble_builtin_impl_candidates`] method. Not
46     BuiltinImpl,
47     /// An assumption from the environment.
48     ///
49     /// More precicely we've used the `n-th` assumption in the `param_env`.
50     ///
51     /// ## Examples
52     ///
53     /// ```rust
54     /// fn is_clone<T: Clone>(x: T) -> (T, T) {
55     ///     // This uses the assumption `T: Clone` from the `where`-bounds
56     ///     // to prove `T: Clone`.
57     ///     (x.clone(), x)
58     /// }
59     /// ```
60     ParamEnv(usize),
61     /// If the self type is an alias type, e.g. an opaque type or a projection,
62     /// we know the bounds on that alias to hold even without knowing its concrete
63     /// underlying type.
64     ///
65     /// More precisely this candidate is using the `n-th` bound in the `item_bounds` of
66     /// the self type.
67     ///
68     /// ## Examples
69     ///
70     /// ```rust
71     /// trait Trait {
72     ///     type Assoc: Clone;
73     /// }
74     ///
75     /// fn foo<T: Trait>(x: <T as Trait>::Assoc) {
76     ///     // We prove `<T as Trait>::Assoc` by looking at the bounds on `Assoc` in
77     ///     // in the trait definition.
78     ///     let _y = x.clone();
79     /// }
80     /// ```
81     AliasBound(usize),
82 }
83
84 pub(super) trait GoalKind<'tcx>: TypeFoldable<'tcx> + Copy + Eq {
85     fn self_ty(self) -> Ty<'tcx>;
86
87     fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self;
88
89     fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId;
90
91     fn consider_impl_candidate(
92         ecx: &mut EvalCtxt<'_, 'tcx>,
93         goal: Goal<'tcx, Self>,
94         impl_def_id: DefId,
95     ) -> QueryResult<'tcx>;
96
97     fn consider_assumption(
98         ecx: &mut EvalCtxt<'_, 'tcx>,
99         goal: Goal<'tcx, Self>,
100         assumption: ty::Predicate<'tcx>,
101     ) -> QueryResult<'tcx>;
102
103     // A type implements an `auto trait` if its components do as well. These components
104     // are given by built-in rules from [`instantiate_constituent_tys_for_auto_trait`].
105     fn consider_auto_trait_candidate(
106         ecx: &mut EvalCtxt<'_, 'tcx>,
107         goal: Goal<'tcx, Self>,
108     ) -> QueryResult<'tcx>;
109
110     // A trait alias holds if the RHS traits and `where` clauses hold.
111     fn consider_trait_alias_candidate(
112         ecx: &mut EvalCtxt<'_, 'tcx>,
113         goal: Goal<'tcx, Self>,
114     ) -> QueryResult<'tcx>;
115
116     // A type is `Copy` or `Clone` if its components are `Sized`. These components
117     // are given by built-in rules from [`instantiate_constituent_tys_for_sized_trait`].
118     fn consider_builtin_sized_candidate(
119         ecx: &mut EvalCtxt<'_, 'tcx>,
120         goal: Goal<'tcx, Self>,
121     ) -> QueryResult<'tcx>;
122
123     // A type is `Copy` or `Clone` if its components are `Copy` or `Clone`. These
124     // components are given by built-in rules from [`instantiate_constituent_tys_for_copy_clone_trait`].
125     fn consider_builtin_copy_clone_candidate(
126         ecx: &mut EvalCtxt<'_, 'tcx>,
127         goal: Goal<'tcx, Self>,
128     ) -> QueryResult<'tcx>;
129
130     // A type is `PointerSized` if we can compute its layout, and that layout
131     // matches the layout of `usize`.
132     fn consider_builtin_pointer_sized_candidate(
133         ecx: &mut EvalCtxt<'_, 'tcx>,
134         goal: Goal<'tcx, Self>,
135     ) -> QueryResult<'tcx>;
136
137     // A callable type (a closure, fn def, or fn ptr) is known to implement the `Fn<A>`
138     // family of traits where `A` is given by the signature of the type.
139     fn consider_builtin_fn_trait_candidates(
140         ecx: &mut EvalCtxt<'_, 'tcx>,
141         goal: Goal<'tcx, Self>,
142         kind: ty::ClosureKind,
143     ) -> QueryResult<'tcx>;
144
145     // `Tuple` is implemented if the `Self` type is a tuple.
146     fn consider_builtin_tuple_candidate(
147         ecx: &mut EvalCtxt<'_, 'tcx>,
148         goal: Goal<'tcx, Self>,
149     ) -> QueryResult<'tcx>;
150
151     // `Pointee` is always implemented.
152     //
153     // See the projection implementation for the `Metadata` types for all of
154     // the built-in types. For structs, the metadata type is given by the struct
155     // tail.
156     fn consider_builtin_pointee_candidate(
157         ecx: &mut EvalCtxt<'_, 'tcx>,
158         goal: Goal<'tcx, Self>,
159     ) -> QueryResult<'tcx>;
160
161     // A generator (that comes from an `async` desugaring) is known to implement
162     // `Future<Output = O>`, where `O` is given by the generator's return type
163     // that was computed during type-checking.
164     fn consider_builtin_future_candidate(
165         ecx: &mut EvalCtxt<'_, 'tcx>,
166         goal: Goal<'tcx, Self>,
167     ) -> QueryResult<'tcx>;
168
169     // A generator (that doesn't come from an `async` desugaring) is known to
170     // implement `Generator<R, Yield = Y, Return = O>`, given the resume, yield,
171     // and return types of the generator computed during type-checking.
172     fn consider_builtin_generator_candidate(
173         ecx: &mut EvalCtxt<'_, 'tcx>,
174         goal: Goal<'tcx, Self>,
175     ) -> QueryResult<'tcx>;
176 }
177
178 impl<'tcx> EvalCtxt<'_, 'tcx> {
179     pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<'tcx>>(
180         &mut self,
181         goal: Goal<'tcx, G>,
182     ) -> Vec<Candidate<'tcx>> {
183         debug_assert_eq!(goal, self.infcx.resolve_vars_if_possible(goal));
184
185         // HACK: `_: Trait` is ambiguous, because it may be satisfied via a builtin rule,
186         // object bound, alias bound, etc. We are unable to determine this until we can at
187         // least structually resolve the type one layer.
188         if goal.predicate.self_ty().is_ty_var() {
189             return vec![Candidate {
190                 source: CandidateSource::BuiltinImpl,
191                 result: self.make_canonical_response(Certainty::AMBIGUOUS).unwrap(),
192             }];
193         }
194
195         let mut candidates = Vec::new();
196
197         self.assemble_candidates_after_normalizing_self_ty(goal, &mut candidates);
198
199         self.assemble_impl_candidates(goal, &mut candidates);
200
201         self.assemble_builtin_impl_candidates(goal, &mut candidates);
202
203         self.assemble_param_env_candidates(goal, &mut candidates);
204
205         self.assemble_alias_bound_candidates(goal, &mut candidates);
206
207         self.assemble_object_bound_candidates(goal, &mut candidates);
208
209         candidates
210     }
211
212     /// If the self type of a goal is a projection, computing the relevant candidates is difficult.
213     ///
214     /// To deal with this, we first try to normalize the self type and add the candidates for the normalized
215     /// self type to the list of candidates in case that succeeds. Note that we can't just eagerly return in
216     /// this case as projections as self types add `
217     fn assemble_candidates_after_normalizing_self_ty<G: GoalKind<'tcx>>(
218         &mut self,
219         goal: Goal<'tcx, G>,
220         candidates: &mut Vec<Candidate<'tcx>>,
221     ) {
222         let tcx = self.tcx();
223         // FIXME: We also have to normalize opaque types, not sure where to best fit that in.
224         let &ty::Alias(ty::Projection, projection_ty) = goal.predicate.self_ty().kind() else {
225             return
226         };
227         self.infcx.probe(|_| {
228             let normalized_ty = self.infcx.next_ty_infer();
229             let normalizes_to_goal = goal.with(
230                 tcx,
231                 ty::Binder::dummy(ty::ProjectionPredicate {
232                     projection_ty,
233                     term: normalized_ty.into(),
234                 }),
235             );
236             let normalization_certainty = match self.evaluate_goal(normalizes_to_goal) {
237                 Ok((_, certainty)) => certainty,
238                 Err(NoSolution) => return,
239             };
240             let normalized_ty = self.infcx.resolve_vars_if_possible(normalized_ty);
241
242             // NOTE: Alternatively we could call `evaluate_goal` here and only have a `Normalized` candidate.
243             // This doesn't work as long as we use `CandidateSource` in winnowing.
244             let goal = goal.with(tcx, goal.predicate.with_self_ty(tcx, normalized_ty));
245             // FIXME: This is broken if we care about the `usize` of `AliasBound` because the self type
246             // could be normalized to yet another projection with different item bounds.
247             let normalized_candidates = self.assemble_and_evaluate_candidates(goal);
248             for mut normalized_candidate in normalized_candidates {
249                 normalized_candidate.result =
250                     normalized_candidate.result.unchecked_map(|mut response| {
251                         // FIXME: This currently hides overflow in the normalization step of the self type
252                         // which is probably wrong. Maybe `unify_and` should actually keep overflow as
253                         // we treat it as non-fatal anyways.
254                         response.certainty = response.certainty.unify_and(normalization_certainty);
255                         response
256                     });
257                 candidates.push(normalized_candidate);
258             }
259         })
260     }
261
262     fn assemble_impl_candidates<G: GoalKind<'tcx>>(
263         &mut self,
264         goal: Goal<'tcx, G>,
265         candidates: &mut Vec<Candidate<'tcx>>,
266     ) {
267         let tcx = self.tcx();
268         tcx.for_each_relevant_impl(
269             goal.predicate.trait_def_id(tcx),
270             goal.predicate.self_ty(),
271             |impl_def_id| match G::consider_impl_candidate(self, goal, impl_def_id) {
272                 Ok(result) => candidates
273                     .push(Candidate { source: CandidateSource::Impl(impl_def_id), result }),
274                 Err(NoSolution) => (),
275             },
276         );
277     }
278
279     fn assemble_builtin_impl_candidates<G: GoalKind<'tcx>>(
280         &mut self,
281         goal: Goal<'tcx, G>,
282         candidates: &mut Vec<Candidate<'tcx>>,
283     ) {
284         let lang_items = self.tcx().lang_items();
285         let trait_def_id = goal.predicate.trait_def_id(self.tcx());
286         let result = if self.tcx().trait_is_auto(trait_def_id) {
287             G::consider_auto_trait_candidate(self, goal)
288         } else if self.tcx().trait_is_alias(trait_def_id) {
289             G::consider_trait_alias_candidate(self, goal)
290         } else if lang_items.sized_trait() == Some(trait_def_id) {
291             G::consider_builtin_sized_candidate(self, goal)
292         } else if lang_items.copy_trait() == Some(trait_def_id)
293             || lang_items.clone_trait() == Some(trait_def_id)
294         {
295             G::consider_builtin_copy_clone_candidate(self, goal)
296         } else if lang_items.pointer_sized() == Some(trait_def_id) {
297             G::consider_builtin_pointer_sized_candidate(self, goal)
298         } else if let Some(kind) = self.tcx().fn_trait_kind_from_def_id(trait_def_id) {
299             G::consider_builtin_fn_trait_candidates(self, goal, kind)
300         } else if lang_items.tuple_trait() == Some(trait_def_id) {
301             G::consider_builtin_tuple_candidate(self, goal)
302         } else if lang_items.pointee_trait() == Some(trait_def_id) {
303             G::consider_builtin_pointee_candidate(self, goal)
304         } else if lang_items.future_trait() == Some(trait_def_id) {
305             G::consider_builtin_future_candidate(self, goal)
306         } else if lang_items.gen_trait() == Some(trait_def_id) {
307             G::consider_builtin_generator_candidate(self, goal)
308         } else {
309             Err(NoSolution)
310         };
311
312         match result {
313             Ok(result) => {
314                 candidates.push(Candidate { source: CandidateSource::BuiltinImpl, result })
315             }
316             Err(NoSolution) => (),
317         }
318     }
319
320     fn assemble_param_env_candidates<G: GoalKind<'tcx>>(
321         &mut self,
322         goal: Goal<'tcx, G>,
323         candidates: &mut Vec<Candidate<'tcx>>,
324     ) {
325         for (i, assumption) in goal.param_env.caller_bounds().iter().enumerate() {
326             match G::consider_assumption(self, goal, assumption) {
327                 Ok(result) => {
328                     candidates.push(Candidate { source: CandidateSource::ParamEnv(i), result })
329                 }
330                 Err(NoSolution) => (),
331             }
332         }
333     }
334
335     fn assemble_alias_bound_candidates<G: GoalKind<'tcx>>(
336         &mut self,
337         goal: Goal<'tcx, G>,
338         candidates: &mut Vec<Candidate<'tcx>>,
339     ) {
340         let alias_ty = match goal.predicate.self_ty().kind() {
341             ty::Bool
342             | ty::Char
343             | ty::Int(_)
344             | ty::Uint(_)
345             | ty::Float(_)
346             | ty::Adt(_, _)
347             | ty::Foreign(_)
348             | ty::Str
349             | ty::Array(_, _)
350             | ty::Slice(_)
351             | ty::RawPtr(_)
352             | ty::Ref(_, _, _)
353             | ty::FnDef(_, _)
354             | ty::FnPtr(_)
355             | ty::Dynamic(..)
356             | ty::Closure(..)
357             | ty::Generator(..)
358             | ty::GeneratorWitness(_)
359             | ty::GeneratorWitnessMIR(..)
360             | ty::Never
361             | ty::Tuple(_)
362             | ty::Param(_)
363             | ty::Placeholder(..)
364             | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
365             | ty::Error(_) => return,
366             ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
367             | ty::Bound(..) => bug!("unexpected self type for `{goal:?}`"),
368             ty::Alias(_, alias_ty) => alias_ty,
369         };
370
371         for (i, (assumption, _)) in self
372             .tcx()
373             .bound_explicit_item_bounds(alias_ty.def_id)
374             .subst_iter_copied(self.tcx(), alias_ty.substs)
375             .enumerate()
376         {
377             match G::consider_assumption(self, goal, assumption) {
378                 Ok(result) => {
379                     candidates.push(Candidate { source: CandidateSource::AliasBound(i), result })
380                 }
381                 Err(NoSolution) => (),
382             }
383         }
384     }
385
386     fn assemble_object_bound_candidates<G: GoalKind<'tcx>>(
387         &mut self,
388         goal: Goal<'tcx, G>,
389         candidates: &mut Vec<Candidate<'tcx>>,
390     ) {
391         let self_ty = goal.predicate.self_ty();
392         let bounds = match *self_ty.kind() {
393             ty::Bool
394             | ty::Char
395             | ty::Int(_)
396             | ty::Uint(_)
397             | ty::Float(_)
398             | ty::Adt(_, _)
399             | ty::Foreign(_)
400             | ty::Str
401             | ty::Array(_, _)
402             | ty::Slice(_)
403             | ty::RawPtr(_)
404             | ty::Ref(_, _, _)
405             | ty::FnDef(_, _)
406             | ty::FnPtr(_)
407             | ty::Alias(..)
408             | ty::Closure(..)
409             | ty::Generator(..)
410             | ty::GeneratorWitness(_)
411             | ty::GeneratorWitnessMIR(..)
412             | ty::Never
413             | ty::Tuple(_)
414             | ty::Param(_)
415             | ty::Placeholder(..)
416             | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
417             | ty::Error(_) => return,
418             ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_))
419             | ty::Bound(..) => bug!("unexpected self type for `{goal:?}`"),
420             ty::Dynamic(bounds, ..) => bounds,
421         };
422
423         let tcx = self.tcx();
424         for assumption in
425             elaborate_predicates(tcx, bounds.iter().map(|bound| bound.with_self_ty(tcx, self_ty)))
426         {
427             match G::consider_assumption(self, goal, assumption.predicate) {
428                 Ok(result) => {
429                     candidates.push(Candidate { source: CandidateSource::BuiltinImpl, result })
430                 }
431                 Err(NoSolution) => (),
432             }
433         }
434     }
435 }