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