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