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