]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_middle/src/traits/select.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / compiler / rustc_middle / src / traits / select.rs
1 //! Candidate selection. See the [rustc dev guide] for more information on how this works.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
4
5 use self::EvaluationResult::*;
6
7 use super::{SelectionError, SelectionResult};
8 use rustc_errors::ErrorGuaranteed;
9
10 use crate::ty;
11
12 use rustc_hir::def_id::DefId;
13 use rustc_query_system::cache::Cache;
14
15 pub type SelectionCache<'tcx> = Cache<
16 // This cache does not use `ParamEnvAnd` in its keys because `ParamEnv::and` can replace
17 // caller bounds with an empty list if the `TraitPredicate` looks global, which may happen
18 // after erasing lifetimes from the predicate.
19 (ty::ParamEnv<'tcx>, ty::TraitPredicate<'tcx>),
20 SelectionResult<'tcx, SelectionCandidate<'tcx>>,
21 >;
22
23 pub type EvaluationCache<'tcx> = Cache<
24 // See above: this cache does not use `ParamEnvAnd` in its keys due to sometimes incorrectly
25 // caching with the wrong `ParamEnv`.
26 (ty::ParamEnv<'tcx>, ty::PolyTraitPredicate<'tcx>),
27 EvaluationResult,
28 >;
29
30 /// The selection process begins by considering all impls, where
31 /// clauses, and so forth that might resolve an obligation. Sometimes
32 /// we'll be able to say definitively that (e.g.) an impl does not
33 /// apply to the obligation: perhaps it is defined for `usize` but the
34 /// obligation is for `i32`. In that case, we drop the impl out of the
35 /// list. But the other cases are considered *candidates*.
36 ///
37 /// For selection to succeed, there must be exactly one matching
38 /// candidate. If the obligation is fully known, this is guaranteed
39 /// by coherence. However, if the obligation contains type parameters
40 /// or variables, there may be multiple such impls.
41 ///
42 /// It is not a real problem if multiple matching impls exist because
43 /// of type variables - it just means the obligation isn't sufficiently
44 /// elaborated. In that case we report an ambiguity, and the caller can
45 /// try again after more type information has been gathered or report a
46 /// "type annotations needed" error.
47 ///
48 /// However, with type parameters, this can be a real problem - type
49 /// parameters don't unify with regular types, but they *can* unify
50 /// with variables from blanket impls, and (unless we know its bounds
51 /// will always be satisfied) picking the blanket impl will be wrong
52 /// for at least *some* substitutions. To make this concrete, if we have
53 ///
54 /// ```rust, ignore
55 /// trait AsDebug { type Out: fmt::Debug; fn debug(self) -> Self::Out; }
56 /// impl<T: fmt::Debug> AsDebug for T {
57 /// type Out = T;
58 /// fn debug(self) -> fmt::Debug { self }
59 /// }
60 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
61 /// ```
62 ///
63 /// we can't just use the impl to resolve the `<T as AsDebug>` obligation
64 /// -- a type from another crate (that doesn't implement `fmt::Debug`) could
65 /// implement `AsDebug`.
66 ///
67 /// Because where-clauses match the type exactly, multiple clauses can
68 /// only match if there are unresolved variables, and we can mostly just
69 /// report this ambiguity in that case. This is still a problem - we can't
70 /// *do anything* with ambiguities that involve only regions. This is issue
71 /// #21974.
72 ///
73 /// If a single where-clause matches and there are no inference
74 /// variables left, then it definitely matches and we can just select
75 /// it.
76 ///
77 /// In fact, we even select the where-clause when the obligation contains
78 /// inference variables. The can lead to inference making "leaps of logic",
79 /// for example in this situation:
80 ///
81 /// ```rust, ignore
82 /// pub trait Foo<T> { fn foo(&self) -> T; }
83 /// impl<T> Foo<()> for T { fn foo(&self) { } }
84 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
85 ///
86 /// pub fn foo<T>(t: T) where T: Foo<bool> {
87 /// println!("{:?}", <T as Foo<_>>::foo(&t));
88 /// }
89 /// fn main() { foo(false); }
90 /// ```
91 ///
92 /// Here the obligation `<T as Foo<$0>>` can be matched by both the blanket
93 /// impl and the where-clause. We select the where-clause and unify `$0=bool`,
94 /// so the program prints "false". However, if the where-clause is omitted,
95 /// the blanket impl is selected, we unify `$0=()`, and the program prints
96 /// "()".
97 ///
98 /// Exactly the same issues apply to projection and object candidates, except
99 /// that we can have both a projection candidate and a where-clause candidate
100 /// for the same obligation. In that case either would do (except that
101 /// different "leaps of logic" would occur if inference variables are
102 /// present), and we just pick the where-clause. This is, for example,
103 /// required for associated types to work in default impls, as the bounds
104 /// are visible both as projection bounds and as where-clauses from the
105 /// parameter environment.
106 #[derive(PartialEq, Eq, Debug, Clone, TypeFoldable, TypeVisitable)]
107 pub enum SelectionCandidate<'tcx> {
108 BuiltinCandidate {
109 /// `false` if there are no *further* obligations.
110 has_nested: bool,
111 },
112
113 /// Implementation of transmutability trait.
114 TransmutabilityCandidate,
115
116 ParamCandidate(ty::PolyTraitPredicate<'tcx>),
117 ImplCandidate(DefId),
118 AutoImplCandidate(DefId),
119
120 /// This is a trait matching with a projected type as `Self`, and we found
121 /// an applicable bound in the trait definition. The `usize` is an index
122 /// into the list returned by `tcx.item_bounds`.
123 ProjectionCandidate(usize),
124
125 /// Implementation of a `Fn`-family trait by one of the anonymous types
126 /// generated for an `||` expression.
127 ClosureCandidate,
128
129 /// Implementation of a `Generator` trait by one of the anonymous types
130 /// generated for a generator.
131 GeneratorCandidate,
132
133 /// Implementation of a `Fn`-family trait by one of the anonymous
134 /// types generated for a fn pointer type (e.g., `fn(int) -> int`)
135 FnPointerCandidate {
136 is_const: bool,
137 },
138
139 /// Builtin implementation of `DiscriminantKind`.
140 DiscriminantKindCandidate,
141
142 /// Builtin implementation of `Pointee`.
143 PointeeCandidate,
144
145 TraitAliasCandidate(DefId),
146
147 /// Matching `dyn Trait` with a supertrait of `Trait`. The index is the
148 /// position in the iterator returned by
149 /// `rustc_infer::traits::util::supertraits`.
150 ObjectCandidate(usize),
151
152 /// Perform trait upcasting coercion of `dyn Trait` to a supertrait of `Trait`.
153 /// The index is the position in the iterator returned by
154 /// `rustc_infer::traits::util::supertraits`.
155 TraitUpcastingUnsizeCandidate(usize),
156
157 BuiltinObjectCandidate,
158
159 BuiltinUnsizeCandidate,
160
161 /// Implementation of `const Destruct`, optionally from a custom `impl const Drop`.
162 ConstDestructCandidate(Option<DefId>),
163 }
164
165 /// The result of trait evaluation. The order is important
166 /// here as the evaluation of a list is the maximum of the
167 /// evaluations.
168 ///
169 /// The evaluation results are ordered:
170 /// - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
171 /// implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
172 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
173 /// - the "union" of evaluation results is equal to their maximum -
174 /// all the "potential success" candidates can potentially succeed,
175 /// so they are noops when unioned with a definite error, and within
176 /// the categories it's easy to see that the unions are correct.
177 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, HashStable)]
178 pub enum EvaluationResult {
179 /// Evaluation successful.
180 EvaluatedToOk,
181 /// Evaluation successful, but there were unevaluated region obligations.
182 EvaluatedToOkModuloRegions,
183 /// Evaluation successful, but need to rerun because opaque types got
184 /// hidden types assigned without it being known whether the opaque types
185 /// are within their defining scope
186 EvaluatedToOkModuloOpaqueTypes,
187 /// Evaluation is known to be ambiguous -- it *might* hold for some
188 /// assignment of inference variables, but it might not.
189 ///
190 /// While this has the same meaning as `EvaluatedToUnknown` -- we can't
191 /// know whether this obligation holds or not -- it is the result we
192 /// would get with an empty stack, and therefore is cacheable.
193 EvaluatedToAmbig,
194 /// Evaluation failed because of recursion involving inference
195 /// variables. We are somewhat imprecise there, so we don't actually
196 /// know the real result.
197 ///
198 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
199 EvaluatedToUnknown,
200 /// Evaluation failed because we encountered an obligation we are already
201 /// trying to prove on this branch.
202 ///
203 /// We know this branch can't be a part of a minimal proof-tree for
204 /// the "root" of our cycle, because then we could cut out the recursion
205 /// and maintain a valid proof tree. However, this does not mean
206 /// that all the obligations on this branch do not hold -- it's possible
207 /// that we entered this branch "speculatively", and that there
208 /// might be some other way to prove this obligation that does not
209 /// go through this cycle -- so we can't cache this as a failure.
210 ///
211 /// For example, suppose we have this:
212 ///
213 /// ```rust,ignore (pseudo-Rust)
214 /// pub trait Trait { fn xyz(); }
215 /// // This impl is "useless", but we can still have
216 /// // an `impl Trait for SomeUnsizedType` somewhere.
217 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
218 ///
219 /// pub fn foo<T: Trait + ?Sized>() {
220 /// <T as Trait>::xyz();
221 /// }
222 /// ```
223 ///
224 /// When checking `foo`, we have to prove `T: Trait`. This basically
225 /// translates into this:
226 ///
227 /// ```plain,ignore
228 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
229 /// ```
230 ///
231 /// When we try to prove it, we first go the first option, which
232 /// recurses. This shows us that the impl is "useless" -- it won't
233 /// tell us that `T: Trait` unless it already implemented `Trait`
234 /// by some other means. However, that does not prevent `T: Trait`
235 /// does not hold, because of the bound (which can indeed be satisfied
236 /// by `SomeUnsizedType` from another crate).
237 //
238 // FIXME: when an `EvaluatedToRecur` goes past its parent root, we
239 // ought to convert it to an `EvaluatedToErr`, because we know
240 // there definitely isn't a proof tree for that obligation. Not
241 // doing so is still sound -- there isn't any proof tree, so the
242 // branch still can't be a part of a minimal one -- but does not re-enable caching.
243 EvaluatedToRecur,
244 /// Evaluation failed.
245 EvaluatedToErr,
246 }
247
248 impl EvaluationResult {
249 /// Returns `true` if this evaluation result is known to apply, even
250 /// considering outlives constraints.
251 pub fn must_apply_considering_regions(self) -> bool {
252 self == EvaluatedToOk
253 }
254
255 /// Returns `true` if this evaluation result is known to apply, ignoring
256 /// outlives constraints.
257 pub fn must_apply_modulo_regions(self) -> bool {
258 self <= EvaluatedToOkModuloRegions
259 }
260
261 pub fn may_apply(self) -> bool {
262 match self {
263 EvaluatedToOkModuloOpaqueTypes
264 | EvaluatedToOk
265 | EvaluatedToOkModuloRegions
266 | EvaluatedToAmbig
267 | EvaluatedToUnknown => true,
268
269 EvaluatedToErr | EvaluatedToRecur => false,
270 }
271 }
272
273 pub fn is_stack_dependent(self) -> bool {
274 match self {
275 EvaluatedToUnknown | EvaluatedToRecur => true,
276
277 EvaluatedToOkModuloOpaqueTypes
278 | EvaluatedToOk
279 | EvaluatedToOkModuloRegions
280 | EvaluatedToAmbig
281 | EvaluatedToErr => false,
282 }
283 }
284 }
285
286 /// Indicates that trait evaluation caused overflow and in which pass.
287 #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable)]
288 pub enum OverflowError {
289 Error(ErrorGuaranteed),
290 Canonical,
291 ErrorReporting,
292 }
293
294 impl From<ErrorGuaranteed> for OverflowError {
295 fn from(e: ErrorGuaranteed) -> OverflowError {
296 OverflowError::Error(e)
297 }
298 }
299
300 TrivialTypeTraversalAndLiftImpls! {
301 OverflowError,
302 }
303
304 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
305 fn from(overflow_error: OverflowError) -> SelectionError<'tcx> {
306 match overflow_error {
307 OverflowError::Error(e) => SelectionError::Overflow(OverflowError::Error(e)),
308 OverflowError::Canonical => SelectionError::Overflow(OverflowError::Canonical),
309 OverflowError::ErrorReporting => SelectionError::ErrorReporting,
310 }
311 }
312 }