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