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