]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
1 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT |
2 | // file at the top-level directory of this distribution and at | |
3 | // http://rust-lang.org/COPYRIGHT. | |
4 | // | |
5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | |
8 | // option. This file may not be copied, modified, or distributed | |
9 | // except according to those terms. | |
10 | ||
c34b1796 | 11 | //! See `README.md` for high-level documentation |
1a4d82fc JJ |
12 | |
13 | pub use self::MethodMatchResult::*; | |
14 | pub use self::MethodMatchedData::*; | |
15 | use self::SelectionCandidate::*; | |
16 | use self::BuiltinBoundConditions::*; | |
17 | use self::EvaluationResult::*; | |
18 | ||
c34b1796 AL |
19 | use super::coherence; |
20 | use super::DerivedObligationCause; | |
21 | use super::project; | |
22 | use super::project::{normalize_with_depth, Normalized}; | |
85aaf69f | 23 | use super::{PredicateObligation, TraitObligation, ObligationCause}; |
c34b1796 AL |
24 | use super::report_overflow_error; |
25 | use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation}; | |
26 | use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch}; | |
d9579d0f AL |
27 | use super::{ObjectCastObligation, Obligation}; |
28 | use super::TraitNotObjectSafe; | |
e9174d1e | 29 | use super::RFC1214Warning; |
c34b1796 AL |
30 | use super::Selection; |
31 | use super::SelectionResult; | |
85aaf69f | 32 | use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure, |
c34b1796 | 33 | VtableFnPointer, VtableObject, VtableDefaultImpl}; |
62682a34 SL |
34 | use super::{VtableImplData, VtableObjectData, VtableBuiltinData, |
35 | VtableClosureData, VtableDefaultImplData}; | |
1a4d82fc | 36 | use super::object_safety; |
c34b1796 | 37 | use super::util; |
1a4d82fc | 38 | |
b039eaaf | 39 | use middle::def_id::DefId; |
1a4d82fc | 40 | use middle::infer; |
92a42be0 | 41 | use middle::infer::{InferCtxt, TypeFreshener, TypeOrigin}; |
e9174d1e SL |
42 | use middle::subst::{Subst, Substs, TypeSpace}; |
43 | use middle::ty::{self, ToPredicate, RegionEscape, ToPolyTraitRef, Ty, HasTypeFlags}; | |
44 | use middle::ty::fast_reject; | |
45 | use middle::ty::fold::TypeFoldable; | |
46 | use middle::ty::relate::TypeRelation; | |
62682a34 | 47 | |
1a4d82fc | 48 | use std::cell::RefCell; |
62682a34 | 49 | use std::fmt; |
1a4d82fc | 50 | use std::rc::Rc; |
e9174d1e SL |
51 | use syntax::abi; |
52 | use rustc_front::hir; | |
1a4d82fc | 53 | use util::common::ErrorReported; |
c34b1796 | 54 | use util::nodemap::FnvHashMap; |
1a4d82fc JJ |
55 | |
56 | pub struct SelectionContext<'cx, 'tcx:'cx> { | |
57 | infcx: &'cx InferCtxt<'cx, 'tcx>, | |
1a4d82fc JJ |
58 | |
59 | /// Freshener used specifically for skolemizing entries on the | |
60 | /// obligation stack. This ensures that all entries on the stack | |
61 | /// at one time will have the same set of skolemized entries, | |
62 | /// which is important for checking for trait bounds that | |
63 | /// recursively require themselves. | |
64 | freshener: TypeFreshener<'cx, 'tcx>, | |
65 | ||
66 | /// If true, indicates that the evaluation should be conservative | |
67 | /// and consider the possibility of types outside this crate. | |
68 | /// This comes up primarily when resolving ambiguity. Imagine | |
69 | /// there is some trait reference `$0 : Bar` where `$0` is an | |
70 | /// inference variable. If `intercrate` is true, then we can never | |
71 | /// say for sure that this reference is not implemented, even if | |
72 | /// there are *no impls at all for `Bar`*, because `$0` could be | |
73 | /// bound to some type that in a downstream crate that implements | |
74 | /// `Bar`. This is the suitable mode for coherence. Elsewhere, | |
75 | /// though, we set this to false, because we are only interested | |
76 | /// in types that the user could actually have written --- in | |
77 | /// other words, we consider `$0 : Bar` to be unimplemented if | |
78 | /// there is no type that the user could *actually name* that | |
79 | /// would satisfy it. This avoids crippling inference, basically. | |
c1a9b12d | 80 | |
1a4d82fc JJ |
81 | intercrate: bool, |
82 | } | |
83 | ||
84 | // A stack that walks back up the stack frame. | |
85 | struct TraitObligationStack<'prev, 'tcx: 'prev> { | |
86 | obligation: &'prev TraitObligation<'tcx>, | |
87 | ||
88 | /// Trait ref from `obligation` but skolemized with the | |
89 | /// selection-context's freshener. Used to check for recursion. | |
90 | fresh_trait_ref: ty::PolyTraitRef<'tcx>, | |
91 | ||
c34b1796 | 92 | previous: TraitObligationStackList<'prev, 'tcx>, |
1a4d82fc JJ |
93 | } |
94 | ||
95 | #[derive(Clone)] | |
96 | pub struct SelectionCache<'tcx> { | |
d9579d0f | 97 | hashmap: RefCell<FnvHashMap<ty::TraitRef<'tcx>, |
c34b1796 | 98 | SelectionResult<'tcx, SelectionCandidate<'tcx>>>>, |
1a4d82fc JJ |
99 | } |
100 | ||
101 | pub enum MethodMatchResult { | |
102 | MethodMatched(MethodMatchedData), | |
e9174d1e | 103 | MethodAmbiguous(/* list of impls that could apply */ Vec<DefId>), |
1a4d82fc JJ |
104 | MethodDidNotMatch, |
105 | } | |
106 | ||
c34b1796 | 107 | #[derive(Copy, Clone, Debug)] |
1a4d82fc JJ |
108 | pub enum MethodMatchedData { |
109 | // In the case of a precise match, we don't really need to store | |
110 | // how the match was found. So don't. | |
111 | PreciseMethodMatch, | |
112 | ||
113 | // In the case of a coercion, we need to know the precise impl so | |
114 | // that we can determine the type to which things were coerced. | |
e9174d1e | 115 | CoerciveMethodMatch(/* impl we matched */ DefId) |
1a4d82fc JJ |
116 | } |
117 | ||
118 | /// The selection process begins by considering all impls, where | |
119 | /// clauses, and so forth that might resolve an obligation. Sometimes | |
120 | /// we'll be able to say definitively that (e.g.) an impl does not | |
c34b1796 | 121 | /// apply to the obligation: perhaps it is defined for `usize` but the |
1a4d82fc JJ |
122 | /// obligation is for `int`. In that case, we drop the impl out of the |
123 | /// list. But the other cases are considered *candidates*. | |
124 | /// | |
d9579d0f AL |
125 | /// For selection to succeed, there must be exactly one matching |
126 | /// candidate. If the obligation is fully known, this is guaranteed | |
127 | /// by coherence. However, if the obligation contains type parameters | |
128 | /// or variables, there may be multiple such impls. | |
1a4d82fc | 129 | /// |
d9579d0f AL |
130 | /// It is not a real problem if multiple matching impls exist because |
131 | /// of type variables - it just means the obligation isn't sufficiently | |
132 | /// elaborated. In that case we report an ambiguity, and the caller can | |
133 | /// try again after more type information has been gathered or report a | |
134 | /// "type annotations required" error. | |
135 | /// | |
136 | /// However, with type parameters, this can be a real problem - type | |
137 | /// parameters don't unify with regular types, but they *can* unify | |
138 | /// with variables from blanket impls, and (unless we know its bounds | |
139 | /// will always be satisfied) picking the blanket impl will be wrong | |
140 | /// for at least *some* substitutions. To make this concrete, if we have | |
141 | /// | |
142 | /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; } | |
143 | /// impl<T: fmt::Debug> AsDebug for T { | |
144 | /// type Out = T; | |
145 | /// fn debug(self) -> fmt::Debug { self } | |
146 | /// } | |
147 | /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); } | |
148 | /// | |
149 | /// we can't just use the impl to resolve the <T as AsDebug> obligation | |
150 | /// - a type from another crate (that doesn't implement fmt::Debug) could | |
151 | /// implement AsDebug. | |
152 | /// | |
153 | /// Because where-clauses match the type exactly, multiple clauses can | |
154 | /// only match if there are unresolved variables, and we can mostly just | |
155 | /// report this ambiguity in that case. This is still a problem - we can't | |
156 | /// *do anything* with ambiguities that involve only regions. This is issue | |
157 | /// #21974. | |
158 | /// | |
159 | /// If a single where-clause matches and there are no inference | |
160 | /// variables left, then it definitely matches and we can just select | |
161 | /// it. | |
162 | /// | |
163 | /// In fact, we even select the where-clause when the obligation contains | |
164 | /// inference variables. The can lead to inference making "leaps of logic", | |
165 | /// for example in this situation: | |
166 | /// | |
167 | /// pub trait Foo<T> { fn foo(&self) -> T; } | |
168 | /// impl<T> Foo<()> for T { fn foo(&self) { } } | |
169 | /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } } | |
170 | /// | |
171 | /// pub fn foo<T>(t: T) where T: Foo<bool> { | |
172 | /// println!("{:?}", <T as Foo<_>>::foo(&t)); | |
173 | /// } | |
174 | /// fn main() { foo(false); } | |
175 | /// | |
176 | /// Here the obligation <T as Foo<$0>> can be matched by both the blanket | |
177 | /// impl and the where-clause. We select the where-clause and unify $0=bool, | |
178 | /// so the program prints "false". However, if the where-clause is omitted, | |
179 | /// the blanket impl is selected, we unify $0=(), and the program prints | |
180 | /// "()". | |
181 | /// | |
182 | /// Exactly the same issues apply to projection and object candidates, except | |
183 | /// that we can have both a projection candidate and a where-clause candidate | |
184 | /// for the same obligation. In that case either would do (except that | |
185 | /// different "leaps of logic" would occur if inference variables are | |
e9174d1e | 186 | /// present), and we just pick the where-clause. This is, for example, |
d9579d0f AL |
187 | /// required for associated types to work in default impls, as the bounds |
188 | /// are visible both as projection bounds and as where-clauses from the | |
189 | /// parameter environment. | |
85aaf69f | 190 | #[derive(PartialEq,Eq,Debug,Clone)] |
1a4d82fc JJ |
191 | enum SelectionCandidate<'tcx> { |
192 | BuiltinCandidate(ty::BuiltinBound), | |
193 | ParamCandidate(ty::PolyTraitRef<'tcx>), | |
e9174d1e SL |
194 | ImplCandidate(DefId), |
195 | DefaultImplCandidate(DefId), | |
196 | DefaultImplObjectCandidate(DefId), | |
1a4d82fc JJ |
197 | |
198 | /// This is a trait matching with a projected type as `Self`, and | |
199 | /// we found an applicable bound in the trait definition. | |
200 | ProjectionCandidate, | |
201 | ||
202 | /// Implementation of a `Fn`-family trait by one of the | |
203 | /// anonymous types generated for a `||` expression. | |
e9174d1e | 204 | ClosureCandidate(/* closure */ DefId, &'tcx ty::ClosureSubsts<'tcx>), |
1a4d82fc JJ |
205 | |
206 | /// Implementation of a `Fn`-family trait by one of the anonymous | |
207 | /// types generated for a fn pointer type (e.g., `fn(int)->int`) | |
208 | FnPointerCandidate, | |
209 | ||
210 | ObjectCandidate, | |
211 | ||
c34b1796 AL |
212 | BuiltinObjectCandidate, |
213 | ||
d9579d0f AL |
214 | BuiltinUnsizeCandidate, |
215 | ||
1a4d82fc JJ |
216 | ErrorCandidate, |
217 | } | |
218 | ||
219 | struct SelectionCandidateSet<'tcx> { | |
220 | // a list of candidates that definitely apply to the current | |
221 | // obligation (meaning: types unify). | |
222 | vec: Vec<SelectionCandidate<'tcx>>, | |
223 | ||
224 | // if this is true, then there were candidates that might or might | |
225 | // not have applied, but we couldn't tell. This occurs when some | |
226 | // of the input types are type variables, in which case there are | |
227 | // various "builtin" rules that might or might not trigger. | |
228 | ambiguous: bool, | |
229 | } | |
230 | ||
231 | enum BuiltinBoundConditions<'tcx> { | |
c34b1796 | 232 | If(ty::Binder<Vec<Ty<'tcx>>>), |
1a4d82fc JJ |
233 | ParameterBuiltin, |
234 | AmbiguousBuiltin | |
235 | } | |
236 | ||
92a42be0 SL |
237 | #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] |
238 | /// The result of trait evaluation. The order is important | |
239 | /// here as the evaluation of a list is the maximum of the | |
240 | /// evaluations. | |
241 | enum EvaluationResult { | |
242 | /// Evaluation successful | |
1a4d82fc | 243 | EvaluatedToOk, |
92a42be0 SL |
244 | /// Evaluation failed because of recursion - treated as ambiguous |
245 | EvaluatedToUnknown, | |
246 | /// Evaluation is known to be ambiguous | |
1a4d82fc | 247 | EvaluatedToAmbig, |
92a42be0 SL |
248 | /// Evaluation failed |
249 | EvaluatedToErr, | |
250 | } | |
251 | ||
252 | #[derive(Clone)] | |
253 | pub struct EvaluationCache<'tcx> { | |
254 | hashmap: RefCell<FnvHashMap<ty::PolyTraitRef<'tcx>, EvaluationResult>> | |
1a4d82fc JJ |
255 | } |
256 | ||
257 | impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { | |
c1a9b12d | 258 | pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) |
1a4d82fc JJ |
259 | -> SelectionContext<'cx, 'tcx> { |
260 | SelectionContext { | |
261 | infcx: infcx, | |
1a4d82fc JJ |
262 | freshener: infcx.freshener(), |
263 | intercrate: false, | |
264 | } | |
265 | } | |
266 | ||
c1a9b12d | 267 | pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) |
1a4d82fc JJ |
268 | -> SelectionContext<'cx, 'tcx> { |
269 | SelectionContext { | |
270 | infcx: infcx, | |
1a4d82fc JJ |
271 | freshener: infcx.freshener(), |
272 | intercrate: true, | |
273 | } | |
274 | } | |
275 | ||
276 | pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> { | |
277 | self.infcx | |
278 | } | |
279 | ||
280 | pub fn tcx(&self) -> &'cx ty::ctxt<'tcx> { | |
281 | self.infcx.tcx | |
282 | } | |
283 | ||
284 | pub fn param_env(&self) -> &'cx ty::ParameterEnvironment<'cx, 'tcx> { | |
c1a9b12d | 285 | self.infcx.param_env() |
1a4d82fc JJ |
286 | } |
287 | ||
c1a9b12d SL |
288 | pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> { |
289 | self.infcx | |
85aaf69f SL |
290 | } |
291 | ||
1a4d82fc JJ |
292 | /////////////////////////////////////////////////////////////////////////// |
293 | // Selection | |
294 | // | |
295 | // The selection phase tries to identify *how* an obligation will | |
296 | // be resolved. For example, it will identify which impl or | |
297 | // parameter bound is to be used. The process can be inconclusive | |
298 | // if the self type in the obligation is not fully inferred. Selection | |
299 | // can result in an error in one of two ways: | |
300 | // | |
301 | // 1. If no applicable impl or parameter bound can be found. | |
302 | // 2. If the output type parameters in the obligation do not match | |
303 | // those specified by the impl/bound. For example, if the obligation | |
304 | // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies | |
305 | // `impl<T> Iterable<T> for Vec<T>`, than an error would result. | |
306 | ||
85aaf69f SL |
307 | /// Attempts to satisfy the obligation. If successful, this will affect the surrounding |
308 | /// type environment by performing unification. | |
1a4d82fc JJ |
309 | pub fn select(&mut self, obligation: &TraitObligation<'tcx>) |
310 | -> SelectionResult<'tcx, Selection<'tcx>> { | |
62682a34 | 311 | debug!("select({:?})", obligation); |
1a4d82fc JJ |
312 | assert!(!obligation.predicate.has_escaping_regions()); |
313 | ||
c34b1796 | 314 | let stack = self.push_stack(TraitObligationStackList::empty(), obligation); |
1a4d82fc | 315 | match try!(self.candidate_from_obligation(&stack)) { |
85aaf69f SL |
316 | None => { |
317 | self.consider_unification_despite_ambiguity(obligation); | |
318 | Ok(None) | |
319 | } | |
1a4d82fc JJ |
320 | Some(candidate) => Ok(Some(try!(self.confirm_candidate(obligation, candidate)))), |
321 | } | |
322 | } | |
323 | ||
85aaf69f SL |
324 | /// In the particular case of unboxed closure obligations, we can |
325 | /// sometimes do some amount of unification for the | |
326 | /// argument/return types even though we can't yet fully match obligation. | |
327 | /// The particular case we are interesting in is an obligation of the form: | |
328 | /// | |
329 | /// C : FnFoo<A> | |
330 | /// | |
331 | /// where `C` is an unboxed closure type and `FnFoo` is one of the | |
332 | /// `Fn` traits. Because we know that users cannot write impls for closure types | |
333 | /// themselves, the only way that `C : FnFoo` can fail to match is under two | |
334 | /// conditions: | |
335 | /// | |
336 | /// 1. The closure kind for `C` is not yet known, because inference isn't complete. | |
337 | /// 2. The closure kind for `C` *is* known, but doesn't match what is needed. | |
338 | /// For example, `C` may be a `FnOnce` closure, but a `Fn` closure is needed. | |
339 | /// | |
340 | /// In either case, we always know what argument types are | |
341 | /// expected by `C`, no matter what kind of `Fn` trait it | |
342 | /// eventually matches. So we can go ahead and unify the argument | |
343 | /// types, even though the end result is ambiguous. | |
344 | /// | |
345 | /// Note that this is safe *even if* the trait would never be | |
346 | /// matched (case 2 above). After all, in that case, an error will | |
347 | /// result, so it kind of doesn't matter what we do --- unifying | |
348 | /// the argument types can only be helpful to the user, because | |
349 | /// once they patch up the kind of closure that is expected, the | |
350 | /// argment types won't really change. | |
351 | fn consider_unification_despite_ambiguity(&mut self, obligation: &TraitObligation<'tcx>) { | |
352 | // Is this a `C : FnFoo(...)` trait reference for some trait binding `FnFoo`? | |
353 | match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) { | |
354 | Some(_) => { } | |
355 | None => { return; } | |
356 | } | |
357 | ||
358 | // Is the self-type a closure type? We ignore bindings here | |
359 | // because if it is a closure type, it must be a closure type from | |
360 | // within this current fn, and hence none of the higher-ranked | |
361 | // lifetimes can appear inside the self-type. | |
c34b1796 | 362 | let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder()); |
85aaf69f | 363 | let (closure_def_id, substs) = match self_ty.sty { |
c1a9b12d | 364 | ty::TyClosure(id, ref substs) => (id, substs), |
85aaf69f SL |
365 | _ => { return; } |
366 | }; | |
367 | assert!(!substs.has_escaping_regions()); | |
368 | ||
62682a34 SL |
369 | // It is OK to call the unnormalized variant here - this is only |
370 | // reached for TyClosure: Fn inputs where the closure kind is | |
371 | // still unknown, which should only occur in typeck where the | |
372 | // closure type is already normalized. | |
373 | let closure_trait_ref = self.closure_trait_ref_unnormalized(obligation, | |
374 | closure_def_id, | |
375 | substs); | |
376 | ||
85aaf69f SL |
377 | match self.confirm_poly_trait_refs(obligation.cause.clone(), |
378 | obligation.predicate.to_poly_trait_ref(), | |
379 | closure_trait_ref) { | |
380 | Ok(()) => { } | |
381 | Err(_) => { /* Silently ignore errors. */ } | |
382 | } | |
383 | } | |
384 | ||
1a4d82fc JJ |
385 | /////////////////////////////////////////////////////////////////////////// |
386 | // EVALUATION | |
387 | // | |
388 | // Tests whether an obligation can be selected or whether an impl | |
389 | // can be applied to particular types. It skips the "confirmation" | |
390 | // step and hence completely ignores output type parameters. | |
391 | // | |
392 | // The result is "true" if the obligation *may* hold and "false" if | |
393 | // we can be sure it does not. | |
394 | ||
92a42be0 | 395 | |
1a4d82fc JJ |
396 | /// Evaluates whether the obligation `obligation` can be satisfied (by any means). |
397 | pub fn evaluate_obligation(&mut self, | |
398 | obligation: &PredicateObligation<'tcx>) | |
399 | -> bool | |
400 | { | |
62682a34 SL |
401 | debug!("evaluate_obligation({:?})", |
402 | obligation); | |
1a4d82fc | 403 | |
92a42be0 SL |
404 | self.infcx.probe(|_| { |
405 | self.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation) | |
406 | .may_apply() | |
407 | }) | |
1a4d82fc JJ |
408 | } |
409 | ||
92a42be0 SL |
410 | /// Evaluates whether the obligation `obligation` can be satisfied, |
411 | /// and returns `false` if not certain. However, this is not entirely | |
412 | /// accurate if inference variables are involved. | |
413 | pub fn evaluate_obligation_conservatively(&mut self, | |
414 | obligation: &PredicateObligation<'tcx>) | |
415 | -> bool | |
1a4d82fc | 416 | { |
92a42be0 SL |
417 | debug!("evaluate_obligation_conservatively({:?})", |
418 | obligation); | |
419 | ||
420 | self.infcx.probe(|_| { | |
421 | self.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation) | |
422 | == EvaluatedToOk | |
423 | }) | |
1a4d82fc JJ |
424 | } |
425 | ||
92a42be0 SL |
426 | /// Evaluates the predicates in `predicates` recursively. Note that |
427 | /// this applies projections in the predicates, and therefore | |
428 | /// is run within an inference probe. | |
1a4d82fc | 429 | fn evaluate_predicates_recursively<'a,'o,I>(&mut self, |
c34b1796 | 430 | stack: TraitObligationStackList<'o, 'tcx>, |
85aaf69f | 431 | predicates: I) |
92a42be0 | 432 | -> EvaluationResult |
1a4d82fc JJ |
433 | where I : Iterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a |
434 | { | |
435 | let mut result = EvaluatedToOk; | |
436 | for obligation in predicates { | |
92a42be0 SL |
437 | let eval = self.evaluate_predicate_recursively(stack, obligation); |
438 | debug!("evaluate_predicate_recursively({:?}) = {:?}", | |
439 | obligation, eval); | |
440 | match eval { | |
441 | EvaluatedToErr => { return EvaluatedToErr; } | |
1a4d82fc | 442 | EvaluatedToAmbig => { result = EvaluatedToAmbig; } |
92a42be0 SL |
443 | EvaluatedToUnknown => { |
444 | if result < EvaluatedToUnknown { | |
445 | result = EvaluatedToUnknown; | |
446 | } | |
447 | } | |
1a4d82fc JJ |
448 | EvaluatedToOk => { } |
449 | } | |
450 | } | |
451 | result | |
452 | } | |
453 | ||
454 | fn evaluate_predicate_recursively<'o>(&mut self, | |
c34b1796 | 455 | previous_stack: TraitObligationStackList<'o, 'tcx>, |
1a4d82fc | 456 | obligation: &PredicateObligation<'tcx>) |
92a42be0 | 457 | -> EvaluationResult |
1a4d82fc | 458 | { |
62682a34 SL |
459 | debug!("evaluate_predicate_recursively({:?})", |
460 | obligation); | |
461 | ||
462 | // Check the cache from the tcx of predicates that we know | |
463 | // have been proven elsewhere. This cache only contains | |
464 | // predicates that are global in scope and hence unaffected by | |
465 | // the current environment. | |
e9174d1e SL |
466 | let w = RFC1214Warning(false); |
467 | if self.tcx().fulfilled_predicates.borrow().is_duplicate(w, &obligation.predicate) { | |
62682a34 SL |
468 | return EvaluatedToOk; |
469 | } | |
1a4d82fc JJ |
470 | |
471 | match obligation.predicate { | |
472 | ty::Predicate::Trait(ref t) => { | |
473 | assert!(!t.has_escaping_regions()); | |
474 | let obligation = obligation.with(t.clone()); | |
475 | self.evaluate_obligation_recursively(previous_stack, &obligation) | |
476 | } | |
477 | ||
478 | ty::Predicate::Equate(ref p) => { | |
92a42be0 SL |
479 | // does this code ever run? |
480 | match self.infcx.equality_predicate(obligation.cause.span, p) { | |
1a4d82fc | 481 | Ok(()) => EvaluatedToOk, |
92a42be0 | 482 | Err(_) => EvaluatedToErr |
1a4d82fc JJ |
483 | } |
484 | } | |
485 | ||
e9174d1e SL |
486 | ty::Predicate::WellFormed(ty) => { |
487 | match ty::wf::obligations(self.infcx, obligation.cause.body_id, | |
488 | ty, obligation.cause.span, | |
489 | obligation.cause.code.is_rfc1214()) { | |
490 | Some(obligations) => | |
491 | self.evaluate_predicates_recursively(previous_stack, obligations.iter()), | |
492 | None => | |
493 | EvaluatedToAmbig, | |
494 | } | |
495 | } | |
496 | ||
1a4d82fc JJ |
497 | ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => { |
498 | // we do not consider region relationships when | |
499 | // evaluating trait matches | |
500 | EvaluatedToOk | |
501 | } | |
502 | ||
e9174d1e SL |
503 | ty::Predicate::ObjectSafe(trait_def_id) => { |
504 | if object_safety::is_object_safe(self.tcx(), trait_def_id) { | |
505 | EvaluatedToOk | |
506 | } else { | |
92a42be0 | 507 | EvaluatedToErr |
e9174d1e SL |
508 | } |
509 | } | |
510 | ||
1a4d82fc | 511 | ty::Predicate::Projection(ref data) => { |
92a42be0 SL |
512 | let project_obligation = obligation.with(data.clone()); |
513 | match project::poly_project_and_unify_type(self, &project_obligation) { | |
514 | Ok(Some(subobligations)) => { | |
515 | self.evaluate_predicates_recursively(previous_stack, | |
516 | subobligations.iter()) | |
1a4d82fc | 517 | } |
92a42be0 SL |
518 | Ok(None) => { |
519 | EvaluatedToAmbig | |
520 | } | |
521 | Err(_) => { | |
522 | EvaluatedToErr | |
523 | } | |
524 | } | |
1a4d82fc JJ |
525 | } |
526 | } | |
527 | } | |
528 | ||
529 | fn evaluate_obligation_recursively<'o>(&mut self, | |
c34b1796 | 530 | previous_stack: TraitObligationStackList<'o, 'tcx>, |
1a4d82fc | 531 | obligation: &TraitObligation<'tcx>) |
92a42be0 | 532 | -> EvaluationResult |
1a4d82fc | 533 | { |
62682a34 SL |
534 | debug!("evaluate_obligation_recursively({:?})", |
535 | obligation); | |
1a4d82fc | 536 | |
c34b1796 | 537 | let stack = self.push_stack(previous_stack, obligation); |
92a42be0 SL |
538 | let fresh_trait_ref = stack.fresh_trait_ref; |
539 | if let Some(result) = self.check_evaluation_cache(fresh_trait_ref) { | |
540 | debug!("CACHE HIT: EVAL({:?})={:?}", | |
541 | fresh_trait_ref, | |
542 | result); | |
543 | return result; | |
544 | } | |
1a4d82fc JJ |
545 | |
546 | let result = self.evaluate_stack(&stack); | |
547 | ||
92a42be0 SL |
548 | debug!("CACHE MISS: EVAL({:?})={:?}", |
549 | fresh_trait_ref, | |
550 | result); | |
551 | self.insert_evaluation_cache(fresh_trait_ref, result); | |
552 | ||
1a4d82fc JJ |
553 | result |
554 | } | |
555 | ||
556 | fn evaluate_stack<'o>(&mut self, | |
557 | stack: &TraitObligationStack<'o, 'tcx>) | |
92a42be0 | 558 | -> EvaluationResult |
1a4d82fc JJ |
559 | { |
560 | // In intercrate mode, whenever any of the types are unbound, | |
561 | // there can always be an impl. Even if there are no impls in | |
562 | // this crate, perhaps the type would be unified with | |
563 | // something from another crate that does provide an impl. | |
564 | // | |
565 | // In intracrate mode, we must still be conservative. The reason is | |
566 | // that we want to avoid cycles. Imagine an impl like: | |
567 | // | |
568 | // impl<T:Eq> Eq for Vec<T> | |
569 | // | |
570 | // and a trait reference like `$0 : Eq` where `$0` is an | |
571 | // unbound variable. When we evaluate this trait-reference, we | |
572 | // will unify `$0` with `Vec<$1>` (for some fresh variable | |
573 | // `$1`), on the condition that `$1 : Eq`. We will then wind | |
574 | // up with many candidates (since that are other `Eq` impls | |
575 | // that apply) and try to winnow things down. This results in | |
576 | // a recursive evaluation that `$1 : Eq` -- as you can | |
577 | // imagine, this is just where we started. To avoid that, we | |
578 | // check for unbound variables and return an ambiguous (hence possible) | |
579 | // match if we've seen this trait before. | |
580 | // | |
581 | // This suffices to allow chains like `FnMut` implemented in | |
582 | // terms of `Fn` etc, but we could probably make this more | |
583 | // precise still. | |
584 | let input_types = stack.fresh_trait_ref.0.input_types(); | |
c1a9b12d | 585 | let unbound_input_types = input_types.iter().any(|ty| ty.is_fresh()); |
92a42be0 SL |
586 | if unbound_input_types && self.intercrate { |
587 | debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous", | |
588 | stack.fresh_trait_ref); | |
589 | return EvaluatedToAmbig; | |
590 | } | |
591 | if unbound_input_types && | |
1a4d82fc | 592 | stack.iter().skip(1).any( |
c34b1796 | 593 | |prev| self.match_fresh_trait_refs(&stack.fresh_trait_ref, |
92a42be0 | 594 | &prev.fresh_trait_ref)) |
1a4d82fc | 595 | { |
92a42be0 | 596 | debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up", |
62682a34 | 597 | stack.fresh_trait_ref); |
92a42be0 | 598 | return EvaluatedToUnknown; |
1a4d82fc JJ |
599 | } |
600 | ||
601 | // If there is any previous entry on the stack that precisely | |
602 | // matches this obligation, then we can assume that the | |
603 | // obligation is satisfied for now (still all other conditions | |
604 | // must be met of course). One obvious case this comes up is | |
605 | // marker traits like `Send`. Think of a linked list: | |
606 | // | |
607 | // struct List<T> { data: T, next: Option<Box<List<T>>> { | |
608 | // | |
609 | // `Box<List<T>>` will be `Send` if `T` is `Send` and | |
610 | // `Option<Box<List<T>>>` is `Send`, and in turn | |
611 | // `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is | |
612 | // `Send`. | |
613 | // | |
614 | // Note that we do this comparison using the `fresh_trait_ref` | |
615 | // fields. Because these have all been skolemized using | |
616 | // `self.freshener`, we can be sure that (a) this will not | |
617 | // affect the inferencer state and (b) that if we see two | |
618 | // skolemized types with the same index, they refer to the | |
619 | // same unbound type variable. | |
620 | if | |
621 | stack.iter() | |
622 | .skip(1) // skip top-most frame | |
623 | .any(|prev| stack.fresh_trait_ref == prev.fresh_trait_ref) | |
624 | { | |
62682a34 SL |
625 | debug!("evaluate_stack({:?}) --> recursive", |
626 | stack.fresh_trait_ref); | |
1a4d82fc JJ |
627 | return EvaluatedToOk; |
628 | } | |
629 | ||
630 | match self.candidate_from_obligation(stack) { | |
92a42be0 | 631 | Ok(Some(c)) => self.evaluate_candidate(stack, &c), |
1a4d82fc | 632 | Ok(None) => EvaluatedToAmbig, |
92a42be0 | 633 | Err(..) => EvaluatedToErr |
1a4d82fc JJ |
634 | } |
635 | } | |
636 | ||
92a42be0 SL |
637 | /// Further evaluate `candidate` to decide whether all type parameters match and whether nested |
638 | /// obligations are met. Returns true if `candidate` remains viable after this further | |
639 | /// scrutiny. | |
640 | fn evaluate_candidate<'o>(&mut self, | |
641 | stack: &TraitObligationStack<'o, 'tcx>, | |
642 | candidate: &SelectionCandidate<'tcx>) | |
643 | -> EvaluationResult | |
1a4d82fc | 644 | { |
92a42be0 SL |
645 | debug!("evaluate_candidate: depth={} candidate={:?}", |
646 | stack.obligation.recursion_depth, candidate); | |
647 | let result = self.infcx.probe(|_| { | |
648 | let candidate = (*candidate).clone(); | |
649 | match self.confirm_candidate(stack.obligation, candidate) { | |
650 | Ok(selection) => { | |
651 | self.evaluate_predicates_recursively( | |
652 | stack.list(), | |
653 | selection.nested_obligations().iter()) | |
1a4d82fc | 654 | } |
92a42be0 | 655 | Err(..) => EvaluatedToErr |
1a4d82fc | 656 | } |
92a42be0 SL |
657 | }); |
658 | debug!("evaluate_candidate: depth={} result={:?}", | |
659 | stack.obligation.recursion_depth, result); | |
660 | result | |
661 | } | |
662 | ||
663 | fn pick_evaluation_cache(&self) -> &EvaluationCache<'tcx> { | |
664 | // see comment in `pick_candidate_cache` | |
665 | if self.intercrate || | |
666 | !self.param_env().caller_bounds.is_empty() | |
667 | { | |
668 | &self.param_env().evaluation_cache | |
669 | } else | |
670 | { | |
671 | &self.tcx().evaluation_cache | |
672 | } | |
673 | } | |
674 | ||
675 | fn check_evaluation_cache(&self, trait_ref: ty::PolyTraitRef<'tcx>) | |
676 | -> Option<EvaluationResult> | |
677 | { | |
678 | let cache = self.pick_evaluation_cache(); | |
679 | cache.hashmap.borrow().get(&trait_ref).cloned() | |
680 | } | |
681 | ||
682 | fn insert_evaluation_cache(&mut self, | |
683 | trait_ref: ty::PolyTraitRef<'tcx>, | |
684 | result: EvaluationResult) | |
685 | { | |
686 | // Avoid caching results that depend on more than just the trait-ref: | |
687 | // The stack can create EvaluatedToUnknown, and closure signatures | |
688 | // being yet uninferred can create "spurious" EvaluatedToAmbig | |
689 | // and EvaluatedToOk. | |
690 | if result == EvaluatedToUnknown || | |
691 | ((result == EvaluatedToAmbig || result == EvaluatedToOk) | |
692 | && trait_ref.has_closure_types()) | |
693 | { | |
694 | return; | |
695 | } | |
696 | ||
697 | let cache = self.pick_evaluation_cache(); | |
698 | cache.hashmap.borrow_mut().insert(trait_ref, result); | |
1a4d82fc JJ |
699 | } |
700 | ||
701 | /////////////////////////////////////////////////////////////////////////// | |
702 | // CANDIDATE ASSEMBLY | |
703 | // | |
704 | // The selection process begins by examining all in-scope impls, | |
705 | // caller obligations, and so forth and assembling a list of | |
c34b1796 AL |
706 | // candidates. See `README.md` and the `Candidate` type for more |
707 | // details. | |
1a4d82fc JJ |
708 | |
709 | fn candidate_from_obligation<'o>(&mut self, | |
710 | stack: &TraitObligationStack<'o, 'tcx>) | |
711 | -> SelectionResult<'tcx, SelectionCandidate<'tcx>> | |
712 | { | |
713 | // Watch out for overflow. This intentionally bypasses (and does | |
714 | // not update) the cache. | |
715 | let recursion_limit = self.infcx.tcx.sess.recursion_limit.get(); | |
716 | if stack.obligation.recursion_depth >= recursion_limit { | |
c34b1796 | 717 | report_overflow_error(self.infcx(), &stack.obligation); |
1a4d82fc JJ |
718 | } |
719 | ||
720 | // Check the cache. Note that we skolemize the trait-ref | |
721 | // separately rather than using `stack.fresh_trait_ref` -- this | |
722 | // is because we want the unbound variables to be replaced | |
723 | // with fresh skolemized types starting from index 0. | |
724 | let cache_fresh_trait_pred = | |
725 | self.infcx.freshen(stack.obligation.predicate.clone()); | |
62682a34 SL |
726 | debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})", |
727 | cache_fresh_trait_pred, | |
728 | stack); | |
1a4d82fc JJ |
729 | assert!(!stack.obligation.predicate.has_escaping_regions()); |
730 | ||
731 | match self.check_candidate_cache(&cache_fresh_trait_pred) { | |
732 | Some(c) => { | |
92a42be0 | 733 | debug!("CACHE HIT: SELECT({:?})={:?}", |
62682a34 SL |
734 | cache_fresh_trait_pred, |
735 | c); | |
1a4d82fc JJ |
736 | return c; |
737 | } | |
738 | None => { } | |
739 | } | |
740 | ||
741 | // If no match, compute result and insert into cache. | |
742 | let candidate = self.candidate_from_obligation_no_cache(stack); | |
85aaf69f SL |
743 | |
744 | if self.should_update_candidate_cache(&cache_fresh_trait_pred, &candidate) { | |
92a42be0 | 745 | debug!("CACHE MISS: SELECT({:?})={:?}", |
62682a34 | 746 | cache_fresh_trait_pred, candidate); |
85aaf69f SL |
747 | self.insert_candidate_cache(cache_fresh_trait_pred, candidate.clone()); |
748 | } | |
749 | ||
1a4d82fc JJ |
750 | candidate |
751 | } | |
752 | ||
753 | fn candidate_from_obligation_no_cache<'o>(&mut self, | |
754 | stack: &TraitObligationStack<'o, 'tcx>) | |
755 | -> SelectionResult<'tcx, SelectionCandidate<'tcx>> | |
756 | { | |
c1a9b12d | 757 | if stack.obligation.predicate.0.self_ty().references_error() { |
1a4d82fc JJ |
758 | return Ok(Some(ErrorCandidate)); |
759 | } | |
760 | ||
c34b1796 AL |
761 | if !self.is_knowable(stack) { |
762 | debug!("intercrate not knowable"); | |
763 | return Ok(None); | |
764 | } | |
765 | ||
1a4d82fc JJ |
766 | let candidate_set = try!(self.assemble_candidates(stack)); |
767 | ||
768 | if candidate_set.ambiguous { | |
769 | debug!("candidate set contains ambig"); | |
770 | return Ok(None); | |
771 | } | |
772 | ||
773 | let mut candidates = candidate_set.vec; | |
774 | ||
62682a34 | 775 | debug!("assembled {} candidates for {:?}: {:?}", |
1a4d82fc | 776 | candidates.len(), |
62682a34 SL |
777 | stack, |
778 | candidates); | |
1a4d82fc JJ |
779 | |
780 | // At this point, we know that each of the entries in the | |
781 | // candidate set is *individually* applicable. Now we have to | |
782 | // figure out if they contain mutual incompatibilities. This | |
783 | // frequently arises if we have an unconstrained input type -- | |
784 | // for example, we are looking for $0:Eq where $0 is some | |
785 | // unconstrained type variable. In that case, we'll get a | |
786 | // candidate which assumes $0 == int, one that assumes $0 == | |
c34b1796 | 787 | // usize, etc. This spells an ambiguity. |
1a4d82fc JJ |
788 | |
789 | // If there is more than one candidate, first winnow them down | |
790 | // by considering extra conditions (nested obligations and so | |
791 | // forth). We don't winnow if there is exactly one | |
792 | // candidate. This is a relatively minor distinction but it | |
793 | // can lead to better inference and error-reporting. An | |
794 | // example would be if there was an impl: | |
795 | // | |
796 | // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } } | |
797 | // | |
798 | // and we were to see some code `foo.push_clone()` where `boo` | |
799 | // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If | |
800 | // we were to winnow, we'd wind up with zero candidates. | |
801 | // Instead, we select the right impl now but report `Bar does | |
802 | // not implement Clone`. | |
803 | if candidates.len() > 1 { | |
92a42be0 | 804 | candidates.retain(|c| self.evaluate_candidate(stack, c).may_apply()) |
1a4d82fc JJ |
805 | } |
806 | ||
807 | // If there are STILL multiple candidate, we can further reduce | |
808 | // the list by dropping duplicates. | |
809 | if candidates.len() > 1 { | |
810 | let mut i = 0; | |
811 | while i < candidates.len() { | |
812 | let is_dup = | |
85aaf69f | 813 | (0..candidates.len()) |
1a4d82fc | 814 | .filter(|&j| i != j) |
85aaf69f | 815 | .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i], |
1a4d82fc JJ |
816 | &candidates[j])); |
817 | if is_dup { | |
62682a34 SL |
818 | debug!("Dropping candidate #{}/{}: {:?}", |
819 | i, candidates.len(), candidates[i]); | |
1a4d82fc JJ |
820 | candidates.swap_remove(i); |
821 | } else { | |
62682a34 SL |
822 | debug!("Retaining candidate #{}/{}: {:?}", |
823 | i, candidates.len(), candidates[i]); | |
1a4d82fc JJ |
824 | i += 1; |
825 | } | |
826 | } | |
827 | } | |
828 | ||
829 | // If there are *STILL* multiple candidates, give up and | |
830 | // report ambiguity. | |
831 | if candidates.len() > 1 { | |
832 | debug!("multiple matches, ambig"); | |
833 | return Ok(None); | |
834 | } | |
835 | ||
85aaf69f | 836 | |
1a4d82fc JJ |
837 | // If there are *NO* candidates, that there are no impls -- |
838 | // that we know of, anyway. Note that in the case where there | |
839 | // are unbound type variables within the obligation, it might | |
840 | // be the case that you could still satisfy the obligation | |
841 | // from another crate by instantiating the type variables with | |
842 | // a type from another crate that does have an impl. This case | |
843 | // is checked for in `evaluate_stack` (and hence users | |
844 | // who might care about this case, like coherence, should use | |
845 | // that function). | |
9346a6ac | 846 | if candidates.is_empty() { |
1a4d82fc JJ |
847 | return Err(Unimplemented); |
848 | } | |
849 | ||
850 | // Just one candidate left. | |
851 | let candidate = candidates.pop().unwrap(); | |
85aaf69f SL |
852 | |
853 | match candidate { | |
854 | ImplCandidate(def_id) => { | |
c1a9b12d | 855 | match self.tcx().trait_impl_polarity(def_id) { |
e9174d1e | 856 | Some(hir::ImplPolarity::Negative) => return Err(Unimplemented), |
85aaf69f SL |
857 | _ => {} |
858 | } | |
859 | } | |
860 | _ => {} | |
861 | } | |
862 | ||
1a4d82fc JJ |
863 | Ok(Some(candidate)) |
864 | } | |
865 | ||
c34b1796 AL |
866 | fn is_knowable<'o>(&mut self, |
867 | stack: &TraitObligationStack<'o, 'tcx>) | |
868 | -> bool | |
869 | { | |
870 | debug!("is_knowable(intercrate={})", self.intercrate); | |
871 | ||
872 | if !self.intercrate { | |
873 | return true; | |
874 | } | |
875 | ||
876 | let obligation = &stack.obligation; | |
877 | let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate); | |
878 | ||
879 | // ok to skip binder because of the nature of the | |
880 | // trait-ref-is-knowable check, which does not care about | |
881 | // bound regions | |
882 | let trait_ref = &predicate.skip_binder().trait_ref; | |
883 | ||
884 | coherence::trait_ref_is_knowable(self.tcx(), trait_ref) | |
885 | } | |
886 | ||
85aaf69f SL |
887 | fn pick_candidate_cache(&self) -> &SelectionCache<'tcx> { |
888 | // If there are any where-clauses in scope, then we always use | |
889 | // a cache local to this particular scope. Otherwise, we | |
890 | // switch to a global cache. We used to try and draw | |
891 | // finer-grained distinctions, but that led to a serious of | |
892 | // annoying and weird bugs like #22019 and #18290. This simple | |
893 | // rule seems to be pretty clearly safe and also still retains | |
894 | // a very high hit rate (~95% when compiling rustc). | |
895 | if !self.param_env().caller_bounds.is_empty() { | |
896 | return &self.param_env().selection_cache; | |
897 | } | |
1a4d82fc JJ |
898 | |
899 | // Avoid using the master cache during coherence and just rely | |
900 | // on the local cache. This effectively disables caching | |
901 | // during coherence. It is really just a simplification to | |
902 | // avoid us having to fear that coherence results "pollute" | |
903 | // the master cache. Since coherence executes pretty quickly, | |
904 | // it's not worth going to more trouble to increase the | |
905 | // hit-rate I don't think. | |
906 | if self.intercrate { | |
907 | return &self.param_env().selection_cache; | |
908 | } | |
909 | ||
1a4d82fc JJ |
910 | // Otherwise, we can use the global cache. |
911 | &self.tcx().selection_cache | |
912 | } | |
913 | ||
914 | fn check_candidate_cache(&mut self, | |
915 | cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>) | |
916 | -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> | |
917 | { | |
85aaf69f | 918 | let cache = self.pick_candidate_cache(); |
1a4d82fc | 919 | let hashmap = cache.hashmap.borrow(); |
85aaf69f | 920 | hashmap.get(&cache_fresh_trait_pred.0.trait_ref).cloned() |
1a4d82fc JJ |
921 | } |
922 | ||
923 | fn insert_candidate_cache(&mut self, | |
924 | cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, | |
925 | candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>) | |
926 | { | |
85aaf69f | 927 | let cache = self.pick_candidate_cache(); |
1a4d82fc JJ |
928 | let mut hashmap = cache.hashmap.borrow_mut(); |
929 | hashmap.insert(cache_fresh_trait_pred.0.trait_ref.clone(), candidate); | |
930 | } | |
931 | ||
85aaf69f SL |
932 | fn should_update_candidate_cache(&mut self, |
933 | cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>, | |
934 | candidate: &SelectionResult<'tcx, SelectionCandidate<'tcx>>) | |
935 | -> bool | |
936 | { | |
937 | // In general, it's a good idea to cache results, even | |
938 | // ambiguous ones, to save us some trouble later. But we have | |
939 | // to be careful not to cache results that could be | |
940 | // invalidated later by advances in inference. Normally, this | |
941 | // is not an issue, because any inference variables whose | |
942 | // types are not yet bound are "freshened" in the cache key, | |
943 | // which means that if we later get the same request once that | |
944 | // type variable IS bound, we'll have a different cache key. | |
945 | // For example, if we have `Vec<_#0t> : Foo`, and `_#0t` is | |
946 | // not yet known, we may cache the result as `None`. But if | |
947 | // later `_#0t` is bound to `Bar`, then when we freshen we'll | |
948 | // have `Vec<Bar> : Foo` as the cache key. | |
949 | // | |
950 | // HOWEVER, it CAN happen that we get an ambiguity result in | |
951 | // one particular case around closures where the cache key | |
952 | // would not change. That is when the precise types of the | |
953 | // upvars that a closure references have not yet been figured | |
954 | // out (i.e., because it is not yet known if they are captured | |
955 | // by ref, and if by ref, what kind of ref). In these cases, | |
956 | // when matching a builtin bound, we will yield back an | |
957 | // ambiguous result. But the *cache key* is just the closure type, | |
958 | // it doesn't capture the state of the upvar computation. | |
959 | // | |
960 | // To avoid this trap, just don't cache ambiguous results if | |
961 | // the self-type contains no inference byproducts (that really | |
962 | // shouldn't happen in other circumstances anyway, given | |
963 | // coherence). | |
964 | ||
965 | match *candidate { | |
966 | Ok(Some(_)) | Err(_) => true, | |
967 | Ok(None) => { | |
c1a9b12d | 968 | cache_fresh_trait_pred.0.input_types().has_infer_types() |
85aaf69f SL |
969 | } |
970 | } | |
971 | } | |
972 | ||
1a4d82fc JJ |
973 | fn assemble_candidates<'o>(&mut self, |
974 | stack: &TraitObligationStack<'o, 'tcx>) | |
975 | -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> | |
976 | { | |
1a4d82fc | 977 | let TraitObligationStack { obligation, .. } = *stack; |
e9174d1e SL |
978 | let ref obligation = Obligation { |
979 | cause: obligation.cause.clone(), | |
980 | recursion_depth: obligation.recursion_depth, | |
981 | predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate) | |
982 | }; | |
983 | ||
984 | if obligation.predicate.skip_binder().self_ty().is_ty_var() { | |
985 | // FIXME(#20297): Self is a type variable (e.g. `_: AsRef<str>`). | |
986 | // | |
987 | // This is somewhat problematic, as the current scheme can't really | |
988 | // handle it turning to be a projection. This does end up as truly | |
989 | // ambiguous in most cases anyway. | |
990 | // | |
991 | // Until this is fixed, take the fast path out - this also improves | |
992 | // performance by preventing assemble_candidates_from_impls from | |
993 | // matching every impl for this trait. | |
994 | return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true }); | |
995 | } | |
1a4d82fc JJ |
996 | |
997 | let mut candidates = SelectionCandidateSet { | |
998 | vec: Vec::new(), | |
999 | ambiguous: false | |
1000 | }; | |
1001 | ||
1002 | // Other bounds. Consider both in-scope bounds from fn decl | |
1003 | // and applicable impls. There is a certain set of precedence rules here. | |
1004 | ||
1005 | match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) { | |
1006 | Some(ty::BoundCopy) => { | |
62682a34 SL |
1007 | debug!("obligation self ty is {:?}", |
1008 | obligation.predicate.0.self_ty()); | |
1a4d82fc | 1009 | |
c34b1796 AL |
1010 | // User-defined copy impls are permitted, but only for |
1011 | // structs and enums. | |
85aaf69f | 1012 | try!(self.assemble_candidates_from_impls(obligation, &mut candidates)); |
1a4d82fc | 1013 | |
c34b1796 | 1014 | // For other types, we'll use the builtin rules. |
1a4d82fc | 1015 | try!(self.assemble_builtin_bound_candidates(ty::BoundCopy, |
e9174d1e | 1016 | obligation, |
1a4d82fc JJ |
1017 | &mut candidates)); |
1018 | } | |
1a4d82fc | 1019 | Some(bound @ ty::BoundSized) => { |
c34b1796 AL |
1020 | // Sized is never implementable by end-users, it is |
1021 | // always automatically computed. | |
e9174d1e SL |
1022 | try!(self.assemble_builtin_bound_candidates(bound, |
1023 | obligation, | |
1024 | &mut candidates)); | |
1a4d82fc JJ |
1025 | } |
1026 | ||
d9579d0f AL |
1027 | None if self.tcx().lang_items.unsize_trait() == |
1028 | Some(obligation.predicate.def_id()) => { | |
1029 | self.assemble_candidates_for_unsizing(obligation, &mut candidates); | |
1030 | } | |
1031 | ||
c34b1796 AL |
1032 | Some(ty::BoundSend) | |
1033 | Some(ty::BoundSync) | | |
1a4d82fc | 1034 | None => { |
85aaf69f | 1035 | try!(self.assemble_closure_candidates(obligation, &mut candidates)); |
1a4d82fc | 1036 | try!(self.assemble_fn_pointer_candidates(obligation, &mut candidates)); |
85aaf69f | 1037 | try!(self.assemble_candidates_from_impls(obligation, &mut candidates)); |
1a4d82fc JJ |
1038 | self.assemble_candidates_from_object_ty(obligation, &mut candidates); |
1039 | } | |
1040 | } | |
1041 | ||
1042 | self.assemble_candidates_from_projected_tys(obligation, &mut candidates); | |
85aaf69f | 1043 | try!(self.assemble_candidates_from_caller_bounds(stack, &mut candidates)); |
c34b1796 AL |
1044 | // Default implementations have lower priority, so we only |
1045 | // consider triggering a default if there is no other impl that can apply. | |
9346a6ac | 1046 | if candidates.vec.is_empty() { |
c34b1796 AL |
1047 | try!(self.assemble_candidates_from_default_impls(obligation, &mut candidates)); |
1048 | } | |
1a4d82fc JJ |
1049 | debug!("candidate list size: {}", candidates.vec.len()); |
1050 | Ok(candidates) | |
1051 | } | |
1052 | ||
1053 | fn assemble_candidates_from_projected_tys(&mut self, | |
1054 | obligation: &TraitObligation<'tcx>, | |
1055 | candidates: &mut SelectionCandidateSet<'tcx>) | |
1056 | { | |
e9174d1e | 1057 | debug!("assemble_candidates_for_projected_tys({:?})", obligation); |
1a4d82fc JJ |
1058 | |
1059 | // FIXME(#20297) -- just examining the self-type is very simplistic | |
1060 | ||
1061 | // before we go into the whole skolemization thing, just | |
1062 | // quickly check if the self-type is a projection at all. | |
e9174d1e | 1063 | let trait_def_id = match obligation.predicate.0.trait_ref.self_ty().sty { |
62682a34 SL |
1064 | ty::TyProjection(ref data) => data.trait_ref.def_id, |
1065 | ty::TyInfer(ty::TyVar(_)) => { | |
e9174d1e SL |
1066 | self.tcx().sess.span_bug(obligation.cause.span, |
1067 | "Self=_ should have been handled by assemble_candidates"); | |
1a4d82fc JJ |
1068 | } |
1069 | _ => { return; } | |
1070 | }; | |
1071 | ||
62682a34 SL |
1072 | debug!("assemble_candidates_for_projected_tys: trait_def_id={:?}", |
1073 | trait_def_id); | |
1a4d82fc JJ |
1074 | |
1075 | let result = self.infcx.probe(|snapshot| { | |
1076 | self.match_projection_obligation_against_bounds_from_trait(obligation, | |
1077 | snapshot) | |
1078 | }); | |
1079 | ||
1080 | if result { | |
1081 | candidates.vec.push(ProjectionCandidate); | |
1082 | } | |
1083 | } | |
1084 | ||
1085 | fn match_projection_obligation_against_bounds_from_trait( | |
1086 | &mut self, | |
1087 | obligation: &TraitObligation<'tcx>, | |
1088 | snapshot: &infer::CombinedSnapshot) | |
1089 | -> bool | |
1090 | { | |
1091 | let poly_trait_predicate = | |
1092 | self.infcx().resolve_type_vars_if_possible(&obligation.predicate); | |
1093 | let (skol_trait_predicate, skol_map) = | |
1094 | self.infcx().skolemize_late_bound_regions(&poly_trait_predicate, snapshot); | |
1095 | debug!("match_projection_obligation_against_bounds_from_trait: \ | |
62682a34 SL |
1096 | skol_trait_predicate={:?} skol_map={:?}", |
1097 | skol_trait_predicate, | |
1098 | skol_map); | |
1a4d82fc JJ |
1099 | |
1100 | let projection_trait_ref = match skol_trait_predicate.trait_ref.self_ty().sty { | |
62682a34 | 1101 | ty::TyProjection(ref data) => &data.trait_ref, |
1a4d82fc JJ |
1102 | _ => { |
1103 | self.tcx().sess.span_bug( | |
1104 | obligation.cause.span, | |
85aaf69f | 1105 | &format!("match_projection_obligation_against_bounds_from_trait() called \ |
62682a34 SL |
1106 | but self-ty not a projection: {:?}", |
1107 | skol_trait_predicate.trait_ref.self_ty())); | |
1a4d82fc JJ |
1108 | } |
1109 | }; | |
1110 | debug!("match_projection_obligation_against_bounds_from_trait: \ | |
62682a34 SL |
1111 | projection_trait_ref={:?}", |
1112 | projection_trait_ref); | |
1a4d82fc | 1113 | |
c1a9b12d | 1114 | let trait_predicates = self.tcx().lookup_predicates(projection_trait_ref.def_id); |
85aaf69f | 1115 | let bounds = trait_predicates.instantiate(self.tcx(), projection_trait_ref.substs); |
1a4d82fc | 1116 | debug!("match_projection_obligation_against_bounds_from_trait: \ |
62682a34 SL |
1117 | bounds={:?}", |
1118 | bounds); | |
1a4d82fc JJ |
1119 | |
1120 | let matching_bound = | |
1121 | util::elaborate_predicates(self.tcx(), bounds.predicates.into_vec()) | |
1122 | .filter_to_traits() | |
1123 | .find( | |
1124 | |bound| self.infcx.probe( | |
1125 | |_| self.match_projection(obligation, | |
1126 | bound.clone(), | |
1127 | skol_trait_predicate.trait_ref.clone(), | |
1128 | &skol_map, | |
1129 | snapshot))); | |
1130 | ||
1131 | debug!("match_projection_obligation_against_bounds_from_trait: \ | |
62682a34 SL |
1132 | matching_bound={:?}", |
1133 | matching_bound); | |
1a4d82fc JJ |
1134 | match matching_bound { |
1135 | None => false, | |
1136 | Some(bound) => { | |
1137 | // Repeat the successful match, if any, this time outside of a probe. | |
1138 | let result = self.match_projection(obligation, | |
1139 | bound, | |
1140 | skol_trait_predicate.trait_ref.clone(), | |
1141 | &skol_map, | |
1142 | snapshot); | |
1143 | assert!(result); | |
1144 | true | |
1145 | } | |
1146 | } | |
1147 | } | |
1148 | ||
1149 | fn match_projection(&mut self, | |
1150 | obligation: &TraitObligation<'tcx>, | |
1151 | trait_bound: ty::PolyTraitRef<'tcx>, | |
d9579d0f | 1152 | skol_trait_ref: ty::TraitRef<'tcx>, |
1a4d82fc JJ |
1153 | skol_map: &infer::SkolemizationMap, |
1154 | snapshot: &infer::CombinedSnapshot) | |
1155 | -> bool | |
1156 | { | |
1157 | assert!(!skol_trait_ref.has_escaping_regions()); | |
92a42be0 | 1158 | let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span); |
1a4d82fc JJ |
1159 | match self.infcx.sub_poly_trait_refs(false, |
1160 | origin, | |
1161 | trait_bound.clone(), | |
1162 | ty::Binder(skol_trait_ref.clone())) { | |
1163 | Ok(()) => { } | |
1164 | Err(_) => { return false; } | |
1165 | } | |
1166 | ||
1167 | self.infcx.leak_check(skol_map, snapshot).is_ok() | |
1168 | } | |
1169 | ||
1170 | /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller | |
1171 | /// supplied to find out whether it is listed among them. | |
1172 | /// | |
1173 | /// Never affects inference environment. | |
85aaf69f SL |
1174 | fn assemble_candidates_from_caller_bounds<'o>(&mut self, |
1175 | stack: &TraitObligationStack<'o, 'tcx>, | |
1176 | candidates: &mut SelectionCandidateSet<'tcx>) | |
1177 | -> Result<(),SelectionError<'tcx>> | |
1a4d82fc | 1178 | { |
62682a34 SL |
1179 | debug!("assemble_candidates_from_caller_bounds({:?})", |
1180 | stack.obligation); | |
1a4d82fc JJ |
1181 | |
1182 | let all_bounds = | |
62682a34 SL |
1183 | self.param_env().caller_bounds |
1184 | .iter() | |
1185 | .filter_map(|o| o.to_opt_poly_trait_ref()); | |
1a4d82fc JJ |
1186 | |
1187 | let matching_bounds = | |
1188 | all_bounds.filter( | |
85aaf69f | 1189 | |bound| self.evaluate_where_clause(stack, bound.clone()).may_apply()); |
1a4d82fc JJ |
1190 | |
1191 | let param_candidates = | |
1192 | matching_bounds.map(|bound| ParamCandidate(bound)); | |
1193 | ||
1194 | candidates.vec.extend(param_candidates); | |
1195 | ||
1196 | Ok(()) | |
1197 | } | |
1198 | ||
85aaf69f SL |
1199 | fn evaluate_where_clause<'o>(&mut self, |
1200 | stack: &TraitObligationStack<'o, 'tcx>, | |
1201 | where_clause_trait_ref: ty::PolyTraitRef<'tcx>) | |
92a42be0 | 1202 | -> EvaluationResult |
85aaf69f SL |
1203 | { |
1204 | self.infcx().probe(move |_| { | |
1205 | match self.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) { | |
1206 | Ok(obligations) => { | |
c34b1796 | 1207 | self.evaluate_predicates_recursively(stack.list(), obligations.iter()) |
85aaf69f | 1208 | } |
92a42be0 | 1209 | Err(()) => EvaluatedToErr |
85aaf69f SL |
1210 | } |
1211 | }) | |
1212 | } | |
1213 | ||
1a4d82fc | 1214 | /// Check for the artificial impl that the compiler will create for an obligation like `X : |
85aaf69f | 1215 | /// FnMut<..>` where `X` is a closure type. |
1a4d82fc | 1216 | /// |
85aaf69f | 1217 | /// Note: the type parameters on a closure candidate are modeled as *output* type |
1a4d82fc JJ |
1218 | /// parameters and hence do not affect whether this trait is a match or not. They will be |
1219 | /// unified during the confirmation step. | |
85aaf69f SL |
1220 | fn assemble_closure_candidates(&mut self, |
1221 | obligation: &TraitObligation<'tcx>, | |
1222 | candidates: &mut SelectionCandidateSet<'tcx>) | |
1223 | -> Result<(),SelectionError<'tcx>> | |
1a4d82fc | 1224 | { |
85aaf69f | 1225 | let kind = match self.tcx().lang_items.fn_trait_kind(obligation.predicate.0.def_id()) { |
1a4d82fc JJ |
1226 | Some(k) => k, |
1227 | None => { return Ok(()); } | |
1228 | }; | |
1229 | ||
c34b1796 AL |
1230 | // ok to skip binder because the substs on closure types never |
1231 | // touch bound regions, they just capture the in-scope | |
1232 | // type/region parameters | |
e9174d1e | 1233 | let self_ty = *obligation.self_ty().skip_binder(); |
1a4d82fc | 1234 | let (closure_def_id, substs) = match self_ty.sty { |
c1a9b12d | 1235 | ty::TyClosure(id, ref substs) => (id, substs), |
62682a34 | 1236 | ty::TyInfer(ty::TyVar(_)) => { |
85aaf69f | 1237 | debug!("assemble_unboxed_closure_candidates: ambiguous self-type"); |
1a4d82fc JJ |
1238 | candidates.ambiguous = true; |
1239 | return Ok(()); | |
1240 | } | |
1241 | _ => { return Ok(()); } | |
1242 | }; | |
1243 | ||
62682a34 SL |
1244 | debug!("assemble_unboxed_candidates: self_ty={:?} kind={:?} obligation={:?}", |
1245 | self_ty, | |
1a4d82fc | 1246 | kind, |
62682a34 | 1247 | obligation); |
1a4d82fc | 1248 | |
c1a9b12d | 1249 | match self.infcx.closure_kind(closure_def_id) { |
85aaf69f SL |
1250 | Some(closure_kind) => { |
1251 | debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind); | |
c34b1796 | 1252 | if closure_kind.extends(kind) { |
c1a9b12d | 1253 | candidates.vec.push(ClosureCandidate(closure_def_id, substs)); |
85aaf69f SL |
1254 | } |
1255 | } | |
1256 | None => { | |
1257 | debug!("assemble_unboxed_candidates: closure_kind not yet known"); | |
1258 | candidates.ambiguous = true; | |
1259 | } | |
1a4d82fc JJ |
1260 | } |
1261 | ||
1262 | Ok(()) | |
1263 | } | |
1264 | ||
1265 | /// Implement one of the `Fn()` family for a fn pointer. | |
1266 | fn assemble_fn_pointer_candidates(&mut self, | |
1267 | obligation: &TraitObligation<'tcx>, | |
1268 | candidates: &mut SelectionCandidateSet<'tcx>) | |
1269 | -> Result<(),SelectionError<'tcx>> | |
1270 | { | |
c34b1796 AL |
1271 | // We provide impl of all fn traits for fn pointers. |
1272 | if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() { | |
1a4d82fc JJ |
1273 | return Ok(()); |
1274 | } | |
1275 | ||
c34b1796 | 1276 | // ok to skip binder because what we are inspecting doesn't involve bound regions |
e9174d1e | 1277 | let self_ty = *obligation.self_ty().skip_binder(); |
1a4d82fc | 1278 | match self_ty.sty { |
62682a34 | 1279 | ty::TyInfer(ty::TyVar(_)) => { |
85aaf69f | 1280 | debug!("assemble_fn_pointer_candidates: ambiguous self-type"); |
1a4d82fc JJ |
1281 | candidates.ambiguous = true; // could wind up being a fn() type |
1282 | } | |
1283 | ||
1284 | // provide an impl, but only for suitable `fn` pointers | |
62682a34 | 1285 | ty::TyBareFn(_, &ty::BareFnTy { |
e9174d1e | 1286 | unsafety: hir::Unsafety::Normal, |
1a4d82fc JJ |
1287 | abi: abi::Rust, |
1288 | sig: ty::Binder(ty::FnSig { | |
1289 | inputs: _, | |
1290 | output: ty::FnConverging(_), | |
1291 | variadic: false | |
1292 | }) | |
1293 | }) => { | |
1294 | candidates.vec.push(FnPointerCandidate); | |
1295 | } | |
1296 | ||
1297 | _ => { } | |
1298 | } | |
1299 | ||
1300 | Ok(()) | |
1301 | } | |
1302 | ||
1303 | /// Search for impls that might apply to `obligation`. | |
1304 | fn assemble_candidates_from_impls(&mut self, | |
1305 | obligation: &TraitObligation<'tcx>, | |
85aaf69f | 1306 | candidates: &mut SelectionCandidateSet<'tcx>) |
1a4d82fc JJ |
1307 | -> Result<(), SelectionError<'tcx>> |
1308 | { | |
62682a34 | 1309 | debug!("assemble_candidates_from_impls(obligation={:?})", obligation); |
85aaf69f | 1310 | |
c1a9b12d | 1311 | let def = self.tcx().lookup_trait_def(obligation.predicate.def_id()); |
d9579d0f AL |
1312 | |
1313 | def.for_each_relevant_impl( | |
1314 | self.tcx(), | |
1315 | obligation.predicate.0.trait_ref.self_ty(), | |
1316 | |impl_def_id| { | |
1317 | self.infcx.probe(|snapshot| { | |
1318 | if let Ok(_) = self.match_impl(impl_def_id, obligation, snapshot) { | |
85aaf69f | 1319 | candidates.vec.push(ImplCandidate(impl_def_id)); |
1a4d82fc | 1320 | } |
d9579d0f AL |
1321 | }); |
1322 | } | |
1323 | ); | |
c34b1796 AL |
1324 | |
1325 | Ok(()) | |
1326 | } | |
1327 | ||
1328 | fn assemble_candidates_from_default_impls(&mut self, | |
1329 | obligation: &TraitObligation<'tcx>, | |
1330 | candidates: &mut SelectionCandidateSet<'tcx>) | |
1331 | -> Result<(), SelectionError<'tcx>> | |
1332 | { | |
1333 | // OK to skip binder here because the tests we do below do not involve bound regions | |
e9174d1e | 1334 | let self_ty = *obligation.self_ty().skip_binder(); |
62682a34 | 1335 | debug!("assemble_candidates_from_default_impls(self_ty={:?})", self_ty); |
c34b1796 AL |
1336 | |
1337 | let def_id = obligation.predicate.def_id(); | |
1338 | ||
c1a9b12d | 1339 | if self.tcx().trait_has_default_impl(def_id) { |
c34b1796 | 1340 | match self_ty.sty { |
62682a34 | 1341 | ty::TyTrait(..) => { |
c34b1796 AL |
1342 | // For object types, we don't know what the closed |
1343 | // over types are. For most traits, this means we | |
1344 | // conservatively say nothing; a candidate may be | |
1345 | // added by `assemble_candidates_from_object_ty`. | |
1346 | // However, for the kind of magic reflect trait, | |
1347 | // we consider it to be implemented even for | |
1348 | // object types, because it just lets you reflect | |
1349 | // onto the object type, not into the object's | |
1350 | // interior. | |
c1a9b12d | 1351 | if self.tcx().has_attr(def_id, "rustc_reflect_like") { |
c34b1796 AL |
1352 | candidates.vec.push(DefaultImplObjectCandidate(def_id)); |
1353 | } | |
1354 | } | |
62682a34 SL |
1355 | ty::TyParam(..) | |
1356 | ty::TyProjection(..) => { | |
c34b1796 AL |
1357 | // In these cases, we don't know what the actual |
1358 | // type is. Therefore, we cannot break it down | |
1359 | // into its constituent types. So we don't | |
1360 | // consider the `..` impl but instead just add no | |
1361 | // candidates: this means that typeck will only | |
1362 | // succeed if there is another reason to believe | |
1363 | // that this obligation holds. That could be a | |
1364 | // where-clause or, in the case of an object type, | |
1365 | // it could be that the object type lists the | |
1366 | // trait (e.g. `Foo+Send : Send`). See | |
1367 | // `compile-fail/typeck-default-trait-impl-send-param.rs` | |
1368 | // for an example of a test case that exercises | |
1369 | // this path. | |
1370 | } | |
62682a34 | 1371 | ty::TyInfer(ty::TyVar(_)) => { |
c34b1796 AL |
1372 | // the defaulted impl might apply, we don't know |
1373 | candidates.ambiguous = true; | |
1374 | } | |
1375 | _ => { | |
c1a9b12d | 1376 | candidates.vec.push(DefaultImplCandidate(def_id.clone())) |
c34b1796 AL |
1377 | } |
1378 | } | |
1379 | } | |
1380 | ||
1a4d82fc JJ |
1381 | Ok(()) |
1382 | } | |
1383 | ||
1384 | /// Search for impls that might apply to `obligation`. | |
1385 | fn assemble_candidates_from_object_ty(&mut self, | |
1386 | obligation: &TraitObligation<'tcx>, | |
1387 | candidates: &mut SelectionCandidateSet<'tcx>) | |
1388 | { | |
62682a34 | 1389 | debug!("assemble_candidates_from_object_ty(self_ty={:?})", |
e9174d1e | 1390 | obligation.self_ty().skip_binder()); |
1a4d82fc JJ |
1391 | |
1392 | // Object-safety candidates are only applicable to object-safe | |
1393 | // traits. Including this check is useful because it helps | |
1394 | // inference in cases of traits like `BorrowFrom`, which are | |
1395 | // not object-safe, and which rely on being able to infer the | |
1396 | // self-type from one of the other inputs. Without this check, | |
1397 | // these cases wind up being considered ambiguous due to a | |
1398 | // (spurious) ambiguity introduced here. | |
c34b1796 AL |
1399 | let predicate_trait_ref = obligation.predicate.to_poly_trait_ref(); |
1400 | if !object_safety::is_object_safe(self.tcx(), predicate_trait_ref.def_id()) { | |
1a4d82fc JJ |
1401 | return; |
1402 | } | |
1403 | ||
c34b1796 | 1404 | self.infcx.commit_if_ok(|snapshot| { |
c34b1796 | 1405 | let (self_ty, _) = |
e9174d1e | 1406 | self.infcx().skolemize_late_bound_regions(&obligation.self_ty(), snapshot); |
c34b1796 | 1407 | let poly_trait_ref = match self_ty.sty { |
62682a34 | 1408 | ty::TyTrait(ref data) => { |
c34b1796 AL |
1409 | match self.tcx().lang_items.to_builtin_kind(obligation.predicate.def_id()) { |
1410 | Some(bound @ ty::BoundSend) | Some(bound @ ty::BoundSync) => { | |
1411 | if data.bounds.builtin_bounds.contains(&bound) { | |
1412 | debug!("assemble_candidates_from_object_ty: matched builtin bound, \ | |
1413 | pushing candidate"); | |
1414 | candidates.vec.push(BuiltinObjectCandidate); | |
1415 | return Ok(()); | |
1416 | } | |
1417 | } | |
1418 | _ => {} | |
1419 | } | |
1a4d82fc | 1420 | |
c34b1796 AL |
1421 | data.principal_trait_ref_with_self_ty(self.tcx(), self_ty) |
1422 | } | |
62682a34 | 1423 | ty::TyInfer(ty::TyVar(_)) => { |
c34b1796 AL |
1424 | debug!("assemble_candidates_from_object_ty: ambiguous"); |
1425 | candidates.ambiguous = true; // could wind up being an object type | |
1426 | return Ok(()); | |
1427 | } | |
1428 | _ => { | |
1429 | return Ok(()); | |
1430 | } | |
1431 | }; | |
1a4d82fc | 1432 | |
62682a34 SL |
1433 | debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}", |
1434 | poly_trait_ref); | |
1a4d82fc | 1435 | |
c1a9b12d SL |
1436 | // Count only those upcast versions that match the trait-ref |
1437 | // we are looking for. Specifically, do not only check for the | |
1438 | // correct trait, but also the correct type parameters. | |
1439 | // For example, we may be trying to upcast `Foo` to `Bar<i32>`, | |
1440 | // but `Foo` is declared as `trait Foo : Bar<u32>`. | |
1441 | let upcast_trait_refs = | |
1442 | util::supertraits(self.tcx(), poly_trait_ref) | |
1443 | .filter(|upcast_trait_ref| { | |
1444 | self.infcx.probe(|_| { | |
1445 | let upcast_trait_ref = upcast_trait_ref.clone(); | |
1446 | self.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok() | |
1447 | }) | |
1448 | }) | |
1449 | .count(); | |
1450 | ||
1451 | if upcast_trait_refs > 1 { | |
c34b1796 AL |
1452 | // can be upcast in many ways; need more type information |
1453 | candidates.ambiguous = true; | |
c1a9b12d | 1454 | } else if upcast_trait_refs == 1 { |
c34b1796 AL |
1455 | candidates.vec.push(ObjectCandidate); |
1456 | } | |
1a4d82fc | 1457 | |
c34b1796 AL |
1458 | Ok::<(),()>(()) |
1459 | }).unwrap(); | |
1a4d82fc JJ |
1460 | } |
1461 | ||
d9579d0f AL |
1462 | /// Search for unsizing that might apply to `obligation`. |
1463 | fn assemble_candidates_for_unsizing(&mut self, | |
1464 | obligation: &TraitObligation<'tcx>, | |
1465 | candidates: &mut SelectionCandidateSet<'tcx>) { | |
1466 | // We currently never consider higher-ranked obligations e.g. | |
1467 | // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not | |
1468 | // because they are a priori invalid, and we could potentially add support | |
1469 | // for them later, it's just that there isn't really a strong need for it. | |
1470 | // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>` | |
1471 | // impl, and those are generally applied to concrete types. | |
1472 | // | |
1473 | // That said, one might try to write a fn with a where clause like | |
1474 | // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>> | |
1475 | // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`. | |
1476 | // Still, you'd be more likely to write that where clause as | |
1477 | // T: Trait | |
1478 | // so it seems ok if we (conservatively) fail to accept that `Unsize` | |
1479 | // obligation above. Should be possible to extend this in the future. | |
e9174d1e | 1480 | let source = match self.tcx().no_late_bound_regions(&obligation.self_ty()) { |
d9579d0f AL |
1481 | Some(t) => t, |
1482 | None => { | |
1483 | // Don't add any candidates if there are bound regions. | |
1484 | return; | |
1485 | } | |
1486 | }; | |
e9174d1e | 1487 | let target = obligation.predicate.0.input_types()[0]; |
d9579d0f | 1488 | |
62682a34 SL |
1489 | debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})", |
1490 | source, target); | |
d9579d0f AL |
1491 | |
1492 | let may_apply = match (&source.sty, &target.sty) { | |
1493 | // Trait+Kx+'a -> Trait+Ky+'b (upcasts). | |
62682a34 | 1494 | (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => { |
d9579d0f AL |
1495 | // Upcasts permit two things: |
1496 | // | |
1497 | // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo` | |
1498 | // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b` | |
1499 | // | |
1500 | // Note that neither of these changes requires any | |
1501 | // change at runtime. Eventually this will be | |
1502 | // generalized. | |
1503 | // | |
1504 | // We always upcast when we can because of reason | |
1505 | // #2 (region bounds). | |
1506 | data_a.principal.def_id() == data_a.principal.def_id() && | |
1507 | data_a.bounds.builtin_bounds.is_superset(&data_b.bounds.builtin_bounds) | |
1508 | } | |
1509 | ||
1510 | // T -> Trait. | |
62682a34 | 1511 | (_, &ty::TyTrait(_)) => true, |
d9579d0f AL |
1512 | |
1513 | // Ambiguous handling is below T -> Trait, because inference | |
1514 | // variables can still implement Unsize<Trait> and nested | |
1515 | // obligations will have the final say (likely deferred). | |
62682a34 SL |
1516 | (&ty::TyInfer(ty::TyVar(_)), _) | |
1517 | (_, &ty::TyInfer(ty::TyVar(_))) => { | |
d9579d0f AL |
1518 | debug!("assemble_candidates_for_unsizing: ambiguous"); |
1519 | candidates.ambiguous = true; | |
1520 | false | |
1521 | } | |
1522 | ||
1523 | // [T; n] -> [T]. | |
62682a34 | 1524 | (&ty::TyArray(_, _), &ty::TySlice(_)) => true, |
d9579d0f AL |
1525 | |
1526 | // Struct<T> -> Struct<U>. | |
62682a34 | 1527 | (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => { |
d9579d0f AL |
1528 | def_id_a == def_id_b |
1529 | } | |
1530 | ||
1531 | _ => false | |
1532 | }; | |
1533 | ||
1534 | if may_apply { | |
1535 | candidates.vec.push(BuiltinUnsizeCandidate); | |
1536 | } | |
1537 | } | |
1538 | ||
1a4d82fc JJ |
1539 | /////////////////////////////////////////////////////////////////////////// |
1540 | // WINNOW | |
1541 | // | |
1542 | // Winnowing is the process of attempting to resolve ambiguity by | |
1543 | // probing further. During the winnowing process, we unify all | |
1544 | // type variables (ignoring skolemization) and then we also | |
1545 | // attempt to evaluate recursive bounds to see if they are | |
1546 | // satisfied. | |
1547 | ||
85aaf69f SL |
1548 | /// Returns true if `candidate_i` should be dropped in favor of |
1549 | /// `candidate_j`. Generally speaking we will drop duplicate | |
1550 | /// candidates and prefer where-clause candidates. | |
d9579d0f AL |
1551 | /// Returns true if `victim` should be dropped in favor of |
1552 | /// `other`. Generally speaking we will drop duplicate | |
1553 | /// candidates and prefer where-clause candidates. | |
1554 | /// | |
1555 | /// See the comment for "SelectionCandidate" for more details. | |
1a4d82fc | 1556 | fn candidate_should_be_dropped_in_favor_of<'o>(&mut self, |
d9579d0f AL |
1557 | victim: &SelectionCandidate<'tcx>, |
1558 | other: &SelectionCandidate<'tcx>) | |
1a4d82fc JJ |
1559 | -> bool |
1560 | { | |
d9579d0f | 1561 | if victim == other { |
85aaf69f SL |
1562 | return true; |
1563 | } | |
1564 | ||
d9579d0f | 1565 | match other { |
92a42be0 | 1566 | &ObjectCandidate | |
d9579d0f AL |
1567 | &ParamCandidate(_) | &ProjectionCandidate => match victim { |
1568 | &DefaultImplCandidate(..) => { | |
1569 | self.tcx().sess.bug( | |
1570 | "default implementations shouldn't be recorded \ | |
1571 | when there are other valid candidates"); | |
1572 | } | |
d9579d0f AL |
1573 | &ImplCandidate(..) | |
1574 | &ClosureCandidate(..) | | |
92a42be0 SL |
1575 | &FnPointerCandidate | |
1576 | &BuiltinObjectCandidate | | |
1577 | &BuiltinUnsizeCandidate | | |
d9579d0f AL |
1578 | &DefaultImplObjectCandidate(..) | |
1579 | &BuiltinCandidate(..) => { | |
1580 | // We have a where-clause so don't go around looking | |
1581 | // for impls. | |
1582 | true | |
1583 | } | |
92a42be0 | 1584 | &ObjectCandidate | |
d9579d0f AL |
1585 | &ProjectionCandidate => { |
1586 | // Arbitrarily give param candidates priority | |
1587 | // over projection and object candidates. | |
1588 | true | |
1589 | }, | |
1590 | &ParamCandidate(..) => false, | |
1591 | &ErrorCandidate => false // propagate errors | |
1592 | }, | |
1593 | _ => false | |
1a4d82fc JJ |
1594 | } |
1595 | } | |
1596 | ||
1597 | /////////////////////////////////////////////////////////////////////////// | |
1598 | // BUILTIN BOUNDS | |
1599 | // | |
1600 | // These cover the traits that are built-in to the language | |
1601 | // itself. This includes `Copy` and `Sized` for sure. For the | |
1602 | // moment, it also includes `Send` / `Sync` and a few others, but | |
1603 | // those will hopefully change to library-defined traits in the | |
1604 | // future. | |
1605 | ||
1606 | fn assemble_builtin_bound_candidates<'o>(&mut self, | |
1607 | bound: ty::BuiltinBound, | |
e9174d1e | 1608 | obligation: &TraitObligation<'tcx>, |
1a4d82fc JJ |
1609 | candidates: &mut SelectionCandidateSet<'tcx>) |
1610 | -> Result<(),SelectionError<'tcx>> | |
1611 | { | |
e9174d1e | 1612 | match self.builtin_bound(bound, obligation) { |
1a4d82fc | 1613 | Ok(If(..)) => { |
62682a34 SL |
1614 | debug!("builtin_bound: bound={:?}", |
1615 | bound); | |
1a4d82fc JJ |
1616 | candidates.vec.push(BuiltinCandidate(bound)); |
1617 | Ok(()) | |
1618 | } | |
1619 | Ok(ParameterBuiltin) => { Ok(()) } | |
85aaf69f SL |
1620 | Ok(AmbiguousBuiltin) => { |
1621 | debug!("assemble_builtin_bound_candidates: ambiguous builtin"); | |
1622 | Ok(candidates.ambiguous = true) | |
1623 | } | |
1a4d82fc JJ |
1624 | Err(e) => { Err(e) } |
1625 | } | |
1626 | } | |
1627 | ||
1628 | fn builtin_bound(&mut self, | |
1629 | bound: ty::BuiltinBound, | |
1630 | obligation: &TraitObligation<'tcx>) | |
1631 | -> Result<BuiltinBoundConditions<'tcx>,SelectionError<'tcx>> | |
1632 | { | |
1633 | // Note: these tests operate on types that may contain bound | |
1634 | // regions. To be proper, we ought to skolemize here, but we | |
1635 | // forego the skolemization and defer it until the | |
1636 | // confirmation step. | |
1637 | ||
1638 | let self_ty = self.infcx.shallow_resolve(obligation.predicate.0.self_ty()); | |
1639 | return match self_ty.sty { | |
62682a34 SL |
1640 | ty::TyInfer(ty::IntVar(_)) | |
1641 | ty::TyInfer(ty::FloatVar(_)) | | |
1642 | ty::TyUint(_) | | |
1643 | ty::TyInt(_) | | |
1644 | ty::TyBool | | |
1645 | ty::TyFloat(_) | | |
1646 | ty::TyBareFn(..) | | |
1647 | ty::TyChar => { | |
1a4d82fc | 1648 | // safe for everything |
c34b1796 | 1649 | ok_if(Vec::new()) |
1a4d82fc JJ |
1650 | } |
1651 | ||
62682a34 | 1652 | ty::TyBox(_) => { // Box<T> |
1a4d82fc | 1653 | match bound { |
c34b1796 | 1654 | ty::BoundCopy => Err(Unimplemented), |
1a4d82fc | 1655 | |
c34b1796 | 1656 | ty::BoundSized => ok_if(Vec::new()), |
1a4d82fc | 1657 | |
c34b1796 AL |
1658 | ty::BoundSync | ty::BoundSend => { |
1659 | self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()"); | |
1a4d82fc JJ |
1660 | } |
1661 | } | |
1662 | } | |
1663 | ||
62682a34 | 1664 | ty::TyRawPtr(..) => { // *const T, *mut T |
1a4d82fc | 1665 | match bound { |
c34b1796 | 1666 | ty::BoundCopy | ty::BoundSized => ok_if(Vec::new()), |
1a4d82fc | 1667 | |
c34b1796 AL |
1668 | ty::BoundSync | ty::BoundSend => { |
1669 | self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()"); | |
1a4d82fc JJ |
1670 | } |
1671 | } | |
1672 | } | |
1673 | ||
62682a34 | 1674 | ty::TyTrait(ref data) => { |
1a4d82fc | 1675 | match bound { |
c34b1796 AL |
1676 | ty::BoundSized => Err(Unimplemented), |
1677 | ty::BoundCopy => { | |
1a4d82fc | 1678 | if data.bounds.builtin_bounds.contains(&bound) { |
c34b1796 | 1679 | ok_if(Vec::new()) |
1a4d82fc JJ |
1680 | } else { |
1681 | // Recursively check all supertraits to find out if any further | |
1682 | // bounds are required and thus we must fulfill. | |
1683 | let principal = | |
1684 | data.principal_trait_ref_with_self_ty(self.tcx(), | |
1685 | self.tcx().types.err); | |
c1a9b12d | 1686 | let copy_def_id = obligation.predicate.def_id(); |
1a4d82fc | 1687 | for tr in util::supertraits(self.tcx(), principal) { |
c1a9b12d | 1688 | if tr.def_id() == copy_def_id { |
c34b1796 | 1689 | return ok_if(Vec::new()) |
1a4d82fc JJ |
1690 | } |
1691 | } | |
1692 | ||
1693 | Err(Unimplemented) | |
1694 | } | |
1695 | } | |
c34b1796 AL |
1696 | ty::BoundSync | ty::BoundSend => { |
1697 | self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()"); | |
1698 | } | |
1a4d82fc JJ |
1699 | } |
1700 | } | |
1701 | ||
c1a9b12d | 1702 | ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl }) => { |
1a4d82fc JJ |
1703 | // &mut T or &T |
1704 | match bound { | |
1705 | ty::BoundCopy => { | |
1706 | match mutbl { | |
1707 | // &mut T is affine and hence never `Copy` | |
e9174d1e | 1708 | hir::MutMutable => Err(Unimplemented), |
1a4d82fc JJ |
1709 | |
1710 | // &T is always copyable | |
e9174d1e | 1711 | hir::MutImmutable => ok_if(Vec::new()), |
1a4d82fc JJ |
1712 | } |
1713 | } | |
1714 | ||
c34b1796 | 1715 | ty::BoundSized => ok_if(Vec::new()), |
1a4d82fc | 1716 | |
c34b1796 AL |
1717 | ty::BoundSync | ty::BoundSend => { |
1718 | self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()"); | |
1a4d82fc JJ |
1719 | } |
1720 | } | |
1721 | } | |
1722 | ||
62682a34 SL |
1723 | ty::TyArray(element_ty, _) => { |
1724 | // [T; n] | |
1a4d82fc | 1725 | match bound { |
62682a34 SL |
1726 | ty::BoundCopy => ok_if(vec![element_ty]), |
1727 | ty::BoundSized => ok_if(Vec::new()), | |
c34b1796 AL |
1728 | ty::BoundSync | ty::BoundSend => { |
1729 | self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()"); | |
1a4d82fc JJ |
1730 | } |
1731 | } | |
1732 | } | |
1733 | ||
62682a34 | 1734 | ty::TyStr | ty::TySlice(_) => { |
1a4d82fc | 1735 | match bound { |
c34b1796 AL |
1736 | ty::BoundSync | ty::BoundSend => { |
1737 | self.tcx().sess.bug("Send/Sync shouldn't occur in builtin_bounds()"); | |
1a4d82fc JJ |
1738 | } |
1739 | ||
c34b1796 | 1740 | ty::BoundCopy | ty::BoundSized => Err(Unimplemented), |
1a4d82fc JJ |
1741 | } |
1742 | } | |
1743 | ||
c34b1796 | 1744 | // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet |
62682a34 | 1745 | ty::TyTuple(ref tys) => ok_if(tys.clone()), |
1a4d82fc | 1746 | |
b039eaaf | 1747 | ty::TyClosure(_, ref substs) => { |
1a4d82fc JJ |
1748 | // FIXME -- This case is tricky. In the case of by-ref |
1749 | // closures particularly, we need the results of | |
1750 | // inference to decide how to reflect the type of each | |
1751 | // upvar (the upvar may have type `T`, but the runtime | |
1752 | // type could be `&mut`, `&`, or just `T`). For now, | |
1753 | // though, we'll do this unsoundly and assume that all | |
1754 | // captures are by value. Really what we ought to do | |
1755 | // is reserve judgement and then intertwine this | |
1756 | // analysis with closure inference. | |
1a4d82fc JJ |
1757 | |
1758 | // Unboxed closures shouldn't be | |
1759 | // implicitly copyable | |
1760 | if bound == ty::BoundCopy { | |
1761 | return Ok(ParameterBuiltin); | |
1762 | } | |
1763 | ||
85aaf69f SL |
1764 | // Upvars are always local variables or references to |
1765 | // local variables, and local variables cannot be | |
1766 | // unsized, so the closure struct as a whole must be | |
1767 | // Sized. | |
1768 | if bound == ty::BoundSized { | |
c34b1796 | 1769 | return ok_if(Vec::new()); |
85aaf69f SL |
1770 | } |
1771 | ||
c1a9b12d | 1772 | ok_if(substs.upvar_tys.clone()) |
1a4d82fc JJ |
1773 | } |
1774 | ||
e9174d1e SL |
1775 | ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => { |
1776 | let types: Vec<Ty> = def.all_fields().map(|f| { | |
1777 | f.ty(self.tcx(), substs) | |
1778 | }).collect(); | |
c34b1796 | 1779 | nominal(bound, types) |
1a4d82fc JJ |
1780 | } |
1781 | ||
62682a34 | 1782 | ty::TyProjection(_) | ty::TyParam(_) => { |
1a4d82fc JJ |
1783 | // Note: A type parameter is only considered to meet a |
1784 | // particular bound if there is a where clause telling | |
1785 | // us that it does, and that case is handled by | |
1786 | // `assemble_candidates_from_caller_bounds()`. | |
1787 | Ok(ParameterBuiltin) | |
1788 | } | |
1789 | ||
62682a34 | 1790 | ty::TyInfer(ty::TyVar(_)) => { |
1a4d82fc JJ |
1791 | // Unbound type variable. Might or might not have |
1792 | // applicable impls and so forth, depending on what | |
1793 | // those type variables wind up being bound to. | |
85aaf69f | 1794 | debug!("assemble_builtin_bound_candidates: ambiguous builtin"); |
1a4d82fc JJ |
1795 | Ok(AmbiguousBuiltin) |
1796 | } | |
1797 | ||
62682a34 | 1798 | ty::TyError => ok_if(Vec::new()), |
1a4d82fc | 1799 | |
62682a34 SL |
1800 | ty::TyInfer(ty::FreshTy(_)) |
1801 | | ty::TyInfer(ty::FreshIntTy(_)) | |
1802 | | ty::TyInfer(ty::FreshFloatTy(_)) => { | |
1a4d82fc JJ |
1803 | self.tcx().sess.bug( |
1804 | &format!( | |
62682a34 SL |
1805 | "asked to assemble builtin bounds of unexpected type: {:?}", |
1806 | self_ty)); | |
1a4d82fc JJ |
1807 | } |
1808 | }; | |
1809 | ||
c34b1796 AL |
1810 | fn ok_if<'tcx>(v: Vec<Ty<'tcx>>) |
1811 | -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>> { | |
1812 | Ok(If(ty::Binder(v))) | |
1813 | } | |
1814 | ||
1815 | fn nominal<'cx, 'tcx>(bound: ty::BuiltinBound, | |
1a4d82fc | 1816 | types: Vec<Ty<'tcx>>) |
c34b1796 | 1817 | -> Result<BuiltinBoundConditions<'tcx>, SelectionError<'tcx>> |
1a4d82fc JJ |
1818 | { |
1819 | // First check for markers and other nonsense. | |
1a4d82fc | 1820 | match bound { |
c34b1796 AL |
1821 | // Fallback to whatever user-defined impls exist in this case. |
1822 | ty::BoundCopy => Ok(ParameterBuiltin), | |
1a4d82fc | 1823 | |
c34b1796 AL |
1824 | // Sized if all the component types are sized. |
1825 | ty::BoundSized => ok_if(types), | |
1826 | ||
1827 | // Shouldn't be coming through here. | |
1828 | ty::BoundSend | ty::BoundSync => unreachable!(), | |
1829 | } | |
1830 | } | |
1831 | } | |
1832 | ||
1833 | /// For default impls, we need to break apart a type into its | |
1834 | /// "constituent types" -- meaning, the types that it contains. | |
1835 | /// | |
1836 | /// Here are some (simple) examples: | |
1837 | /// | |
1838 | /// ``` | |
1839 | /// (i32, u32) -> [i32, u32] | |
1840 | /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32] | |
1841 | /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32] | |
1842 | /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32] | |
1843 | /// ``` | |
c1a9b12d | 1844 | fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> { |
c34b1796 | 1845 | match t.sty { |
62682a34 SL |
1846 | ty::TyUint(_) | |
1847 | ty::TyInt(_) | | |
1848 | ty::TyBool | | |
1849 | ty::TyFloat(_) | | |
1850 | ty::TyBareFn(..) | | |
1851 | ty::TyStr | | |
1852 | ty::TyError | | |
1853 | ty::TyInfer(ty::IntVar(_)) | | |
1854 | ty::TyInfer(ty::FloatVar(_)) | | |
1855 | ty::TyChar => { | |
c1a9b12d | 1856 | Vec::new() |
c34b1796 AL |
1857 | } |
1858 | ||
62682a34 SL |
1859 | ty::TyTrait(..) | |
1860 | ty::TyParam(..) | | |
1861 | ty::TyProjection(..) | | |
1862 | ty::TyInfer(ty::TyVar(_)) | | |
1863 | ty::TyInfer(ty::FreshTy(_)) | | |
1864 | ty::TyInfer(ty::FreshIntTy(_)) | | |
1865 | ty::TyInfer(ty::FreshFloatTy(_)) => { | |
c34b1796 AL |
1866 | self.tcx().sess.bug( |
1867 | &format!( | |
62682a34 SL |
1868 | "asked to assemble constituent types of unexpected type: {:?}", |
1869 | t)); | |
c34b1796 AL |
1870 | } |
1871 | ||
62682a34 | 1872 | ty::TyBox(referent_ty) => { // Box<T> |
c1a9b12d | 1873 | vec![referent_ty] |
c34b1796 AL |
1874 | } |
1875 | ||
c1a9b12d SL |
1876 | ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) | |
1877 | ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => { | |
1878 | vec![element_ty] | |
c34b1796 AL |
1879 | }, |
1880 | ||
62682a34 | 1881 | ty::TyArray(element_ty, _) | ty::TySlice(element_ty) => { |
c1a9b12d | 1882 | vec![element_ty] |
c34b1796 | 1883 | } |
1a4d82fc | 1884 | |
62682a34 | 1885 | ty::TyTuple(ref tys) => { |
c34b1796 | 1886 | // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet |
c1a9b12d SL |
1887 | tys.clone() |
1888 | } | |
1889 | ||
b039eaaf | 1890 | ty::TyClosure(_, ref substs) => { |
c1a9b12d SL |
1891 | // FIXME(#27086). We are invariant w/r/t our |
1892 | // substs.func_substs, but we don't see them as | |
1893 | // constituent types; this seems RIGHT but also like | |
1894 | // something that a normal type couldn't simulate. Is | |
1895 | // this just a gap with the way that PhantomData and | |
1896 | // OIBIT interact? That is, there is no way to say | |
1897 | // "make me invariant with respect to this TYPE, but | |
1898 | // do not act as though I can reach it" | |
c1a9b12d | 1899 | substs.upvar_tys.clone() |
c34b1796 AL |
1900 | } |
1901 | ||
1902 | // for `PhantomData<T>`, we pass `T` | |
e9174d1e | 1903 | ty::TyStruct(def, substs) if def.is_phantom_data() => { |
c1a9b12d | 1904 | substs.types.get_slice(TypeSpace).to_vec() |
c34b1796 | 1905 | } |
1a4d82fc | 1906 | |
e9174d1e SL |
1907 | ty::TyStruct(def, substs) | ty::TyEnum(def, substs) => { |
1908 | def.all_fields() | |
1909 | .map(|f| f.ty(self.tcx(), substs)) | |
1910 | .collect() | |
c34b1796 AL |
1911 | } |
1912 | } | |
1913 | } | |
1914 | ||
1915 | fn collect_predicates_for_types(&mut self, | |
1916 | obligation: &TraitObligation<'tcx>, | |
e9174d1e | 1917 | trait_def_id: DefId, |
c34b1796 AL |
1918 | types: ty::Binder<Vec<Ty<'tcx>>>) |
1919 | -> Vec<PredicateObligation<'tcx>> | |
1920 | { | |
1921 | let derived_cause = match self.tcx().lang_items.to_builtin_kind(trait_def_id) { | |
1922 | Some(_) => { | |
1923 | self.derived_cause(obligation, BuiltinDerivedObligation) | |
1924 | }, | |
1925 | None => { | |
1926 | self.derived_cause(obligation, ImplDerivedObligation) | |
1927 | } | |
1928 | }; | |
1929 | ||
1930 | // Because the types were potentially derived from | |
1931 | // higher-ranked obligations they may reference late-bound | |
1932 | // regions. For example, `for<'a> Foo<&'a int> : Copy` would | |
1933 | // yield a type like `for<'a> &'a int`. In general, we | |
1934 | // maintain the invariant that we never manipulate bound | |
1935 | // regions, so we have to process these bound regions somehow. | |
1936 | // | |
1937 | // The strategy is to: | |
1938 | // | |
1939 | // 1. Instantiate those regions to skolemized regions (e.g., | |
1940 | // `for<'a> &'a int` becomes `&0 int`. | |
1941 | // 2. Produce something like `&'0 int : Copy` | |
1942 | // 3. Re-bind the regions back to `for<'a> &'a int : Copy` | |
1943 | ||
1944 | // Move the binder into the individual types | |
1945 | let bound_types: Vec<ty::Binder<Ty<'tcx>>> = | |
1946 | types.skip_binder() | |
1947 | .iter() | |
1948 | .map(|&nested_ty| ty::Binder(nested_ty)) | |
1949 | .collect(); | |
1950 | ||
1951 | // For each type, produce a vector of resulting obligations | |
1952 | let obligations: Result<Vec<Vec<_>>, _> = bound_types.iter().map(|nested_ty| { | |
1953 | self.infcx.commit_if_ok(|snapshot| { | |
1954 | let (skol_ty, skol_map) = | |
1955 | self.infcx().skolemize_late_bound_regions(nested_ty, snapshot); | |
1956 | let Normalized { value: normalized_ty, mut obligations } = | |
1957 | project::normalize_with_depth(self, | |
1958 | obligation.cause.clone(), | |
1959 | obligation.recursion_depth + 1, | |
1960 | &skol_ty); | |
1961 | let skol_obligation = | |
d9579d0f AL |
1962 | util::predicate_for_trait_def(self.tcx(), |
1963 | derived_cause.clone(), | |
1964 | trait_def_id, | |
1965 | obligation.recursion_depth + 1, | |
1966 | normalized_ty, | |
1967 | vec![]); | |
c34b1796 AL |
1968 | obligations.push(skol_obligation); |
1969 | Ok(self.infcx().plug_leaks(skol_map, snapshot, &obligations)) | |
1970 | }) | |
1971 | }).collect(); | |
1972 | ||
1973 | // Flatten those vectors (couldn't do it above due `collect`) | |
1974 | match obligations { | |
62682a34 | 1975 | Ok(obligations) => obligations.into_iter().flat_map(|o| o).collect(), |
c34b1796 | 1976 | Err(ErrorReported) => Vec::new(), |
1a4d82fc JJ |
1977 | } |
1978 | } | |
1979 | ||
1980 | /////////////////////////////////////////////////////////////////////////// | |
1981 | // CONFIRMATION | |
1982 | // | |
1983 | // Confirmation unifies the output type parameters of the trait | |
1984 | // with the values found in the obligation, possibly yielding a | |
c34b1796 | 1985 | // type error. See `README.md` for more details. |
1a4d82fc JJ |
1986 | |
1987 | fn confirm_candidate(&mut self, | |
1988 | obligation: &TraitObligation<'tcx>, | |
1989 | candidate: SelectionCandidate<'tcx>) | |
1990 | -> Result<Selection<'tcx>,SelectionError<'tcx>> | |
1991 | { | |
62682a34 SL |
1992 | debug!("confirm_candidate({:?}, {:?})", |
1993 | obligation, | |
1994 | candidate); | |
1a4d82fc JJ |
1995 | |
1996 | match candidate { | |
1997 | BuiltinCandidate(builtin_bound) => { | |
1998 | Ok(VtableBuiltin( | |
1999 | try!(self.confirm_builtin_candidate(obligation, builtin_bound)))) | |
2000 | } | |
2001 | ||
2002 | ErrorCandidate => { | |
62682a34 | 2003 | Ok(VtableBuiltin(VtableBuiltinData { nested: vec![] })) |
1a4d82fc JJ |
2004 | } |
2005 | ||
2006 | ParamCandidate(param) => { | |
85aaf69f SL |
2007 | let obligations = self.confirm_param_candidate(obligation, param); |
2008 | Ok(VtableParam(obligations)) | |
1a4d82fc JJ |
2009 | } |
2010 | ||
c34b1796 AL |
2011 | DefaultImplCandidate(trait_def_id) => { |
2012 | let data = self.confirm_default_impl_candidate(obligation, trait_def_id); | |
2013 | Ok(VtableDefaultImpl(data)) | |
2014 | } | |
2015 | ||
2016 | DefaultImplObjectCandidate(trait_def_id) => { | |
2017 | let data = self.confirm_default_impl_object_candidate(obligation, trait_def_id); | |
2018 | Ok(VtableDefaultImpl(data)) | |
2019 | } | |
2020 | ||
1a4d82fc JJ |
2021 | ImplCandidate(impl_def_id) => { |
2022 | let vtable_impl = | |
2023 | try!(self.confirm_impl_candidate(obligation, impl_def_id)); | |
2024 | Ok(VtableImpl(vtable_impl)) | |
2025 | } | |
2026 | ||
85aaf69f | 2027 | ClosureCandidate(closure_def_id, substs) => { |
62682a34 | 2028 | let vtable_closure = |
c1a9b12d | 2029 | try!(self.confirm_closure_candidate(obligation, closure_def_id, substs)); |
62682a34 | 2030 | Ok(VtableClosure(vtable_closure)) |
1a4d82fc JJ |
2031 | } |
2032 | ||
c34b1796 AL |
2033 | BuiltinObjectCandidate => { |
2034 | // This indicates something like `(Trait+Send) : | |
2035 | // Send`. In this case, we know that this holds | |
2036 | // because that's what the object type is telling us, | |
2037 | // and there's really no additional obligations to | |
2038 | // prove and no types in particular to unify etc. | |
2039 | Ok(VtableParam(Vec::new())) | |
2040 | } | |
2041 | ||
1a4d82fc JJ |
2042 | ObjectCandidate => { |
2043 | let data = self.confirm_object_candidate(obligation); | |
2044 | Ok(VtableObject(data)) | |
2045 | } | |
2046 | ||
2047 | FnPointerCandidate => { | |
2048 | let fn_type = | |
2049 | try!(self.confirm_fn_pointer_candidate(obligation)); | |
2050 | Ok(VtableFnPointer(fn_type)) | |
2051 | } | |
2052 | ||
2053 | ProjectionCandidate => { | |
2054 | self.confirm_projection_candidate(obligation); | |
85aaf69f | 2055 | Ok(VtableParam(Vec::new())) |
1a4d82fc | 2056 | } |
d9579d0f AL |
2057 | |
2058 | BuiltinUnsizeCandidate => { | |
2059 | let data = try!(self.confirm_builtin_unsize_candidate(obligation)); | |
2060 | Ok(VtableBuiltin(data)) | |
2061 | } | |
1a4d82fc JJ |
2062 | } |
2063 | } | |
2064 | ||
2065 | fn confirm_projection_candidate(&mut self, | |
2066 | obligation: &TraitObligation<'tcx>) | |
2067 | { | |
2068 | let _: Result<(),()> = | |
c34b1796 | 2069 | self.infcx.commit_if_ok(|snapshot| { |
1a4d82fc JJ |
2070 | let result = |
2071 | self.match_projection_obligation_against_bounds_from_trait(obligation, | |
2072 | snapshot); | |
2073 | assert!(result); | |
2074 | Ok(()) | |
2075 | }); | |
2076 | } | |
2077 | ||
2078 | fn confirm_param_candidate(&mut self, | |
2079 | obligation: &TraitObligation<'tcx>, | |
2080 | param: ty::PolyTraitRef<'tcx>) | |
85aaf69f | 2081 | -> Vec<PredicateObligation<'tcx>> |
1a4d82fc | 2082 | { |
62682a34 SL |
2083 | debug!("confirm_param_candidate({:?},{:?})", |
2084 | obligation, | |
2085 | param); | |
1a4d82fc JJ |
2086 | |
2087 | // During evaluation, we already checked that this | |
2088 | // where-clause trait-ref could be unified with the obligation | |
2089 | // trait-ref. Repeat that unification now without any | |
2090 | // transactional boundary; it should not fail. | |
85aaf69f SL |
2091 | match self.match_where_clause_trait_ref(obligation, param.clone()) { |
2092 | Ok(obligations) => obligations, | |
2093 | Err(()) => { | |
1a4d82fc | 2094 | self.tcx().sess.bug( |
62682a34 SL |
2095 | &format!("Where clause `{:?}` was applicable to `{:?}` but now is not", |
2096 | param, | |
2097 | obligation)); | |
1a4d82fc JJ |
2098 | } |
2099 | } | |
2100 | } | |
2101 | ||
2102 | fn confirm_builtin_candidate(&mut self, | |
2103 | obligation: &TraitObligation<'tcx>, | |
2104 | bound: ty::BuiltinBound) | |
2105 | -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, | |
2106 | SelectionError<'tcx>> | |
2107 | { | |
62682a34 SL |
2108 | debug!("confirm_builtin_candidate({:?})", |
2109 | obligation); | |
1a4d82fc JJ |
2110 | |
2111 | match try!(self.builtin_bound(bound, obligation)) { | |
2112 | If(nested) => Ok(self.vtable_builtin_data(obligation, bound, nested)), | |
2113 | AmbiguousBuiltin | ParameterBuiltin => { | |
2114 | self.tcx().sess.span_bug( | |
2115 | obligation.cause.span, | |
62682a34 SL |
2116 | &format!("builtin bound for {:?} was ambig", |
2117 | obligation)); | |
1a4d82fc JJ |
2118 | } |
2119 | } | |
2120 | } | |
2121 | ||
2122 | fn vtable_builtin_data(&mut self, | |
2123 | obligation: &TraitObligation<'tcx>, | |
2124 | bound: ty::BuiltinBound, | |
c34b1796 | 2125 | nested: ty::Binder<Vec<Ty<'tcx>>>) |
1a4d82fc JJ |
2126 | -> VtableBuiltinData<PredicateObligation<'tcx>> |
2127 | { | |
c34b1796 AL |
2128 | let trait_def = match self.tcx().lang_items.from_builtin_kind(bound) { |
2129 | Ok(def_id) => def_id, | |
2130 | Err(_) => { | |
2131 | self.tcx().sess.bug("builtin trait definition not found"); | |
2132 | } | |
1a4d82fc JJ |
2133 | }; |
2134 | ||
c34b1796 AL |
2135 | let obligations = self.collect_predicates_for_types(obligation, trait_def, nested); |
2136 | ||
62682a34 SL |
2137 | debug!("vtable_builtin_data: obligations={:?}", |
2138 | obligations); | |
1a4d82fc JJ |
2139 | |
2140 | VtableBuiltinData { nested: obligations } | |
2141 | } | |
2142 | ||
c34b1796 AL |
2143 | /// This handles the case where a `impl Foo for ..` impl is being used. |
2144 | /// The idea is that the impl applies to `X : Foo` if the following conditions are met: | |
2145 | /// | |
2146 | /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds | |
2147 | /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds. | |
2148 | fn confirm_default_impl_candidate(&mut self, | |
2149 | obligation: &TraitObligation<'tcx>, | |
e9174d1e | 2150 | trait_def_id: DefId) |
c34b1796 AL |
2151 | -> VtableDefaultImplData<PredicateObligation<'tcx>> |
2152 | { | |
62682a34 SL |
2153 | debug!("confirm_default_impl_candidate({:?}, {:?})", |
2154 | obligation, | |
2155 | trait_def_id); | |
c34b1796 AL |
2156 | |
2157 | // binder is moved below | |
2158 | let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty()); | |
c1a9b12d SL |
2159 | let types = self.constituent_types_for_ty(self_ty); |
2160 | self.vtable_default_impl(obligation, trait_def_id, ty::Binder(types)) | |
c34b1796 AL |
2161 | } |
2162 | ||
2163 | fn confirm_default_impl_object_candidate(&mut self, | |
2164 | obligation: &TraitObligation<'tcx>, | |
e9174d1e | 2165 | trait_def_id: DefId) |
c34b1796 AL |
2166 | -> VtableDefaultImplData<PredicateObligation<'tcx>> |
2167 | { | |
62682a34 SL |
2168 | debug!("confirm_default_impl_object_candidate({:?}, {:?})", |
2169 | obligation, | |
2170 | trait_def_id); | |
c34b1796 | 2171 | |
c1a9b12d | 2172 | assert!(self.tcx().has_attr(trait_def_id, "rustc_reflect_like")); |
c34b1796 AL |
2173 | |
2174 | // OK to skip binder, it is reintroduced below | |
2175 | let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty()); | |
2176 | match self_ty.sty { | |
62682a34 | 2177 | ty::TyTrait(ref data) => { |
c34b1796 AL |
2178 | // OK to skip the binder, it is reintroduced below |
2179 | let input_types = data.principal.skip_binder().substs.types.get_slice(TypeSpace); | |
2180 | let assoc_types = data.bounds.projection_bounds | |
2181 | .iter() | |
2182 | .map(|pb| pb.skip_binder().ty); | |
2183 | let all_types: Vec<_> = input_types.iter().cloned() | |
2184 | .chain(assoc_types) | |
2185 | .collect(); | |
2186 | ||
2187 | // reintroduce the two binding levels we skipped, then flatten into one | |
2188 | let all_types = ty::Binder(ty::Binder(all_types)); | |
c1a9b12d | 2189 | let all_types = self.tcx().flatten_late_bound_regions(&all_types); |
c34b1796 AL |
2190 | |
2191 | self.vtable_default_impl(obligation, trait_def_id, all_types) | |
2192 | } | |
2193 | _ => { | |
2194 | self.tcx().sess.bug( | |
2195 | &format!( | |
62682a34 SL |
2196 | "asked to confirm default object implementation for non-object type: {:?}", |
2197 | self_ty)); | |
c34b1796 AL |
2198 | } |
2199 | } | |
2200 | } | |
2201 | ||
2202 | /// See `confirm_default_impl_candidate` | |
2203 | fn vtable_default_impl(&mut self, | |
2204 | obligation: &TraitObligation<'tcx>, | |
e9174d1e | 2205 | trait_def_id: DefId, |
c34b1796 AL |
2206 | nested: ty::Binder<Vec<Ty<'tcx>>>) |
2207 | -> VtableDefaultImplData<PredicateObligation<'tcx>> | |
2208 | { | |
62682a34 | 2209 | debug!("vtable_default_impl_data: nested={:?}", nested); |
c34b1796 AL |
2210 | |
2211 | let mut obligations = self.collect_predicates_for_types(obligation, | |
2212 | trait_def_id, | |
2213 | nested); | |
2214 | ||
62682a34 | 2215 | let trait_obligations: Result<Vec<_>,()> = self.infcx.commit_if_ok(|snapshot| { |
c34b1796 AL |
2216 | let poly_trait_ref = obligation.predicate.to_poly_trait_ref(); |
2217 | let (trait_ref, skol_map) = | |
2218 | self.infcx().skolemize_late_bound_regions(&poly_trait_ref, snapshot); | |
2219 | Ok(self.impl_or_trait_obligations(obligation.cause.clone(), | |
2220 | obligation.recursion_depth + 1, | |
2221 | trait_def_id, | |
2222 | &trait_ref.substs, | |
2223 | skol_map, | |
2224 | snapshot)) | |
2225 | }); | |
2226 | ||
62682a34 SL |
2227 | // no Errors in that code above |
2228 | obligations.append(&mut trait_obligations.unwrap()); | |
c34b1796 | 2229 | |
62682a34 | 2230 | debug!("vtable_default_impl_data: obligations={:?}", obligations); |
c34b1796 AL |
2231 | |
2232 | VtableDefaultImplData { | |
2233 | trait_def_id: trait_def_id, | |
2234 | nested: obligations | |
2235 | } | |
2236 | } | |
2237 | ||
1a4d82fc JJ |
2238 | fn confirm_impl_candidate(&mut self, |
2239 | obligation: &TraitObligation<'tcx>, | |
e9174d1e | 2240 | impl_def_id: DefId) |
1a4d82fc JJ |
2241 | -> Result<VtableImplData<'tcx, PredicateObligation<'tcx>>, |
2242 | SelectionError<'tcx>> | |
2243 | { | |
62682a34 SL |
2244 | debug!("confirm_impl_candidate({:?},{:?})", |
2245 | obligation, | |
2246 | impl_def_id); | |
1a4d82fc JJ |
2247 | |
2248 | // First, create the substitutions by matching the impl again, | |
2249 | // this time not in a probe. | |
c34b1796 | 2250 | self.infcx.commit_if_ok(|snapshot| { |
d9579d0f | 2251 | let (substs, skol_map) = |
1a4d82fc | 2252 | self.rematch_impl(impl_def_id, obligation, |
d9579d0f | 2253 | snapshot); |
62682a34 | 2254 | debug!("confirm_impl_candidate substs={:?}", substs); |
1a4d82fc JJ |
2255 | Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(), |
2256 | obligation.recursion_depth + 1, skol_map, snapshot)) | |
2257 | }) | |
2258 | } | |
2259 | ||
2260 | fn vtable_impl(&mut self, | |
e9174d1e | 2261 | impl_def_id: DefId, |
62682a34 | 2262 | mut substs: Normalized<'tcx, Substs<'tcx>>, |
1a4d82fc | 2263 | cause: ObligationCause<'tcx>, |
c34b1796 | 2264 | recursion_depth: usize, |
1a4d82fc JJ |
2265 | skol_map: infer::SkolemizationMap, |
2266 | snapshot: &infer::CombinedSnapshot) | |
2267 | -> VtableImplData<'tcx, PredicateObligation<'tcx>> | |
2268 | { | |
62682a34 SL |
2269 | debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})", |
2270 | impl_def_id, | |
2271 | substs, | |
1a4d82fc | 2272 | recursion_depth, |
62682a34 | 2273 | skol_map); |
1a4d82fc JJ |
2274 | |
2275 | let mut impl_obligations = | |
c34b1796 AL |
2276 | self.impl_or_trait_obligations(cause, |
2277 | recursion_depth, | |
2278 | impl_def_id, | |
2279 | &substs.value, | |
2280 | skol_map, | |
2281 | snapshot); | |
1a4d82fc | 2282 | |
62682a34 SL |
2283 | debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}", |
2284 | impl_def_id, | |
2285 | impl_obligations); | |
1a4d82fc | 2286 | |
92a42be0 SL |
2287 | // Because of RFC447, the impl-trait-ref and obligations |
2288 | // are sufficient to determine the impl substs, without | |
2289 | // relying on projections in the impl-trait-ref. | |
2290 | // | |
2291 | // e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V` | |
62682a34 | 2292 | impl_obligations.append(&mut substs.obligations); |
1a4d82fc JJ |
2293 | |
2294 | VtableImplData { impl_def_id: impl_def_id, | |
2295 | substs: substs.value, | |
2296 | nested: impl_obligations } | |
2297 | } | |
2298 | ||
2299 | fn confirm_object_candidate(&mut self, | |
2300 | obligation: &TraitObligation<'tcx>) | |
2301 | -> VtableObjectData<'tcx> | |
2302 | { | |
62682a34 SL |
2303 | debug!("confirm_object_candidate({:?})", |
2304 | obligation); | |
1a4d82fc | 2305 | |
c34b1796 AL |
2306 | // FIXME skipping binder here seems wrong -- we should |
2307 | // probably flatten the binder from the obligation and the | |
2308 | // binder from the object. Have to try to make a broken test | |
2309 | // case that results. -nmatsakis | |
2310 | let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder()); | |
1a4d82fc | 2311 | let poly_trait_ref = match self_ty.sty { |
62682a34 | 2312 | ty::TyTrait(ref data) => { |
1a4d82fc JJ |
2313 | data.principal_trait_ref_with_self_ty(self.tcx(), self_ty) |
2314 | } | |
2315 | _ => { | |
2316 | self.tcx().sess.span_bug(obligation.cause.span, | |
2317 | "object candidate with non-object"); | |
2318 | } | |
2319 | }; | |
2320 | ||
c1a9b12d SL |
2321 | let mut upcast_trait_ref = None; |
2322 | let vtable_base; | |
2323 | ||
2324 | { | |
2325 | // We want to find the first supertrait in the list of | |
2326 | // supertraits that we can unify with, and do that | |
2327 | // unification. We know that there is exactly one in the list | |
2328 | // where we can unify because otherwise select would have | |
2329 | // reported an ambiguity. (When we do find a match, also | |
2330 | // record it for later.) | |
2331 | let nonmatching = | |
2332 | util::supertraits(self.tcx(), poly_trait_ref) | |
2333 | .take_while(|&t| { | |
2334 | match | |
2335 | self.infcx.commit_if_ok( | |
2336 | |_| self.match_poly_trait_ref(obligation, t)) | |
2337 | { | |
2338 | Ok(_) => { upcast_trait_ref = Some(t); false } | |
2339 | Err(_) => { true } | |
2340 | } | |
2341 | }); | |
2342 | ||
2343 | // Additionally, for each of the nonmatching predicates that | |
2344 | // we pass over, we sum up the set of number of vtable | |
2345 | // entries, so that we can compute the offset for the selected | |
2346 | // trait. | |
2347 | vtable_base = | |
2348 | nonmatching.map(|t| util::count_own_vtable_entries(self.tcx(), t)) | |
2349 | .sum(); | |
1a4d82fc | 2350 | |
1a4d82fc JJ |
2351 | } |
2352 | ||
c1a9b12d SL |
2353 | VtableObjectData { |
2354 | upcast_trait_ref: upcast_trait_ref.unwrap(), | |
2355 | vtable_base: vtable_base, | |
2356 | } | |
1a4d82fc JJ |
2357 | } |
2358 | ||
2359 | fn confirm_fn_pointer_candidate(&mut self, | |
2360 | obligation: &TraitObligation<'tcx>) | |
2361 | -> Result<ty::Ty<'tcx>,SelectionError<'tcx>> | |
2362 | { | |
62682a34 SL |
2363 | debug!("confirm_fn_pointer_candidate({:?})", |
2364 | obligation); | |
1a4d82fc | 2365 | |
c34b1796 AL |
2366 | // ok to skip binder; it is reintroduced below |
2367 | let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder()); | |
c1a9b12d | 2368 | let sig = self_ty.fn_sig(); |
c34b1796 | 2369 | let trait_ref = |
85aaf69f SL |
2370 | util::closure_trait_ref_and_return_type(self.tcx(), |
2371 | obligation.predicate.def_id(), | |
2372 | self_ty, | |
2373 | sig, | |
c34b1796 AL |
2374 | util::TupleArgumentsFlag::Yes) |
2375 | .map_bound(|(trait_ref, _)| trait_ref); | |
1a4d82fc JJ |
2376 | |
2377 | try!(self.confirm_poly_trait_refs(obligation.cause.clone(), | |
2378 | obligation.predicate.to_poly_trait_ref(), | |
2379 | trait_ref)); | |
2380 | Ok(self_ty) | |
2381 | } | |
2382 | ||
85aaf69f SL |
2383 | fn confirm_closure_candidate(&mut self, |
2384 | obligation: &TraitObligation<'tcx>, | |
e9174d1e | 2385 | closure_def_id: DefId, |
c1a9b12d | 2386 | substs: &ty::ClosureSubsts<'tcx>) |
62682a34 SL |
2387 | -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, |
2388 | SelectionError<'tcx>> | |
1a4d82fc | 2389 | { |
62682a34 SL |
2390 | debug!("confirm_closure_candidate({:?},{:?},{:?})", |
2391 | obligation, | |
2392 | closure_def_id, | |
2393 | substs); | |
1a4d82fc | 2394 | |
62682a34 SL |
2395 | let Normalized { |
2396 | value: trait_ref, | |
2397 | obligations | |
2398 | } = self.closure_trait_ref(obligation, closure_def_id, substs); | |
1a4d82fc | 2399 | |
62682a34 SL |
2400 | debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})", |
2401 | closure_def_id, | |
2402 | trait_ref, | |
2403 | obligations); | |
1a4d82fc | 2404 | |
62682a34 SL |
2405 | try!(self.confirm_poly_trait_refs(obligation.cause.clone(), |
2406 | obligation.predicate.to_poly_trait_ref(), | |
2407 | trait_ref)); | |
2408 | ||
2409 | Ok(VtableClosureData { | |
2410 | closure_def_id: closure_def_id, | |
2411 | substs: substs.clone(), | |
2412 | nested: obligations | |
2413 | }) | |
1a4d82fc JJ |
2414 | } |
2415 | ||
85aaf69f | 2416 | /// In the case of closure types and fn pointers, |
1a4d82fc JJ |
2417 | /// we currently treat the input type parameters on the trait as |
2418 | /// outputs. This means that when we have a match we have only | |
2419 | /// considered the self type, so we have to go back and make sure | |
2420 | /// to relate the argument types too. This is kind of wrong, but | |
2421 | /// since we control the full set of impls, also not that wrong, | |
2422 | /// and it DOES yield better error messages (since we don't report | |
2423 | /// errors as if there is no applicable impl, but rather report | |
2424 | /// errors are about mismatched argument types. | |
2425 | /// | |
b039eaaf | 2426 | /// Here is an example. Imagine we have a closure expression |
1a4d82fc JJ |
2427 | /// and we desugared it so that the type of the expression is |
2428 | /// `Closure`, and `Closure` expects an int as argument. Then it | |
2429 | /// is "as if" the compiler generated this impl: | |
2430 | /// | |
2431 | /// impl Fn(int) for Closure { ... } | |
2432 | /// | |
c34b1796 | 2433 | /// Now imagine our obligation is `Fn(usize) for Closure`. So far |
1a4d82fc | 2434 | /// we have matched the self-type `Closure`. At this point we'll |
c34b1796 | 2435 | /// compare the `int` to `usize` and generate an error. |
1a4d82fc JJ |
2436 | /// |
2437 | /// Note that this checking occurs *after* the impl has selected, | |
2438 | /// because these output type parameters should not affect the | |
2439 | /// selection of the impl. Therefore, if there is a mismatch, we | |
2440 | /// report an error to the user. | |
2441 | fn confirm_poly_trait_refs(&mut self, | |
2442 | obligation_cause: ObligationCause, | |
2443 | obligation_trait_ref: ty::PolyTraitRef<'tcx>, | |
2444 | expected_trait_ref: ty::PolyTraitRef<'tcx>) | |
2445 | -> Result<(), SelectionError<'tcx>> | |
2446 | { | |
92a42be0 | 2447 | let origin = TypeOrigin::RelateOutputImplTypes(obligation_cause.span); |
1a4d82fc JJ |
2448 | |
2449 | let obligation_trait_ref = obligation_trait_ref.clone(); | |
2450 | match self.infcx.sub_poly_trait_refs(false, | |
2451 | origin, | |
2452 | expected_trait_ref.clone(), | |
2453 | obligation_trait_ref.clone()) { | |
2454 | Ok(()) => Ok(()), | |
2455 | Err(e) => Err(OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e)) | |
2456 | } | |
2457 | } | |
2458 | ||
d9579d0f AL |
2459 | fn confirm_builtin_unsize_candidate(&mut self, |
2460 | obligation: &TraitObligation<'tcx>,) | |
2461 | -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, | |
2462 | SelectionError<'tcx>> { | |
2463 | let tcx = self.tcx(); | |
2464 | ||
2465 | // assemble_candidates_for_unsizing should ensure there are no late bound | |
2466 | // regions here. See the comment there for more details. | |
2467 | let source = self.infcx.shallow_resolve( | |
c1a9b12d | 2468 | tcx.no_late_bound_regions(&obligation.self_ty()).unwrap()); |
d9579d0f AL |
2469 | let target = self.infcx.shallow_resolve(obligation.predicate.0.input_types()[0]); |
2470 | ||
62682a34 SL |
2471 | debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})", |
2472 | source, target); | |
d9579d0f AL |
2473 | |
2474 | let mut nested = vec![]; | |
2475 | match (&source.sty, &target.sty) { | |
2476 | // Trait+Kx+'a -> Trait+Ky+'b (upcasts). | |
62682a34 | 2477 | (&ty::TyTrait(ref data_a), &ty::TyTrait(ref data_b)) => { |
d9579d0f AL |
2478 | // See assemble_candidates_for_unsizing for more info. |
2479 | let bounds = ty::ExistentialBounds { | |
2480 | region_bound: data_b.bounds.region_bound, | |
2481 | builtin_bounds: data_b.bounds.builtin_bounds, | |
2482 | projection_bounds: data_a.bounds.projection_bounds.clone(), | |
2483 | }; | |
2484 | ||
c1a9b12d | 2485 | let new_trait = tcx.mk_trait(data_a.principal.clone(), bounds); |
92a42be0 | 2486 | let origin = TypeOrigin::Misc(obligation.cause.span); |
d9579d0f AL |
2487 | if self.infcx.sub_types(false, origin, new_trait, target).is_err() { |
2488 | return Err(Unimplemented); | |
2489 | } | |
2490 | ||
2491 | // Register one obligation for 'a: 'b. | |
2492 | let cause = ObligationCause::new(obligation.cause.span, | |
2493 | obligation.cause.body_id, | |
2494 | ObjectCastObligation(target)); | |
2495 | let outlives = ty::OutlivesPredicate(data_a.bounds.region_bound, | |
2496 | data_b.bounds.region_bound); | |
2497 | nested.push(Obligation::with_depth(cause, | |
2498 | obligation.recursion_depth + 1, | |
c1a9b12d | 2499 | ty::Binder(outlives).to_predicate())); |
d9579d0f AL |
2500 | } |
2501 | ||
2502 | // T -> Trait. | |
62682a34 | 2503 | (_, &ty::TyTrait(ref data)) => { |
d9579d0f AL |
2504 | let object_did = data.principal_def_id(); |
2505 | if !object_safety::is_object_safe(tcx, object_did) { | |
2506 | return Err(TraitNotObjectSafe(object_did)); | |
2507 | } | |
2508 | ||
2509 | let cause = ObligationCause::new(obligation.cause.span, | |
2510 | obligation.cause.body_id, | |
2511 | ObjectCastObligation(target)); | |
2512 | let mut push = |predicate| { | |
2513 | nested.push(Obligation::with_depth(cause.clone(), | |
2514 | obligation.recursion_depth + 1, | |
2515 | predicate)); | |
2516 | }; | |
2517 | ||
2518 | // Create the obligation for casting from T to Trait. | |
c1a9b12d | 2519 | push(data.principal_trait_ref_with_self_ty(tcx, source).to_predicate()); |
d9579d0f AL |
2520 | |
2521 | // We can only make objects from sized types. | |
2522 | let mut builtin_bounds = data.bounds.builtin_bounds; | |
2523 | builtin_bounds.insert(ty::BoundSized); | |
2524 | ||
2525 | // Create additional obligations for all the various builtin | |
2526 | // bounds attached to the object cast. (In other words, if the | |
2527 | // object type is Foo+Send, this would create an obligation | |
2528 | // for the Send check.) | |
2529 | for bound in &builtin_bounds { | |
2530 | if let Ok(tr) = util::trait_ref_for_builtin_bound(tcx, bound, source) { | |
c1a9b12d | 2531 | push(tr.to_predicate()); |
d9579d0f AL |
2532 | } else { |
2533 | return Err(Unimplemented); | |
2534 | } | |
2535 | } | |
2536 | ||
2537 | // Create obligations for the projection predicates. | |
2538 | for bound in data.projection_bounds_with_self_ty(tcx, source) { | |
c1a9b12d | 2539 | push(bound.to_predicate()); |
d9579d0f AL |
2540 | } |
2541 | ||
2542 | // If the type is `Foo+'a`, ensures that the type | |
2543 | // being cast to `Foo+'a` outlives `'a`: | |
2544 | let outlives = ty::OutlivesPredicate(source, | |
2545 | data.bounds.region_bound); | |
c1a9b12d | 2546 | push(ty::Binder(outlives).to_predicate()); |
d9579d0f AL |
2547 | } |
2548 | ||
2549 | // [T; n] -> [T]. | |
62682a34 | 2550 | (&ty::TyArray(a, _), &ty::TySlice(b)) => { |
92a42be0 | 2551 | let origin = TypeOrigin::Misc(obligation.cause.span); |
d9579d0f AL |
2552 | if self.infcx.sub_types(false, origin, a, b).is_err() { |
2553 | return Err(Unimplemented); | |
2554 | } | |
2555 | } | |
2556 | ||
2557 | // Struct<T> -> Struct<U>. | |
e9174d1e SL |
2558 | (&ty::TyStruct(def, substs_a), &ty::TyStruct(_, substs_b)) => { |
2559 | let fields = def | |
2560 | .all_fields() | |
2561 | .map(|f| f.unsubst_ty()) | |
2562 | .collect::<Vec<_>>(); | |
d9579d0f | 2563 | |
62682a34 SL |
2564 | // The last field of the structure has to exist and contain type parameters. |
2565 | let field = if let Some(&field) = fields.last() { | |
2566 | field | |
d9579d0f AL |
2567 | } else { |
2568 | return Err(Unimplemented); | |
2569 | }; | |
62682a34 | 2570 | let mut ty_params = vec![]; |
c1a9b12d | 2571 | for ty in field.walk() { |
62682a34 SL |
2572 | if let ty::TyParam(p) = ty.sty { |
2573 | assert!(p.space == TypeSpace); | |
2574 | let idx = p.idx as usize; | |
2575 | if !ty_params.contains(&idx) { | |
2576 | ty_params.push(idx); | |
2577 | } | |
2578 | } | |
c1a9b12d | 2579 | } |
62682a34 SL |
2580 | if ty_params.is_empty() { |
2581 | return Err(Unimplemented); | |
2582 | } | |
d9579d0f | 2583 | |
62682a34 SL |
2584 | // Replace type parameters used in unsizing with |
2585 | // TyError and ensure they do not affect any other fields. | |
d9579d0f AL |
2586 | // This could be checked after type collection for any struct |
2587 | // with a potentially unsized trailing field. | |
2588 | let mut new_substs = substs_a.clone(); | |
62682a34 SL |
2589 | for &i in &ty_params { |
2590 | new_substs.types.get_mut_slice(TypeSpace)[i] = tcx.types.err; | |
2591 | } | |
c1a9b12d SL |
2592 | for &ty in fields.split_last().unwrap().1 { |
2593 | if ty.subst(tcx, &new_substs).references_error() { | |
d9579d0f AL |
2594 | return Err(Unimplemented); |
2595 | } | |
2596 | } | |
2597 | ||
62682a34 SL |
2598 | // Extract Field<T> and Field<U> from Struct<T> and Struct<U>. |
2599 | let inner_source = field.subst(tcx, substs_a); | |
2600 | let inner_target = field.subst(tcx, substs_b); | |
d9579d0f | 2601 | |
62682a34 SL |
2602 | // Check that the source structure with the target's |
2603 | // type parameters is a subtype of the target. | |
2604 | for &i in &ty_params { | |
2605 | let param_b = *substs_b.types.get(TypeSpace, i); | |
2606 | new_substs.types.get_mut_slice(TypeSpace)[i] = param_b; | |
2607 | } | |
e9174d1e | 2608 | let new_struct = tcx.mk_struct(def, tcx.mk_substs(new_substs)); |
92a42be0 | 2609 | let origin = TypeOrigin::Misc(obligation.cause.span); |
d9579d0f AL |
2610 | if self.infcx.sub_types(false, origin, new_struct, target).is_err() { |
2611 | return Err(Unimplemented); | |
2612 | } | |
2613 | ||
62682a34 | 2614 | // Construct the nested Field<T>: Unsize<Field<U>> predicate. |
d9579d0f AL |
2615 | nested.push(util::predicate_for_trait_def(tcx, |
2616 | obligation.cause.clone(), | |
2617 | obligation.predicate.def_id(), | |
2618 | obligation.recursion_depth + 1, | |
2619 | inner_source, | |
2620 | vec![inner_target])); | |
2621 | } | |
2622 | ||
2623 | _ => unreachable!() | |
2624 | }; | |
2625 | ||
62682a34 | 2626 | Ok(VtableBuiltinData { nested: nested }) |
d9579d0f AL |
2627 | } |
2628 | ||
1a4d82fc JJ |
2629 | /////////////////////////////////////////////////////////////////////////// |
2630 | // Matching | |
2631 | // | |
2632 | // Matching is a common path used for both evaluation and | |
2633 | // confirmation. It basically unifies types that appear in impls | |
2634 | // and traits. This does affect the surrounding environment; | |
2635 | // therefore, when used during evaluation, match routines must be | |
2636 | // run inside of a `probe()` so that their side-effects are | |
2637 | // contained. | |
2638 | ||
2639 | fn rematch_impl(&mut self, | |
e9174d1e | 2640 | impl_def_id: DefId, |
1a4d82fc | 2641 | obligation: &TraitObligation<'tcx>, |
d9579d0f AL |
2642 | snapshot: &infer::CombinedSnapshot) |
2643 | -> (Normalized<'tcx, Substs<'tcx>>, infer::SkolemizationMap) | |
1a4d82fc | 2644 | { |
d9579d0f AL |
2645 | match self.match_impl(impl_def_id, obligation, snapshot) { |
2646 | Ok((substs, skol_map)) => (substs, skol_map), | |
1a4d82fc JJ |
2647 | Err(()) => { |
2648 | self.tcx().sess.bug( | |
62682a34 SL |
2649 | &format!("Impl {:?} was matchable against {:?} but now is not", |
2650 | impl_def_id, | |
2651 | obligation)); | |
1a4d82fc JJ |
2652 | } |
2653 | } | |
2654 | } | |
2655 | ||
2656 | fn match_impl(&mut self, | |
e9174d1e | 2657 | impl_def_id: DefId, |
1a4d82fc | 2658 | obligation: &TraitObligation<'tcx>, |
d9579d0f AL |
2659 | snapshot: &infer::CombinedSnapshot) |
2660 | -> Result<(Normalized<'tcx, Substs<'tcx>>, | |
2661 | infer::SkolemizationMap), ()> | |
1a4d82fc | 2662 | { |
c1a9b12d | 2663 | let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap(); |
1a4d82fc JJ |
2664 | |
2665 | // Before we create the substitutions and everything, first | |
2666 | // consider a "quick reject". This avoids creating more types | |
2667 | // and so forth that we need to. | |
d9579d0f | 2668 | if self.fast_reject_trait_refs(obligation, &impl_trait_ref) { |
1a4d82fc JJ |
2669 | return Err(()); |
2670 | } | |
2671 | ||
d9579d0f AL |
2672 | let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions( |
2673 | &obligation.predicate, | |
2674 | snapshot); | |
2675 | let skol_obligation_trait_ref = skol_obligation.trait_ref; | |
2676 | ||
c34b1796 AL |
2677 | let impl_substs = util::fresh_type_vars_for_impl(self.infcx, |
2678 | obligation.cause.span, | |
2679 | impl_def_id); | |
1a4d82fc JJ |
2680 | |
2681 | let impl_trait_ref = impl_trait_ref.subst(self.tcx(), | |
2682 | &impl_substs); | |
2683 | ||
2684 | let impl_trait_ref = | |
2685 | project::normalize_with_depth(self, | |
2686 | obligation.cause.clone(), | |
2687 | obligation.recursion_depth + 1, | |
2688 | &impl_trait_ref); | |
2689 | ||
62682a34 SL |
2690 | debug!("match_impl(impl_def_id={:?}, obligation={:?}, \ |
2691 | impl_trait_ref={:?}, skol_obligation_trait_ref={:?})", | |
2692 | impl_def_id, | |
2693 | obligation, | |
2694 | impl_trait_ref, | |
2695 | skol_obligation_trait_ref); | |
1a4d82fc | 2696 | |
92a42be0 SL |
2697 | let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span); |
2698 | if let Err(e) = self.infcx.eq_trait_refs(false, | |
2699 | origin, | |
2700 | impl_trait_ref.value.clone(), | |
2701 | skol_obligation_trait_ref) { | |
2702 | debug!("match_impl: failed eq_trait_refs due to `{}`", e); | |
c34b1796 | 2703 | return Err(()); |
1a4d82fc JJ |
2704 | } |
2705 | ||
d9579d0f | 2706 | if let Err(e) = self.infcx.leak_check(&skol_map, snapshot) { |
62682a34 | 2707 | debug!("match_impl: failed leak check due to `{}`", e); |
c34b1796 | 2708 | return Err(()); |
1a4d82fc JJ |
2709 | } |
2710 | ||
62682a34 | 2711 | debug!("match_impl: success impl_substs={:?}", impl_substs); |
d9579d0f | 2712 | Ok((Normalized { |
c34b1796 AL |
2713 | value: impl_substs, |
2714 | obligations: impl_trait_ref.obligations | |
d9579d0f | 2715 | }, skol_map)) |
1a4d82fc JJ |
2716 | } |
2717 | ||
2718 | fn fast_reject_trait_refs(&mut self, | |
2719 | obligation: &TraitObligation, | |
2720 | impl_trait_ref: &ty::TraitRef) | |
2721 | -> bool | |
2722 | { | |
2723 | // We can avoid creating type variables and doing the full | |
2724 | // substitution if we find that any of the input types, when | |
2725 | // simplified, do not match. | |
2726 | ||
2727 | obligation.predicate.0.input_types().iter() | |
62682a34 | 2728 | .zip(impl_trait_ref.input_types()) |
1a4d82fc JJ |
2729 | .any(|(&obligation_ty, &impl_ty)| { |
2730 | let simplified_obligation_ty = | |
2731 | fast_reject::simplify_type(self.tcx(), obligation_ty, true); | |
2732 | let simplified_impl_ty = | |
2733 | fast_reject::simplify_type(self.tcx(), impl_ty, false); | |
2734 | ||
2735 | simplified_obligation_ty.is_some() && | |
2736 | simplified_impl_ty.is_some() && | |
2737 | simplified_obligation_ty != simplified_impl_ty | |
2738 | }) | |
2739 | } | |
2740 | ||
85aaf69f SL |
2741 | /// Normalize `where_clause_trait_ref` and try to match it against |
2742 | /// `obligation`. If successful, return any predicates that | |
2743 | /// result from the normalization. Normalization is necessary | |
2744 | /// because where-clauses are stored in the parameter environment | |
2745 | /// unnormalized. | |
2746 | fn match_where_clause_trait_ref(&mut self, | |
2747 | obligation: &TraitObligation<'tcx>, | |
2748 | where_clause_trait_ref: ty::PolyTraitRef<'tcx>) | |
2749 | -> Result<Vec<PredicateObligation<'tcx>>,()> | |
2750 | { | |
c34b1796 | 2751 | try!(self.match_poly_trait_ref(obligation, where_clause_trait_ref)); |
85aaf69f SL |
2752 | Ok(Vec::new()) |
2753 | } | |
2754 | ||
2755 | /// Returns `Ok` if `poly_trait_ref` being true implies that the | |
2756 | /// obligation is satisfied. | |
c1a9b12d | 2757 | fn match_poly_trait_ref(&self, |
1a4d82fc | 2758 | obligation: &TraitObligation<'tcx>, |
85aaf69f | 2759 | poly_trait_ref: ty::PolyTraitRef<'tcx>) |
1a4d82fc JJ |
2760 | -> Result<(),()> |
2761 | { | |
62682a34 SL |
2762 | debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}", |
2763 | obligation, | |
2764 | poly_trait_ref); | |
1a4d82fc | 2765 | |
92a42be0 | 2766 | let origin = TypeOrigin::RelateOutputImplTypes(obligation.cause.span); |
1a4d82fc JJ |
2767 | match self.infcx.sub_poly_trait_refs(false, |
2768 | origin, | |
85aaf69f | 2769 | poly_trait_ref, |
1a4d82fc JJ |
2770 | obligation.predicate.to_poly_trait_ref()) { |
2771 | Ok(()) => Ok(()), | |
2772 | Err(_) => Err(()), | |
2773 | } | |
2774 | } | |
2775 | ||
1a4d82fc JJ |
2776 | /////////////////////////////////////////////////////////////////////////// |
2777 | // Miscellany | |
2778 | ||
c34b1796 AL |
2779 | fn match_fresh_trait_refs(&self, |
2780 | previous: &ty::PolyTraitRef<'tcx>, | |
2781 | current: &ty::PolyTraitRef<'tcx>) | |
2782 | -> bool | |
2783 | { | |
e9174d1e | 2784 | let mut matcher = ty::_match::Match::new(self.tcx()); |
c34b1796 AL |
2785 | matcher.relate(previous, current).is_ok() |
2786 | } | |
2787 | ||
1a4d82fc | 2788 | fn push_stack<'o,'s:'o>(&mut self, |
c34b1796 | 2789 | previous_stack: TraitObligationStackList<'s, 'tcx>, |
1a4d82fc JJ |
2790 | obligation: &'o TraitObligation<'tcx>) |
2791 | -> TraitObligationStack<'o, 'tcx> | |
2792 | { | |
2793 | let fresh_trait_ref = | |
2794 | obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener); | |
2795 | ||
2796 | TraitObligationStack { | |
2797 | obligation: obligation, | |
2798 | fresh_trait_ref: fresh_trait_ref, | |
c34b1796 | 2799 | previous: previous_stack, |
1a4d82fc JJ |
2800 | } |
2801 | } | |
2802 | ||
62682a34 SL |
2803 | fn closure_trait_ref_unnormalized(&mut self, |
2804 | obligation: &TraitObligation<'tcx>, | |
e9174d1e | 2805 | closure_def_id: DefId, |
c1a9b12d | 2806 | substs: &ty::ClosureSubsts<'tcx>) |
62682a34 | 2807 | -> ty::PolyTraitRef<'tcx> |
85aaf69f | 2808 | { |
c1a9b12d | 2809 | let closure_type = self.infcx.closure_type(closure_def_id, substs); |
85aaf69f SL |
2810 | let ty::Binder((trait_ref, _)) = |
2811 | util::closure_trait_ref_and_return_type(self.tcx(), | |
2812 | obligation.predicate.def_id(), | |
2813 | obligation.predicate.0.self_ty(), // (1) | |
2814 | &closure_type.sig, | |
2815 | util::TupleArgumentsFlag::No); | |
85aaf69f SL |
2816 | // (1) Feels icky to skip the binder here, but OTOH we know |
2817 | // that the self-type is an unboxed closure type and hence is | |
2818 | // in fact unparameterized (or at least does not reference any | |
2819 | // regions bound in the obligation). Still probably some | |
2820 | // refactoring could make this nicer. | |
2821 | ||
2822 | ty::Binder(trait_ref) | |
2823 | } | |
2824 | ||
62682a34 SL |
2825 | fn closure_trait_ref(&mut self, |
2826 | obligation: &TraitObligation<'tcx>, | |
e9174d1e | 2827 | closure_def_id: DefId, |
c1a9b12d | 2828 | substs: &ty::ClosureSubsts<'tcx>) |
62682a34 SL |
2829 | -> Normalized<'tcx, ty::PolyTraitRef<'tcx>> |
2830 | { | |
2831 | let trait_ref = self.closure_trait_ref_unnormalized( | |
2832 | obligation, closure_def_id, substs); | |
2833 | ||
2834 | // A closure signature can contain associated types which | |
2835 | // must be normalized. | |
2836 | normalize_with_depth(self, | |
2837 | obligation.cause.clone(), | |
2838 | obligation.recursion_depth+1, | |
2839 | &trait_ref) | |
2840 | } | |
2841 | ||
c34b1796 AL |
2842 | /// Returns the obligations that are implied by instantiating an |
2843 | /// impl or trait. The obligations are substituted and fully | |
2844 | /// normalized. This is used when confirming an impl or default | |
2845 | /// impl. | |
2846 | fn impl_or_trait_obligations(&mut self, | |
2847 | cause: ObligationCause<'tcx>, | |
2848 | recursion_depth: usize, | |
e9174d1e | 2849 | def_id: DefId, // of impl or trait |
c34b1796 AL |
2850 | substs: &Substs<'tcx>, // for impl or trait |
2851 | skol_map: infer::SkolemizationMap, | |
2852 | snapshot: &infer::CombinedSnapshot) | |
62682a34 | 2853 | -> Vec<PredicateObligation<'tcx>> |
1a4d82fc | 2854 | { |
62682a34 | 2855 | debug!("impl_or_trait_obligations(def_id={:?})", def_id); |
92a42be0 | 2856 | let tcx = self.tcx(); |
c34b1796 | 2857 | |
92a42be0 SL |
2858 | // To allow for one-pass evaluation of the nested obligation, |
2859 | // each predicate must be preceded by the obligations required | |
2860 | // to normalize it. | |
2861 | // for example, if we have: | |
2862 | // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy | |
2863 | // the impl will have the following predicates: | |
2864 | // <V as Iterator>::Item = U, | |
2865 | // U: Iterator, U: Sized, | |
2866 | // V: Iterator, V: Sized, | |
2867 | // <U as Iterator>::Item: Copy | |
2868 | // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last | |
2869 | // obligation will normalize to `<$0 as Iterator>::Item = $1` and | |
2870 | // `$1: Copy`, so we must ensure the obligations are emitted in | |
2871 | // that order. | |
2872 | let predicates = tcx | |
2873 | .lookup_predicates(def_id) | |
2874 | .predicates.iter() | |
2875 | .flat_map(|predicate| { | |
2876 | let predicate = | |
2877 | normalize_with_depth(self, cause.clone(), recursion_depth, | |
2878 | &predicate.subst(tcx, substs)); | |
2879 | predicate.obligations.into_iter().chain( | |
2880 | Some(Obligation { | |
2881 | cause: cause.clone(), | |
2882 | recursion_depth: recursion_depth, | |
2883 | predicate: predicate.value | |
2884 | })) | |
2885 | }).collect(); | |
2886 | self.infcx().plug_leaks(skol_map, snapshot, &predicates) | |
1a4d82fc JJ |
2887 | } |
2888 | ||
1a4d82fc JJ |
2889 | #[allow(unused_comparisons)] |
2890 | fn derived_cause(&self, | |
2891 | obligation: &TraitObligation<'tcx>, | |
2892 | variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>) | |
2893 | -> ObligationCause<'tcx> | |
2894 | { | |
2895 | /*! | |
2896 | * Creates a cause for obligations that are derived from | |
2897 | * `obligation` by a recursive search (e.g., for a builtin | |
2898 | * bound, or eventually a `impl Foo for ..`). If `obligation` | |
2899 | * is itself a derived obligation, this is just a clone, but | |
2900 | * otherwise we create a "derived obligation" cause so as to | |
2901 | * keep track of the original root obligation for error | |
2902 | * reporting. | |
2903 | */ | |
2904 | ||
2905 | // NOTE(flaper87): As of now, it keeps track of the whole error | |
2906 | // chain. Ideally, we should have a way to configure this either | |
2907 | // by using -Z verbose or just a CLI argument. | |
2908 | if obligation.recursion_depth >= 0 { | |
e9174d1e SL |
2909 | let derived_code = match obligation.cause.code { |
2910 | ObligationCauseCode::RFC1214(ref base_code) => { | |
2911 | let derived_cause = DerivedObligationCause { | |
2912 | parent_trait_ref: obligation.predicate.to_poly_trait_ref(), | |
2913 | parent_code: base_code.clone(), | |
2914 | }; | |
2915 | ObligationCauseCode::RFC1214(Rc::new(variant(derived_cause))) | |
2916 | } | |
2917 | _ => { | |
2918 | let derived_cause = DerivedObligationCause { | |
2919 | parent_trait_ref: obligation.predicate.to_poly_trait_ref(), | |
2920 | parent_code: Rc::new(obligation.cause.code.clone()) | |
2921 | }; | |
2922 | variant(derived_cause) | |
2923 | } | |
1a4d82fc | 2924 | }; |
e9174d1e | 2925 | ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code) |
1a4d82fc JJ |
2926 | } else { |
2927 | obligation.cause.clone() | |
2928 | } | |
2929 | } | |
2930 | } | |
2931 | ||
1a4d82fc JJ |
2932 | impl<'tcx> SelectionCache<'tcx> { |
2933 | pub fn new() -> SelectionCache<'tcx> { | |
2934 | SelectionCache { | |
c34b1796 | 2935 | hashmap: RefCell::new(FnvHashMap()) |
1a4d82fc JJ |
2936 | } |
2937 | } | |
2938 | } | |
2939 | ||
92a42be0 SL |
2940 | impl<'tcx> EvaluationCache<'tcx> { |
2941 | pub fn new() -> EvaluationCache<'tcx> { | |
2942 | EvaluationCache { | |
2943 | hashmap: RefCell::new(FnvHashMap()) | |
2944 | } | |
2945 | } | |
2946 | } | |
2947 | ||
c34b1796 AL |
2948 | impl<'o,'tcx> TraitObligationStack<'o,'tcx> { |
2949 | fn list(&'o self) -> TraitObligationStackList<'o,'tcx> { | |
2950 | TraitObligationStackList::with(self) | |
2951 | } | |
2952 | ||
2953 | fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> { | |
2954 | self.list() | |
2955 | } | |
2956 | } | |
2957 | ||
2958 | #[derive(Copy, Clone)] | |
2959 | struct TraitObligationStackList<'o,'tcx:'o> { | |
2960 | head: Option<&'o TraitObligationStack<'o,'tcx>> | |
2961 | } | |
2962 | ||
2963 | impl<'o,'tcx> TraitObligationStackList<'o,'tcx> { | |
2964 | fn empty() -> TraitObligationStackList<'o,'tcx> { | |
2965 | TraitObligationStackList { head: None } | |
2966 | } | |
2967 | ||
2968 | fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> { | |
2969 | TraitObligationStackList { head: Some(r) } | |
1a4d82fc JJ |
2970 | } |
2971 | } | |
2972 | ||
c34b1796 | 2973 | impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{ |
1a4d82fc JJ |
2974 | type Item = &'o TraitObligationStack<'o,'tcx>; |
2975 | ||
c34b1796 AL |
2976 | fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> { |
2977 | match self.head { | |
1a4d82fc JJ |
2978 | Some(o) => { |
2979 | *self = o.previous; | |
2980 | Some(o) | |
2981 | } | |
c34b1796 | 2982 | None => None |
1a4d82fc JJ |
2983 | } |
2984 | } | |
2985 | } | |
2986 | ||
62682a34 SL |
2987 | impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> { |
2988 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2989 | write!(f, "TraitObligationStack({:?})", self.obligation) | |
1a4d82fc JJ |
2990 | } |
2991 | } | |
2992 | ||
92a42be0 | 2993 | impl EvaluationResult { |
1a4d82fc JJ |
2994 | fn may_apply(&self) -> bool { |
2995 | match *self { | |
2996 | EvaluatedToOk | | |
2997 | EvaluatedToAmbig | | |
92a42be0 | 2998 | EvaluatedToUnknown => true, |
c34b1796 | 2999 | |
92a42be0 | 3000 | EvaluatedToErr => false |
1a4d82fc JJ |
3001 | } |
3002 | } | |
3003 | } | |
3004 | ||
3005 | impl MethodMatchResult { | |
3006 | pub fn may_apply(&self) -> bool { | |
3007 | match *self { | |
3008 | MethodMatched(_) => true, | |
3009 | MethodAmbiguous(_) => true, | |
3010 | MethodDidNotMatch => false, | |
3011 | } | |
3012 | } | |
3013 | } |