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