rustc_middle/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
5use rustc_errors::ErrorGuaranteed;
6use rustc_hir::def_id::DefId;
7use rustc_macros::{HashStable, TypeVisitable};
8use rustc_query_system::cache::Cache;
9
10use self::EvaluationResult::*;
11use super::{SelectionError, SelectionResult};
12use crate::ty;
13
14pub type SelectionCache<'tcx, ENV> =
15    Cache<(ENV, ty::TraitPredicate<'tcx>), SelectionResult<'tcx, SelectionCandidate<'tcx>>>;
16
17pub type EvaluationCache<'tcx, ENV> = Cache<(ENV, ty::PolyTraitPredicate<'tcx>), EvaluationResult>;
18
19/// The selection process begins by considering all impls, where
20/// clauses, and so forth that might resolve an obligation. Sometimes
21/// we'll be able to say definitively that (e.g.) an impl does not
22/// apply to the obligation: perhaps it is defined for `usize` but the
23/// obligation is for `i32`. In that case, we drop the impl out of the
24/// list. But the other cases are considered *candidates*.
25///
26/// For selection to succeed, there must be exactly one matching
27/// candidate. If the obligation is fully known, this is guaranteed
28/// by coherence. However, if the obligation contains type parameters
29/// or variables, there may be multiple such impls.
30///
31/// It is not a real problem if multiple matching impls exist because
32/// of type variables - it just means the obligation isn't sufficiently
33/// elaborated. In that case we report an ambiguity, and the caller can
34/// try again after more type information has been gathered or report a
35/// "type annotations needed" error.
36///
37/// However, with type parameters, this can be a real problem - type
38/// parameters don't unify with regular types, but they *can* unify
39/// with variables from blanket impls, and (unless we know its bounds
40/// will always be satisfied) picking the blanket impl will be wrong
41/// for at least *some* generic parameters. To make this concrete, if
42/// we have
43///
44/// ```rust, ignore
45/// trait AsDebug { type Out: fmt::Debug; fn debug(self) -> Self::Out; }
46/// impl<T: fmt::Debug> AsDebug for T {
47///     type Out = T;
48///     fn debug(self) -> fmt::Debug { self }
49/// }
50/// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
51/// ```
52///
53/// we can't just use the impl to resolve the `<T as AsDebug>` obligation
54/// -- a type from another crate (that doesn't implement `fmt::Debug`) could
55/// implement `AsDebug`.
56///
57/// Because where-clauses match the type exactly, multiple clauses can
58/// only match if there are unresolved variables, and we can mostly just
59/// report this ambiguity in that case. This is still a problem - we can't
60/// *do anything* with ambiguities that involve only regions. This is issue
61/// #21974.
62///
63/// If a single where-clause matches and there are no inference
64/// variables left, then it definitely matches and we can just select
65/// it.
66///
67/// In fact, we even select the where-clause when the obligation contains
68/// inference variables. The can lead to inference making "leaps of logic",
69/// for example in this situation:
70///
71/// ```rust, ignore
72/// pub trait Foo<T> { fn foo(&self) -> T; }
73/// impl<T> Foo<()> for T { fn foo(&self) { } }
74/// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
75///
76/// pub fn foo<T>(t: T) where T: Foo<bool> {
77///     println!("{:?}", <T as Foo<_>>::foo(&t));
78/// }
79/// fn main() { foo(false); }
80/// ```
81///
82/// Here the obligation `<T as Foo<$0>>` can be matched by both the blanket
83/// impl and the where-clause. We select the where-clause and unify `$0=bool`,
84/// so the program prints "false". However, if the where-clause is omitted,
85/// the blanket impl is selected, we unify `$0=()`, and the program prints
86/// "()".
87///
88/// Exactly the same issues apply to projection and object candidates, except
89/// that we can have both a projection candidate and a where-clause candidate
90/// for the same obligation. In that case either would do (except that
91/// different "leaps of logic" would occur if inference variables are
92/// present), and we just pick the where-clause. This is, for example,
93/// required for associated types to work in default impls, as the bounds
94/// are visible both as projection bounds and as where-clauses from the
95/// parameter environment.
96#[derive(PartialEq, Eq, Debug, Clone, TypeVisitable)]
97pub enum SelectionCandidate<'tcx> {
98    /// A builtin implementation for some specific traits, used in cases
99    /// where we cannot rely an ordinary library implementations.
100    ///
101    /// The most notable examples are `sized`, `Copy` and `Clone`. This is also
102    /// used for the `DiscriminantKind` and `Pointee` trait, both of which have
103    /// an associated type.
104    BuiltinCandidate {
105        /// `false` if there are no *further* obligations.
106        has_nested: bool,
107    },
108
109    /// Implementation of transmutability trait.
110    TransmutabilityCandidate,
111
112    ParamCandidate(ty::PolyTraitPredicate<'tcx>),
113    ImplCandidate(DefId),
114    AutoImplCandidate,
115
116    /// This is a trait matching with a projected type as `Self`, and we found
117    /// an applicable bound in the trait definition. The `usize` is an index
118    /// into the list returned by `tcx.item_bounds`.
119    ProjectionCandidate(usize),
120
121    /// Implementation of a `Fn`-family trait by one of the anonymous types
122    /// generated for an `||` expression.
123    ClosureCandidate {
124        is_const: bool,
125    },
126
127    /// Implementation of an `AsyncFn`-family trait by one of the anonymous types
128    /// generated for an `async ||` expression.
129    AsyncClosureCandidate,
130
131    /// Implementation of the `AsyncFnKindHelper` helper trait, which
132    /// is used internally to delay computation for async closures until after
133    /// upvar analysis is performed in HIR typeck.
134    AsyncFnKindHelperCandidate,
135
136    /// Implementation of a `Coroutine` trait by one of the anonymous types
137    /// generated for a coroutine.
138    CoroutineCandidate,
139
140    /// Implementation of a `Future` trait by one of the coroutine types
141    /// generated for an async construct.
142    FutureCandidate,
143
144    /// Implementation of an `Iterator` trait by one of the coroutine types
145    /// generated for a `gen` construct.
146    IteratorCandidate,
147
148    /// Implementation of an `AsyncIterator` trait by one of the coroutine types
149    /// generated for a `async gen` construct.
150    AsyncIteratorCandidate,
151
152    /// Implementation of a `Fn`-family trait by one of the anonymous
153    /// types generated for a fn pointer type (e.g., `fn(int) -> int`)
154    FnPointerCandidate,
155
156    TraitAliasCandidate,
157
158    /// Matching `dyn Trait` with a supertrait of `Trait`. The index is the
159    /// position in the iterator returned by
160    /// `rustc_infer::traits::util::supertraits`.
161    ObjectCandidate(usize),
162
163    /// Perform trait upcasting coercion of `dyn Trait` to a supertrait of `Trait`.
164    /// The index is the position in the iterator returned by
165    /// `rustc_infer::traits::util::supertraits`.
166    TraitUpcastingUnsizeCandidate(usize),
167
168    BuiltinObjectCandidate,
169
170    BuiltinUnsizeCandidate,
171
172    BikeshedGuaranteedNoDropCandidate,
173}
174
175/// The result of trait evaluation. The order is important
176/// here as the evaluation of a list is the maximum of the
177/// evaluations.
178///
179/// The evaluation results are ordered:
180///     - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
181///       implies `EvaluatedToAmbig` implies `EvaluatedToAmbigStackDependent`
182///     - the "union" of evaluation results is equal to their maximum -
183///     all the "potential success" candidates can potentially succeed,
184///     so they are noops when unioned with a definite error, and within
185///     the categories it's easy to see that the unions are correct.
186#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, HashStable)]
187pub enum EvaluationResult {
188    /// Evaluation successful.
189    EvaluatedToOk,
190    /// Evaluation successful, but there were unevaluated region obligations.
191    EvaluatedToOkModuloRegions,
192    /// Evaluation successful, but need to rerun because opaque types got
193    /// hidden types assigned without it being known whether the opaque types
194    /// are within their defining scope
195    EvaluatedToOkModuloOpaqueTypes,
196    /// Evaluation is known to be ambiguous -- it *might* hold for some
197    /// assignment of inference variables, but it might not.
198    ///
199    /// While this has the same meaning as `EvaluatedToAmbigStackDependent` -- we can't
200    /// know whether this obligation holds or not -- it is the result we
201    /// would get with an empty stack, and therefore is cacheable.
202    EvaluatedToAmbig,
203    /// Evaluation failed because of recursion involving inference
204    /// variables. We are somewhat imprecise there, so we don't actually
205    /// know the real result.
206    ///
207    /// This can't be trivially cached because the result depends on the
208    /// stack results.
209    EvaluatedToAmbigStackDependent,
210    /// Evaluation failed.
211    EvaluatedToErr,
212}
213
214impl EvaluationResult {
215    /// Returns `true` if this evaluation result is known to apply, even
216    /// considering outlives constraints.
217    pub fn must_apply_considering_regions(self) -> bool {
218        self == EvaluatedToOk
219    }
220
221    /// Returns `true` if this evaluation result is known to apply, ignoring
222    /// outlives constraints.
223    pub fn must_apply_modulo_regions(self) -> bool {
224        self <= EvaluatedToOkModuloRegions
225    }
226
227    pub fn may_apply(self) -> bool {
228        match self {
229            EvaluatedToOkModuloOpaqueTypes
230            | EvaluatedToOk
231            | EvaluatedToOkModuloRegions
232            | EvaluatedToAmbig
233            | EvaluatedToAmbigStackDependent => true,
234
235            EvaluatedToErr => false,
236        }
237    }
238
239    pub fn is_stack_dependent(self) -> bool {
240        match self {
241            EvaluatedToAmbigStackDependent => true,
242
243            EvaluatedToOkModuloOpaqueTypes
244            | EvaluatedToOk
245            | EvaluatedToOkModuloRegions
246            | EvaluatedToAmbig
247            | EvaluatedToErr => false,
248        }
249    }
250}
251
252/// Indicates that trait evaluation caused overflow and in which pass.
253#[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable)]
254pub enum OverflowError {
255    Error(ErrorGuaranteed),
256    Canonical,
257}
258
259impl From<ErrorGuaranteed> for OverflowError {
260    fn from(e: ErrorGuaranteed) -> OverflowError {
261        OverflowError::Error(e)
262    }
263}
264
265impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
266    fn from(overflow_error: OverflowError) -> SelectionError<'tcx> {
267        match overflow_error {
268            OverflowError::Error(e) => SelectionError::Overflow(OverflowError::Error(e)),
269            OverflowError::Canonical => SelectionError::Overflow(OverflowError::Canonical),
270        }
271    }
272}