]> git.proxmox.com Git - rustc.git/blob - src/librustc/traits/select.rs
New upstream version 1.37.0+dfsg1
[rustc.git] / src / librustc / traits / select.rs
1 // ignore-tidy-filelength
2
3 //! Candidate selection. See the [rustc guide] for more information on how this works.
4 //!
5 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html#selection
6
7 use self::EvaluationResult::*;
8 use self::SelectionCandidate::*;
9
10 use super::coherence::{self, Conflict};
11 use super::project;
12 use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
13 use super::util;
14 use super::DerivedObligationCause;
15 use super::Selection;
16 use super::SelectionResult;
17 use super::TraitNotObjectSafe;
18 use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
19 use super::{IntercrateMode, TraitQueryMode};
20 use super::{ObjectCastObligation, Obligation};
21 use super::{ObligationCause, PredicateObligation, TraitObligation};
22 use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
23 use super::{
24 VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
25 VtableObject, VtableParam, VtableTraitAlias,
26 };
27 use super::{
28 VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
29 VtableGeneratorData, VtableImplData, VtableObjectData, VtableTraitAliasData,
30 };
31
32 use crate::dep_graph::{DepKind, DepNodeIndex};
33 use crate::hir::def_id::DefId;
34 use crate::infer::{CombinedSnapshot, InferCtxt, InferOk, PlaceholderMap, TypeFreshener};
35 use crate::middle::lang_items;
36 use crate::mir::interpret::GlobalId;
37 use crate::ty::fast_reject;
38 use crate::ty::relate::TypeRelation;
39 use crate::ty::subst::{Subst, SubstsRef};
40 use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
41
42 use crate::hir;
43 use rustc_data_structures::bit_set::GrowableBitSet;
44 use rustc_data_structures::sync::Lock;
45 use rustc_target::spec::abi::Abi;
46 use std::cell::{Cell, RefCell};
47 use std::cmp;
48 use std::fmt::{self, Display};
49 use std::iter;
50 use std::rc::Rc;
51 use crate::util::nodemap::{FxHashMap, FxHashSet};
52
53 pub struct SelectionContext<'cx, 'tcx> {
54 infcx: &'cx InferCtxt<'cx, 'tcx>,
55
56 /// Freshener used specifically for entries on the obligation
57 /// stack. This ensures that all entries on the stack at one time
58 /// will have the same set of placeholder entries, which is
59 /// important for checking for trait bounds that recursively
60 /// require themselves.
61 freshener: TypeFreshener<'cx, 'tcx>,
62
63 /// If `true`, indicates that the evaluation should be conservative
64 /// and consider the possibility of types outside this crate.
65 /// This comes up primarily when resolving ambiguity. Imagine
66 /// there is some trait reference `$0: Bar` where `$0` is an
67 /// inference variable. If `intercrate` is true, then we can never
68 /// say for sure that this reference is not implemented, even if
69 /// there are *no impls at all for `Bar`*, because `$0` could be
70 /// bound to some type that in a downstream crate that implements
71 /// `Bar`. This is the suitable mode for coherence. Elsewhere,
72 /// though, we set this to false, because we are only interested
73 /// in types that the user could actually have written --- in
74 /// other words, we consider `$0: Bar` to be unimplemented if
75 /// there is no type that the user could *actually name* that
76 /// would satisfy it. This avoids crippling inference, basically.
77 intercrate: Option<IntercrateMode>,
78
79 intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
80
81 /// Controls whether or not to filter out negative impls when selecting.
82 /// This is used in librustdoc to distinguish between the lack of an impl
83 /// and a negative impl
84 allow_negative_impls: bool,
85
86 /// The mode that trait queries run in, which informs our error handling
87 /// policy. In essence, canonicalized queries need their errors propagated
88 /// rather than immediately reported because we do not have accurate spans.
89 query_mode: TraitQueryMode,
90 }
91
92 #[derive(Clone, Debug)]
93 pub enum IntercrateAmbiguityCause {
94 DownstreamCrate {
95 trait_desc: String,
96 self_desc: Option<String>,
97 },
98 UpstreamCrateUpdate {
99 trait_desc: String,
100 self_desc: Option<String>,
101 },
102 }
103
104 impl IntercrateAmbiguityCause {
105 /// Emits notes when the overlap is caused by complex intercrate ambiguities.
106 /// See #23980 for details.
107 pub fn add_intercrate_ambiguity_hint(&self, err: &mut errors::DiagnosticBuilder<'_>) {
108 err.note(&self.intercrate_ambiguity_hint());
109 }
110
111 pub fn intercrate_ambiguity_hint(&self) -> String {
112 match self {
113 &IntercrateAmbiguityCause::DownstreamCrate {
114 ref trait_desc,
115 ref self_desc,
116 } => {
117 let self_desc = if let &Some(ref ty) = self_desc {
118 format!(" for type `{}`", ty)
119 } else {
120 String::new()
121 };
122 format!(
123 "downstream crates may implement trait `{}`{}",
124 trait_desc, self_desc
125 )
126 }
127 &IntercrateAmbiguityCause::UpstreamCrateUpdate {
128 ref trait_desc,
129 ref self_desc,
130 } => {
131 let self_desc = if let &Some(ref ty) = self_desc {
132 format!(" for type `{}`", ty)
133 } else {
134 String::new()
135 };
136 format!(
137 "upstream crates may add new impl of trait `{}`{} \
138 in future versions",
139 trait_desc, self_desc
140 )
141 }
142 }
143 }
144 }
145
146 // A stack that walks back up the stack frame.
147 struct TraitObligationStack<'prev, 'tcx> {
148 obligation: &'prev TraitObligation<'tcx>,
149
150 /// Trait ref from `obligation` but "freshened" with the
151 /// selection-context's freshener. Used to check for recursion.
152 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
153
154 /// Starts out equal to `depth` -- if, during evaluation, we
155 /// encounter a cycle, then we will set this flag to the minimum
156 /// depth of that cycle for all participants in the cycle. These
157 /// participants will then forego caching their results. This is
158 /// not the most efficient solution, but it addresses #60010. The
159 /// problem we are trying to prevent:
160 ///
161 /// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
162 /// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
163 /// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
164 ///
165 /// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
166 /// is `EvaluatedToOk`; this is because they were only considered
167 /// ok on the premise that if `A: AutoTrait` held, but we indeed
168 /// encountered a problem (later on) with `A: AutoTrait. So we
169 /// currently set a flag on the stack node for `B: AutoTrait` (as
170 /// well as the second instance of `A: AutoTrait`) to supress
171 /// caching.
172 ///
173 /// This is a simple, targeted fix. A more-performant fix requires
174 /// deeper changes, but would permit more caching: we could
175 /// basically defer caching until we have fully evaluated the
176 /// tree, and then cache the entire tree at once. In any case, the
177 /// performance impact here shouldn't be so horrible: every time
178 /// this is hit, we do cache at least one trait, so we only
179 /// evaluate each member of a cycle up to N times, where N is the
180 /// length of the cycle. This means the performance impact is
181 /// bounded and we shouldn't have any terrible worst-cases.
182 reached_depth: Cell<usize>,
183
184 previous: TraitObligationStackList<'prev, 'tcx>,
185
186 /// Number of parent frames plus one -- so the topmost frame has depth 1.
187 depth: usize,
188
189 /// Depth-first number of this node in the search graph -- a
190 /// pre-order index. Basically a freshly incremented counter.
191 dfn: usize,
192 }
193
194 #[derive(Clone, Default)]
195 pub struct SelectionCache<'tcx> {
196 hashmap: Lock<
197 FxHashMap<ty::TraitRef<'tcx>, WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
198 >,
199 }
200
201 /// The selection process begins by considering all impls, where
202 /// clauses, and so forth that might resolve an obligation. Sometimes
203 /// we'll be able to say definitively that (e.g.) an impl does not
204 /// apply to the obligation: perhaps it is defined for `usize` but the
205 /// obligation is for `int`. In that case, we drop the impl out of the
206 /// list. But the other cases are considered *candidates*.
207 ///
208 /// For selection to succeed, there must be exactly one matching
209 /// candidate. If the obligation is fully known, this is guaranteed
210 /// by coherence. However, if the obligation contains type parameters
211 /// or variables, there may be multiple such impls.
212 ///
213 /// It is not a real problem if multiple matching impls exist because
214 /// of type variables - it just means the obligation isn't sufficiently
215 /// elaborated. In that case we report an ambiguity, and the caller can
216 /// try again after more type information has been gathered or report a
217 /// "type annotations required" error.
218 ///
219 /// However, with type parameters, this can be a real problem - type
220 /// parameters don't unify with regular types, but they *can* unify
221 /// with variables from blanket impls, and (unless we know its bounds
222 /// will always be satisfied) picking the blanket impl will be wrong
223 /// for at least *some* substitutions. To make this concrete, if we have
224 ///
225 /// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
226 /// impl<T: fmt::Debug> AsDebug for T {
227 /// type Out = T;
228 /// fn debug(self) -> fmt::Debug { self }
229 /// }
230 /// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
231 ///
232 /// we can't just use the impl to resolve the <T as AsDebug> obligation
233 /// - a type from another crate (that doesn't implement fmt::Debug) could
234 /// implement AsDebug.
235 ///
236 /// Because where-clauses match the type exactly, multiple clauses can
237 /// only match if there are unresolved variables, and we can mostly just
238 /// report this ambiguity in that case. This is still a problem - we can't
239 /// *do anything* with ambiguities that involve only regions. This is issue
240 /// #21974.
241 ///
242 /// If a single where-clause matches and there are no inference
243 /// variables left, then it definitely matches and we can just select
244 /// it.
245 ///
246 /// In fact, we even select the where-clause when the obligation contains
247 /// inference variables. The can lead to inference making "leaps of logic",
248 /// for example in this situation:
249 ///
250 /// pub trait Foo<T> { fn foo(&self) -> T; }
251 /// impl<T> Foo<()> for T { fn foo(&self) { } }
252 /// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
253 ///
254 /// pub fn foo<T>(t: T) where T: Foo<bool> {
255 /// println!("{:?}", <T as Foo<_>>::foo(&t));
256 /// }
257 /// fn main() { foo(false); }
258 ///
259 /// Here the obligation <T as Foo<$0>> can be matched by both the blanket
260 /// impl and the where-clause. We select the where-clause and unify $0=bool,
261 /// so the program prints "false". However, if the where-clause is omitted,
262 /// the blanket impl is selected, we unify $0=(), and the program prints
263 /// "()".
264 ///
265 /// Exactly the same issues apply to projection and object candidates, except
266 /// that we can have both a projection candidate and a where-clause candidate
267 /// for the same obligation. In that case either would do (except that
268 /// different "leaps of logic" would occur if inference variables are
269 /// present), and we just pick the where-clause. This is, for example,
270 /// required for associated types to work in default impls, as the bounds
271 /// are visible both as projection bounds and as where-clauses from the
272 /// parameter environment.
273 #[derive(PartialEq, Eq, Debug, Clone)]
274 enum SelectionCandidate<'tcx> {
275 /// If has_nested is false, there are no *further* obligations
276 BuiltinCandidate {
277 has_nested: bool,
278 },
279 ParamCandidate(ty::PolyTraitRef<'tcx>),
280 ImplCandidate(DefId),
281 AutoImplCandidate(DefId),
282
283 /// This is a trait matching with a projected type as `Self`, and
284 /// we found an applicable bound in the trait definition.
285 ProjectionCandidate,
286
287 /// Implementation of a `Fn`-family trait by one of the anonymous types
288 /// generated for a `||` expression.
289 ClosureCandidate,
290
291 /// Implementation of a `Generator` trait by one of the anonymous types
292 /// generated for a generator.
293 GeneratorCandidate,
294
295 /// Implementation of a `Fn`-family trait by one of the anonymous
296 /// types generated for a fn pointer type (e.g., `fn(int)->int`)
297 FnPointerCandidate,
298
299 TraitAliasCandidate(DefId),
300
301 ObjectCandidate,
302
303 BuiltinObjectCandidate,
304
305 BuiltinUnsizeCandidate,
306 }
307
308 impl<'a, 'tcx> ty::Lift<'tcx> for SelectionCandidate<'a> {
309 type Lifted = SelectionCandidate<'tcx>;
310 fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
311 Some(match *self {
312 BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
313 ImplCandidate(def_id) => ImplCandidate(def_id),
314 AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
315 ProjectionCandidate => ProjectionCandidate,
316 ClosureCandidate => ClosureCandidate,
317 GeneratorCandidate => GeneratorCandidate,
318 FnPointerCandidate => FnPointerCandidate,
319 TraitAliasCandidate(def_id) => TraitAliasCandidate(def_id),
320 ObjectCandidate => ObjectCandidate,
321 BuiltinObjectCandidate => BuiltinObjectCandidate,
322 BuiltinUnsizeCandidate => BuiltinUnsizeCandidate,
323
324 ParamCandidate(ref trait_ref) => {
325 return tcx.lift(trait_ref).map(ParamCandidate);
326 }
327 })
328 }
329 }
330
331 EnumTypeFoldableImpl! {
332 impl<'tcx> TypeFoldable<'tcx> for SelectionCandidate<'tcx> {
333 (SelectionCandidate::BuiltinCandidate) { has_nested },
334 (SelectionCandidate::ParamCandidate)(poly_trait_ref),
335 (SelectionCandidate::ImplCandidate)(def_id),
336 (SelectionCandidate::AutoImplCandidate)(def_id),
337 (SelectionCandidate::ProjectionCandidate),
338 (SelectionCandidate::ClosureCandidate),
339 (SelectionCandidate::GeneratorCandidate),
340 (SelectionCandidate::FnPointerCandidate),
341 (SelectionCandidate::TraitAliasCandidate)(def_id),
342 (SelectionCandidate::ObjectCandidate),
343 (SelectionCandidate::BuiltinObjectCandidate),
344 (SelectionCandidate::BuiltinUnsizeCandidate),
345 }
346 }
347
348 struct SelectionCandidateSet<'tcx> {
349 // a list of candidates that definitely apply to the current
350 // obligation (meaning: types unify).
351 vec: Vec<SelectionCandidate<'tcx>>,
352
353 // if this is true, then there were candidates that might or might
354 // not have applied, but we couldn't tell. This occurs when some
355 // of the input types are type variables, in which case there are
356 // various "builtin" rules that might or might not trigger.
357 ambiguous: bool,
358 }
359
360 #[derive(PartialEq, Eq, Debug, Clone)]
361 struct EvaluatedCandidate<'tcx> {
362 candidate: SelectionCandidate<'tcx>,
363 evaluation: EvaluationResult,
364 }
365
366 /// When does the builtin impl for `T: Trait` apply?
367 enum BuiltinImplConditions<'tcx> {
368 /// The impl is conditional on T1,T2,.. : Trait
369 Where(ty::Binder<Vec<Ty<'tcx>>>),
370 /// There is no built-in impl. There may be some other
371 /// candidate (a where-clause or user-defined impl).
372 None,
373 /// It is unknown whether there is an impl.
374 Ambiguous,
375 }
376
377 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
378 /// The result of trait evaluation. The order is important
379 /// here as the evaluation of a list is the maximum of the
380 /// evaluations.
381 ///
382 /// The evaluation results are ordered:
383 /// - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
384 /// implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
385 /// - `EvaluatedToErr` implies `EvaluatedToRecur`
386 /// - the "union" of evaluation results is equal to their maximum -
387 /// all the "potential success" candidates can potentially succeed,
388 /// so they are noops when unioned with a definite error, and within
389 /// the categories it's easy to see that the unions are correct.
390 pub enum EvaluationResult {
391 /// Evaluation successful
392 EvaluatedToOk,
393 /// Evaluation successful, but there were unevaluated region obligations
394 EvaluatedToOkModuloRegions,
395 /// Evaluation is known to be ambiguous - it *might* hold for some
396 /// assignment of inference variables, but it might not.
397 ///
398 /// While this has the same meaning as `EvaluatedToUnknown` - we can't
399 /// know whether this obligation holds or not - it is the result we
400 /// would get with an empty stack, and therefore is cacheable.
401 EvaluatedToAmbig,
402 /// Evaluation failed because of recursion involving inference
403 /// variables. We are somewhat imprecise there, so we don't actually
404 /// know the real result.
405 ///
406 /// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
407 EvaluatedToUnknown,
408 /// Evaluation failed because we encountered an obligation we are already
409 /// trying to prove on this branch.
410 ///
411 /// We know this branch can't be a part of a minimal proof-tree for
412 /// the "root" of our cycle, because then we could cut out the recursion
413 /// and maintain a valid proof tree. However, this does not mean
414 /// that all the obligations on this branch do not hold - it's possible
415 /// that we entered this branch "speculatively", and that there
416 /// might be some other way to prove this obligation that does not
417 /// go through this cycle - so we can't cache this as a failure.
418 ///
419 /// For example, suppose we have this:
420 ///
421 /// ```rust,ignore (pseudo-Rust)
422 /// pub trait Trait { fn xyz(); }
423 /// // This impl is "useless", but we can still have
424 /// // an `impl Trait for SomeUnsizedType` somewhere.
425 /// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
426 ///
427 /// pub fn foo<T: Trait + ?Sized>() {
428 /// <T as Trait>::xyz();
429 /// }
430 /// ```
431 ///
432 /// When checking `foo`, we have to prove `T: Trait`. This basically
433 /// translates into this:
434 ///
435 /// ```plain,ignore
436 /// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
437 /// ```
438 ///
439 /// When we try to prove it, we first go the first option, which
440 /// recurses. This shows us that the impl is "useless" -- it won't
441 /// tell us that `T: Trait` unless it already implemented `Trait`
442 /// by some other means. However, that does not prevent `T: Trait`
443 /// does not hold, because of the bound (which can indeed be satisfied
444 /// by `SomeUnsizedType` from another crate).
445 //
446 // FIXME: when an `EvaluatedToRecur` goes past its parent root, we
447 // ought to convert it to an `EvaluatedToErr`, because we know
448 // there definitely isn't a proof tree for that obligation. Not
449 // doing so is still sound -- there isn't any proof tree, so the
450 // branch still can't be a part of a minimal one -- but does not re-enable caching.
451 EvaluatedToRecur,
452 /// Evaluation failed.
453 EvaluatedToErr,
454 }
455
456 impl EvaluationResult {
457 /// Returns `true` if this evaluation result is known to apply, even
458 /// considering outlives constraints.
459 pub fn must_apply_considering_regions(self) -> bool {
460 self == EvaluatedToOk
461 }
462
463 /// Returns `true` if this evaluation result is known to apply, ignoring
464 /// outlives constraints.
465 pub fn must_apply_modulo_regions(self) -> bool {
466 self <= EvaluatedToOkModuloRegions
467 }
468
469 pub fn may_apply(self) -> bool {
470 match self {
471 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToUnknown => {
472 true
473 }
474
475 EvaluatedToErr | EvaluatedToRecur => false,
476 }
477 }
478
479 fn is_stack_dependent(self) -> bool {
480 match self {
481 EvaluatedToUnknown | EvaluatedToRecur => true,
482
483 EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToErr => false,
484 }
485 }
486 }
487
488 impl_stable_hash_for!(enum self::EvaluationResult {
489 EvaluatedToOk,
490 EvaluatedToOkModuloRegions,
491 EvaluatedToAmbig,
492 EvaluatedToUnknown,
493 EvaluatedToRecur,
494 EvaluatedToErr
495 });
496
497 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
498 /// Indicates that trait evaluation caused overflow.
499 pub struct OverflowError;
500
501 impl_stable_hash_for!(struct OverflowError {});
502
503 impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
504 fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
505 SelectionError::Overflow
506 }
507 }
508
509 #[derive(Clone, Default)]
510 pub struct EvaluationCache<'tcx> {
511 hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>,
512 }
513
514 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
515 pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
516 SelectionContext {
517 infcx,
518 freshener: infcx.freshener(),
519 intercrate: None,
520 intercrate_ambiguity_causes: None,
521 allow_negative_impls: false,
522 query_mode: TraitQueryMode::Standard,
523 }
524 }
525
526 pub fn intercrate(
527 infcx: &'cx InferCtxt<'cx, 'tcx>,
528 mode: IntercrateMode,
529 ) -> SelectionContext<'cx, 'tcx> {
530 debug!("intercrate({:?})", mode);
531 SelectionContext {
532 infcx,
533 freshener: infcx.freshener(),
534 intercrate: Some(mode),
535 intercrate_ambiguity_causes: None,
536 allow_negative_impls: false,
537 query_mode: TraitQueryMode::Standard,
538 }
539 }
540
541 pub fn with_negative(
542 infcx: &'cx InferCtxt<'cx, 'tcx>,
543 allow_negative_impls: bool,
544 ) -> SelectionContext<'cx, 'tcx> {
545 debug!("with_negative({:?})", allow_negative_impls);
546 SelectionContext {
547 infcx,
548 freshener: infcx.freshener(),
549 intercrate: None,
550 intercrate_ambiguity_causes: None,
551 allow_negative_impls,
552 query_mode: TraitQueryMode::Standard,
553 }
554 }
555
556 pub fn with_query_mode(
557 infcx: &'cx InferCtxt<'cx, 'tcx>,
558 query_mode: TraitQueryMode,
559 ) -> SelectionContext<'cx, 'tcx> {
560 debug!("with_query_mode({:?})", query_mode);
561 SelectionContext {
562 infcx,
563 freshener: infcx.freshener(),
564 intercrate: None,
565 intercrate_ambiguity_causes: None,
566 allow_negative_impls: false,
567 query_mode,
568 }
569 }
570
571 /// Enables tracking of intercrate ambiguity causes. These are
572 /// used in coherence to give improved diagnostics. We don't do
573 /// this until we detect a coherence error because it can lead to
574 /// false overflow results (#47139) and because it costs
575 /// computation time.
576 pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
577 assert!(self.intercrate.is_some());
578 assert!(self.intercrate_ambiguity_causes.is_none());
579 self.intercrate_ambiguity_causes = Some(vec![]);
580 debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
581 }
582
583 /// Gets the intercrate ambiguity causes collected since tracking
584 /// was enabled and disables tracking at the same time. If
585 /// tracking is not enabled, just returns an empty vector.
586 pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
587 assert!(self.intercrate.is_some());
588 self.intercrate_ambiguity_causes.take().unwrap_or(vec![])
589 }
590
591 pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
592 self.infcx
593 }
594
595 pub fn tcx(&self) -> TyCtxt<'tcx> {
596 self.infcx.tcx
597 }
598
599 pub fn closure_typer(&self) -> &'cx InferCtxt<'cx, 'tcx> {
600 self.infcx
601 }
602
603 ///////////////////////////////////////////////////////////////////////////
604 // Selection
605 //
606 // The selection phase tries to identify *how* an obligation will
607 // be resolved. For example, it will identify which impl or
608 // parameter bound is to be used. The process can be inconclusive
609 // if the self type in the obligation is not fully inferred. Selection
610 // can result in an error in one of two ways:
611 //
612 // 1. If no applicable impl or parameter bound can be found.
613 // 2. If the output type parameters in the obligation do not match
614 // those specified by the impl/bound. For example, if the obligation
615 // is `Vec<Foo>:Iterable<Bar>`, but the impl specifies
616 // `impl<T> Iterable<T> for Vec<T>`, than an error would result.
617
618 /// Attempts to satisfy the obligation. If successful, this will affect the surrounding
619 /// type environment by performing unification.
620 pub fn select(
621 &mut self,
622 obligation: &TraitObligation<'tcx>,
623 ) -> SelectionResult<'tcx, Selection<'tcx>> {
624 debug!("select({:?})", obligation);
625 debug_assert!(!obligation.predicate.has_escaping_bound_vars());
626
627 let pec = &ProvisionalEvaluationCache::default();
628 let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
629
630 let candidate = match self.candidate_from_obligation(&stack) {
631 Err(SelectionError::Overflow) => {
632 // In standard mode, overflow must have been caught and reported
633 // earlier.
634 assert!(self.query_mode == TraitQueryMode::Canonical);
635 return Err(SelectionError::Overflow);
636 }
637 Err(e) => {
638 return Err(e);
639 }
640 Ok(None) => {
641 return Ok(None);
642 }
643 Ok(Some(candidate)) => candidate,
644 };
645
646 match self.confirm_candidate(obligation, candidate) {
647 Err(SelectionError::Overflow) => {
648 assert!(self.query_mode == TraitQueryMode::Canonical);
649 Err(SelectionError::Overflow)
650 }
651 Err(e) => Err(e),
652 Ok(candidate) => Ok(Some(candidate)),
653 }
654 }
655
656 ///////////////////////////////////////////////////////////////////////////
657 // EVALUATION
658 //
659 // Tests whether an obligation can be selected or whether an impl
660 // can be applied to particular types. It skips the "confirmation"
661 // step and hence completely ignores output type parameters.
662 //
663 // The result is "true" if the obligation *may* hold and "false" if
664 // we can be sure it does not.
665
666 /// Evaluates whether the obligation `obligation` can be satisfied (by any means).
667 pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
668 debug!("predicate_may_hold_fatal({:?})", obligation);
669
670 // This fatal query is a stopgap that should only be used in standard mode,
671 // where we do not expect overflow to be propagated.
672 assert!(self.query_mode == TraitQueryMode::Standard);
673
674 self.evaluate_root_obligation(obligation)
675 .expect("Overflow should be caught earlier in standard query mode")
676 .may_apply()
677 }
678
679 /// Evaluates whether the obligation `obligation` can be satisfied
680 /// and returns an `EvaluationResult`. This is meant for the
681 /// *initial* call.
682 pub fn evaluate_root_obligation(
683 &mut self,
684 obligation: &PredicateObligation<'tcx>,
685 ) -> Result<EvaluationResult, OverflowError> {
686 self.evaluation_probe(|this| {
687 this.evaluate_predicate_recursively(
688 TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
689 obligation.clone(),
690 )
691 })
692 }
693
694 fn evaluation_probe(
695 &mut self,
696 op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
697 ) -> Result<EvaluationResult, OverflowError> {
698 self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
699 let result = op(self)?;
700 match self.infcx.region_constraints_added_in_snapshot(snapshot) {
701 None => Ok(result),
702 Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
703 }
704 })
705 }
706
707 /// Evaluates the predicates in `predicates` recursively. Note that
708 /// this applies projections in the predicates, and therefore
709 /// is run within an inference probe.
710 fn evaluate_predicates_recursively<'o, I>(
711 &mut self,
712 stack: TraitObligationStackList<'o, 'tcx>,
713 predicates: I,
714 ) -> Result<EvaluationResult, OverflowError>
715 where
716 I: IntoIterator<Item = PredicateObligation<'tcx>>,
717 {
718 let mut result = EvaluatedToOk;
719 for obligation in predicates {
720 let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
721 debug!(
722 "evaluate_predicate_recursively({:?}) = {:?}",
723 obligation, eval
724 );
725 if let EvaluatedToErr = eval {
726 // fast-path - EvaluatedToErr is the top of the lattice,
727 // so we don't need to look on the other predicates.
728 return Ok(EvaluatedToErr);
729 } else {
730 result = cmp::max(result, eval);
731 }
732 }
733 Ok(result)
734 }
735
736 fn evaluate_predicate_recursively<'o>(
737 &mut self,
738 previous_stack: TraitObligationStackList<'o, 'tcx>,
739 obligation: PredicateObligation<'tcx>,
740 ) -> Result<EvaluationResult, OverflowError> {
741 debug!("evaluate_predicate_recursively(previous_stack={:?}, obligation={:?})",
742 previous_stack.head(), obligation);
743
744 // Previous_stack stores a TraitObligatiom, while 'obligation' is
745 // a PredicateObligation. These are distinct types, so we can't
746 // use any Option combinator method that would force them to be
747 // the same
748 match previous_stack.head() {
749 Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
750 None => self.check_recursion_limit(&obligation, &obligation)?
751 }
752
753 match obligation.predicate {
754 ty::Predicate::Trait(ref t) => {
755 debug_assert!(!t.has_escaping_bound_vars());
756 let obligation = obligation.with(t.clone());
757 self.evaluate_trait_predicate_recursively(previous_stack, obligation)
758 }
759
760 ty::Predicate::Subtype(ref p) => {
761 // does this code ever run?
762 match self.infcx
763 .subtype_predicate(&obligation.cause, obligation.param_env, p)
764 {
765 Some(Ok(InferOk { mut obligations, .. })) => {
766 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
767 self.evaluate_predicates_recursively(previous_stack,obligations.into_iter())
768 }
769 Some(Err(_)) => Ok(EvaluatedToErr),
770 None => Ok(EvaluatedToAmbig),
771 }
772 }
773
774 ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
775 self.infcx,
776 obligation.param_env,
777 obligation.cause.body_id,
778 ty,
779 obligation.cause.span,
780 ) {
781 Some(mut obligations) => {
782 self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
783 self.evaluate_predicates_recursively(previous_stack, obligations.into_iter())
784 }
785 None => Ok(EvaluatedToAmbig),
786 },
787
788 ty::Predicate::TypeOutlives(..) | ty::Predicate::RegionOutlives(..) => {
789 // we do not consider region relationships when
790 // evaluating trait matches
791 Ok(EvaluatedToOkModuloRegions)
792 }
793
794 ty::Predicate::ObjectSafe(trait_def_id) => {
795 if self.tcx().is_object_safe(trait_def_id) {
796 Ok(EvaluatedToOk)
797 } else {
798 Ok(EvaluatedToErr)
799 }
800 }
801
802 ty::Predicate::Projection(ref data) => {
803 let project_obligation = obligation.with(data.clone());
804 match project::poly_project_and_unify_type(self, &project_obligation) {
805 Ok(Some(mut subobligations)) => {
806 self.add_depth(subobligations.iter_mut(), obligation.recursion_depth);
807 let result = self.evaluate_predicates_recursively(
808 previous_stack,
809 subobligations.into_iter(),
810 );
811 if let Some(key) =
812 ProjectionCacheKey::from_poly_projection_predicate(self, data)
813 {
814 self.infcx.projection_cache.borrow_mut().complete(key);
815 }
816 result
817 }
818 Ok(None) => Ok(EvaluatedToAmbig),
819 Err(_) => Ok(EvaluatedToErr),
820 }
821 }
822
823 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
824 match self.infcx.closure_kind(closure_def_id, closure_substs) {
825 Some(closure_kind) => {
826 if closure_kind.extends(kind) {
827 Ok(EvaluatedToOk)
828 } else {
829 Ok(EvaluatedToErr)
830 }
831 }
832 None => Ok(EvaluatedToAmbig),
833 }
834 }
835
836 ty::Predicate::ConstEvaluatable(def_id, substs) => {
837 let tcx = self.tcx();
838 if !(obligation.param_env, substs).has_local_value() {
839 let param_env = obligation.param_env;
840 let instance =
841 ty::Instance::resolve(tcx, param_env, def_id, substs);
842 if let Some(instance) = instance {
843 let cid = GlobalId {
844 instance,
845 promoted: None,
846 };
847 match self.tcx().const_eval(param_env.and(cid)) {
848 Ok(_) => Ok(EvaluatedToOk),
849 Err(_) => Ok(EvaluatedToErr),
850 }
851 } else {
852 Ok(EvaluatedToErr)
853 }
854 } else {
855 // Inference variables still left in param_env or substs.
856 Ok(EvaluatedToAmbig)
857 }
858 }
859 }
860 }
861
862 fn evaluate_trait_predicate_recursively<'o>(
863 &mut self,
864 previous_stack: TraitObligationStackList<'o, 'tcx>,
865 mut obligation: TraitObligation<'tcx>,
866 ) -> Result<EvaluationResult, OverflowError> {
867 debug!("evaluate_trait_predicate_recursively({:?})", obligation);
868
869 if self.intercrate.is_none() && obligation.is_global()
870 && obligation
871 .param_env
872 .caller_bounds
873 .iter()
874 .all(|bound| bound.needs_subst())
875 {
876 // If a param env has no global bounds, global obligations do not
877 // depend on its particular value in order to work, so we can clear
878 // out the param env and get better caching.
879 debug!(
880 "evaluate_trait_predicate_recursively({:?}) - in global",
881 obligation
882 );
883 obligation.param_env = obligation.param_env.without_caller_bounds();
884 }
885
886 let stack = self.push_stack(previous_stack, &obligation);
887 let fresh_trait_ref = stack.fresh_trait_ref;
888 if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
889 debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
890 return Ok(result);
891 }
892
893 if let Some(result) = stack.cache().get_provisional(fresh_trait_ref) {
894 debug!("PROVISIONAL CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
895 stack.update_reached_depth(stack.cache().current_reached_depth());
896 return Ok(result);
897 }
898
899 // Check if this is a match for something already on the
900 // stack. If so, we don't want to insert the result into the
901 // main cache (it is cycle dependent) nor the provisional
902 // cache (which is meant for things that have completed but
903 // for a "backedge" -- this result *is* the backedge).
904 if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
905 return Ok(cycle_result);
906 }
907
908 let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
909 let result = result?;
910
911 if !result.must_apply_modulo_regions() {
912 stack.cache().on_failure(stack.dfn);
913 }
914
915 let reached_depth = stack.reached_depth.get();
916 if reached_depth >= stack.depth {
917 debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
918 self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
919
920 stack.cache().on_completion(stack.depth, |fresh_trait_ref, provisional_result| {
921 self.insert_evaluation_cache(
922 obligation.param_env,
923 fresh_trait_ref,
924 dep_node,
925 provisional_result.max(result),
926 );
927 });
928 } else {
929 debug!("PROVISIONAL: {:?}={:?}", fresh_trait_ref, result);
930 debug!(
931 "evaluate_trait_predicate_recursively: caching provisionally because {:?} \
932 is a cycle participant (at depth {}, reached depth {})",
933 fresh_trait_ref,
934 stack.depth,
935 reached_depth,
936 );
937
938 stack.cache().insert_provisional(
939 stack.dfn,
940 reached_depth,
941 fresh_trait_ref,
942 result,
943 );
944 }
945
946
947 Ok(result)
948 }
949
950 /// If there is any previous entry on the stack that precisely
951 /// matches this obligation, then we can assume that the
952 /// obligation is satisfied for now (still all other conditions
953 /// must be met of course). One obvious case this comes up is
954 /// marker traits like `Send`. Think of a linked list:
955 ///
956 /// struct List<T> { data: T, next: Option<Box<List<T>>> }
957 ///
958 /// `Box<List<T>>` will be `Send` if `T` is `Send` and
959 /// `Option<Box<List<T>>>` is `Send`, and in turn
960 /// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
961 /// `Send`.
962 ///
963 /// Note that we do this comparison using the `fresh_trait_ref`
964 /// fields. Because these have all been freshened using
965 /// `self.freshener`, we can be sure that (a) this will not
966 /// affect the inferencer state and (b) that if we see two
967 /// fresh regions with the same index, they refer to the same
968 /// unbound type variable.
969 fn check_evaluation_cycle(
970 &mut self,
971 stack: &TraitObligationStack<'_, 'tcx>,
972 ) -> Option<EvaluationResult> {
973 if let Some(cycle_depth) = stack.iter()
974 .skip(1) // skip top-most frame
975 .find(|prev| stack.obligation.param_env == prev.obligation.param_env &&
976 stack.fresh_trait_ref == prev.fresh_trait_ref)
977 .map(|stack| stack.depth)
978 {
979 debug!(
980 "evaluate_stack({:?}) --> recursive at depth {}",
981 stack.fresh_trait_ref,
982 cycle_depth,
983 );
984
985 // If we have a stack like `A B C D E A`, where the top of
986 // the stack is the final `A`, then this will iterate over
987 // `A, E, D, C, B` -- i.e., all the participants apart
988 // from the cycle head. We mark them as participating in a
989 // cycle. This suppresses caching for those nodes. See
990 // `in_cycle` field for more details.
991 stack.update_reached_depth(cycle_depth);
992
993 // Subtle: when checking for a coinductive cycle, we do
994 // not compare using the "freshened trait refs" (which
995 // have erased regions) but rather the fully explicit
996 // trait refs. This is important because it's only a cycle
997 // if the regions match exactly.
998 let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
999 let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
1000 if self.coinductive_match(cycle) {
1001 debug!(
1002 "evaluate_stack({:?}) --> recursive, coinductive",
1003 stack.fresh_trait_ref
1004 );
1005 Some(EvaluatedToOk)
1006 } else {
1007 debug!(
1008 "evaluate_stack({:?}) --> recursive, inductive",
1009 stack.fresh_trait_ref
1010 );
1011 Some(EvaluatedToRecur)
1012 }
1013 } else {
1014 None
1015 }
1016 }
1017
1018 fn evaluate_stack<'o>(
1019 &mut self,
1020 stack: &TraitObligationStack<'o, 'tcx>,
1021 ) -> Result<EvaluationResult, OverflowError> {
1022 // In intercrate mode, whenever any of the types are unbound,
1023 // there can always be an impl. Even if there are no impls in
1024 // this crate, perhaps the type would be unified with
1025 // something from another crate that does provide an impl.
1026 //
1027 // In intra mode, we must still be conservative. The reason is
1028 // that we want to avoid cycles. Imagine an impl like:
1029 //
1030 // impl<T:Eq> Eq for Vec<T>
1031 //
1032 // and a trait reference like `$0 : Eq` where `$0` is an
1033 // unbound variable. When we evaluate this trait-reference, we
1034 // will unify `$0` with `Vec<$1>` (for some fresh variable
1035 // `$1`), on the condition that `$1 : Eq`. We will then wind
1036 // up with many candidates (since that are other `Eq` impls
1037 // that apply) and try to winnow things down. This results in
1038 // a recursive evaluation that `$1 : Eq` -- as you can
1039 // imagine, this is just where we started. To avoid that, we
1040 // check for unbound variables and return an ambiguous (hence possible)
1041 // match if we've seen this trait before.
1042 //
1043 // This suffices to allow chains like `FnMut` implemented in
1044 // terms of `Fn` etc, but we could probably make this more
1045 // precise still.
1046 let unbound_input_types = stack
1047 .fresh_trait_ref
1048 .skip_binder()
1049 .input_types()
1050 .any(|ty| ty.is_fresh());
1051 // this check was an imperfect workaround for a bug n the old
1052 // intercrate mode, it should be removed when that goes away.
1053 if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
1054 debug!(
1055 "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
1056 stack.fresh_trait_ref
1057 );
1058 // Heuristics: show the diagnostics when there are no candidates in crate.
1059 if self.intercrate_ambiguity_causes.is_some() {
1060 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1061 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1062 if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
1063 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1064 let self_ty = trait_ref.self_ty();
1065 let cause = IntercrateAmbiguityCause::DownstreamCrate {
1066 trait_desc: trait_ref.to_string(),
1067 self_desc: if self_ty.has_concrete_skeleton() {
1068 Some(self_ty.to_string())
1069 } else {
1070 None
1071 },
1072 };
1073 debug!("evaluate_stack: pushing cause = {:?}", cause);
1074 self.intercrate_ambiguity_causes
1075 .as_mut()
1076 .unwrap()
1077 .push(cause);
1078 }
1079 }
1080 }
1081 return Ok(EvaluatedToAmbig);
1082 }
1083 if unbound_input_types && stack.iter().skip(1).any(|prev| {
1084 stack.obligation.param_env == prev.obligation.param_env
1085 && self.match_fresh_trait_refs(&stack.fresh_trait_ref, &prev.fresh_trait_ref)
1086 }) {
1087 debug!(
1088 "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
1089 stack.fresh_trait_ref
1090 );
1091 return Ok(EvaluatedToUnknown);
1092 }
1093
1094 match self.candidate_from_obligation(stack) {
1095 Ok(Some(c)) => self.evaluate_candidate(stack, &c),
1096 Ok(None) => Ok(EvaluatedToAmbig),
1097 Err(Overflow) => Err(OverflowError),
1098 Err(..) => Ok(EvaluatedToErr),
1099 }
1100 }
1101
1102 /// For defaulted traits, we use a co-inductive strategy to solve, so
1103 /// that recursion is ok. This routine returns true if the top of the
1104 /// stack (`cycle[0]`):
1105 ///
1106 /// - is a defaulted trait,
1107 /// - it also appears in the backtrace at some position `X`,
1108 /// - all the predicates at positions `X..` between `X` an the top are
1109 /// also defaulted traits.
1110 pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
1111 where
1112 I: Iterator<Item = ty::Predicate<'tcx>>,
1113 {
1114 let mut cycle = cycle;
1115 cycle.all(|predicate| self.coinductive_predicate(predicate))
1116 }
1117
1118 fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
1119 let result = match predicate {
1120 ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
1121 _ => false,
1122 };
1123 debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
1124 result
1125 }
1126
1127 /// Further evaluate `candidate` to decide whether all type parameters match and whether nested
1128 /// obligations are met. Returns whether `candidate` remains viable after this further
1129 /// scrutiny.
1130 fn evaluate_candidate<'o>(
1131 &mut self,
1132 stack: &TraitObligationStack<'o, 'tcx>,
1133 candidate: &SelectionCandidate<'tcx>,
1134 ) -> Result<EvaluationResult, OverflowError> {
1135 debug!(
1136 "evaluate_candidate: depth={} candidate={:?}",
1137 stack.obligation.recursion_depth, candidate
1138 );
1139 let result = self.evaluation_probe(|this| {
1140 let candidate = (*candidate).clone();
1141 match this.confirm_candidate(stack.obligation, candidate) {
1142 Ok(selection) => this.evaluate_predicates_recursively(
1143 stack.list(),
1144 selection.nested_obligations().into_iter()
1145 ),
1146 Err(..) => Ok(EvaluatedToErr),
1147 }
1148 })?;
1149 debug!(
1150 "evaluate_candidate: depth={} result={:?}",
1151 stack.obligation.recursion_depth, result
1152 );
1153 Ok(result)
1154 }
1155
1156 fn check_evaluation_cache(
1157 &self,
1158 param_env: ty::ParamEnv<'tcx>,
1159 trait_ref: ty::PolyTraitRef<'tcx>,
1160 ) -> Option<EvaluationResult> {
1161 let tcx = self.tcx();
1162 if self.can_use_global_caches(param_env) {
1163 let cache = tcx.evaluation_cache.hashmap.borrow();
1164 if let Some(cached) = cache.get(&trait_ref) {
1165 return Some(cached.get(tcx));
1166 }
1167 }
1168 self.infcx
1169 .evaluation_cache
1170 .hashmap
1171 .borrow()
1172 .get(&trait_ref)
1173 .map(|v| v.get(tcx))
1174 }
1175
1176 fn insert_evaluation_cache(
1177 &mut self,
1178 param_env: ty::ParamEnv<'tcx>,
1179 trait_ref: ty::PolyTraitRef<'tcx>,
1180 dep_node: DepNodeIndex,
1181 result: EvaluationResult,
1182 ) {
1183 // Avoid caching results that depend on more than just the trait-ref
1184 // - the stack can create recursion.
1185 if result.is_stack_dependent() {
1186 return;
1187 }
1188
1189 if self.can_use_global_caches(param_env) {
1190 if !trait_ref.has_local_value() {
1191 debug!(
1192 "insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
1193 trait_ref, result,
1194 );
1195 // This may overwrite the cache with the same value
1196 // FIXME: Due to #50507 this overwrites the different values
1197 // This should be changed to use HashMapExt::insert_same
1198 // when that is fixed
1199 self.tcx()
1200 .evaluation_cache
1201 .hashmap
1202 .borrow_mut()
1203 .insert(trait_ref, WithDepNode::new(dep_node, result));
1204 return;
1205 }
1206 }
1207
1208 debug!(
1209 "insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
1210 trait_ref, result,
1211 );
1212 self.infcx
1213 .evaluation_cache
1214 .hashmap
1215 .borrow_mut()
1216 .insert(trait_ref, WithDepNode::new(dep_node, result));
1217 }
1218
1219 // For various reasons, it's possible for a subobligation
1220 // to have a *lower* recursion_depth than the obligation used to create it.
1221 // Projection sub-obligations may be returned from the projection cache,
1222 // which results in obligations with an 'old' recursion_depth.
1223 // Additionally, methods like ty::wf::obligations and
1224 // InferCtxt.subtype_predicate produce subobligations without
1225 // taking in a 'parent' depth, causing the generated subobligations
1226 // to have a recursion_depth of 0
1227 //
1228 // To ensure that obligation_depth never decreasees, we force all subobligations
1229 // to have at least the depth of the original obligation.
1230 fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(&self, it: I,
1231 min_depth: usize) {
1232 it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
1233 }
1234
1235 // Check that the recursion limit has not been exceeded.
1236 //
1237 // The weird return type of this function allows it to be used with the 'try' (?)
1238 // operator within certain functions
1239 fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
1240 &self,
1241 obligation: &Obligation<'tcx, T>,
1242 error_obligation: &Obligation<'tcx, V>
1243 ) -> Result<(), OverflowError> {
1244 let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
1245 if obligation.recursion_depth >= recursion_limit {
1246 match self.query_mode {
1247 TraitQueryMode::Standard => {
1248 self.infcx().report_overflow_error(error_obligation, true);
1249 }
1250 TraitQueryMode::Canonical => {
1251 return Err(OverflowError);
1252 }
1253 }
1254 }
1255 Ok(())
1256 }
1257
1258 ///////////////////////////////////////////////////////////////////////////
1259 // CANDIDATE ASSEMBLY
1260 //
1261 // The selection process begins by examining all in-scope impls,
1262 // caller obligations, and so forth and assembling a list of
1263 // candidates. See the [rustc guide] for more details.
1264 //
1265 // [rustc guide]:
1266 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly
1267
1268 fn candidate_from_obligation<'o>(
1269 &mut self,
1270 stack: &TraitObligationStack<'o, 'tcx>,
1271 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1272 // Watch out for overflow. This intentionally bypasses (and does
1273 // not update) the cache.
1274 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
1275
1276
1277 // Check the cache. Note that we freshen the trait-ref
1278 // separately rather than using `stack.fresh_trait_ref` --
1279 // this is because we want the unbound variables to be
1280 // replaced with fresh types starting from index 0.
1281 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
1282 debug!(
1283 "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
1284 cache_fresh_trait_pred, stack
1285 );
1286 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
1287
1288 if let Some(c) =
1289 self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
1290 {
1291 debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
1292 return c;
1293 }
1294
1295 // If no match, compute result and insert into cache.
1296 //
1297 // FIXME(nikomatsakis) -- this cache is not taking into
1298 // account cycles that may have occurred in forming the
1299 // candidate. I don't know of any specific problems that
1300 // result but it seems awfully suspicious.
1301 let (candidate, dep_node) =
1302 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
1303
1304 debug!(
1305 "CACHE MISS: SELECT({:?})={:?}",
1306 cache_fresh_trait_pred, candidate
1307 );
1308 self.insert_candidate_cache(
1309 stack.obligation.param_env,
1310 cache_fresh_trait_pred,
1311 dep_node,
1312 candidate.clone(),
1313 );
1314 candidate
1315 }
1316
1317 fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
1318 where
1319 OP: FnOnce(&mut Self) -> R,
1320 {
1321 let (result, dep_node) = self.tcx()
1322 .dep_graph
1323 .with_anon_task(DepKind::TraitSelect, || op(self));
1324 self.tcx().dep_graph.read_index(dep_node);
1325 (result, dep_node)
1326 }
1327
1328 // Treat negative impls as unimplemented
1329 fn filter_negative_impls(
1330 &self,
1331 candidate: SelectionCandidate<'tcx>,
1332 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1333 if let ImplCandidate(def_id) = candidate {
1334 if !self.allow_negative_impls
1335 && self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative
1336 {
1337 return Err(Unimplemented);
1338 }
1339 }
1340 Ok(Some(candidate))
1341 }
1342
1343 fn candidate_from_obligation_no_cache<'o>(
1344 &mut self,
1345 stack: &TraitObligationStack<'o, 'tcx>,
1346 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
1347 if stack.obligation.predicate.references_error() {
1348 // If we encounter a `Error`, we generally prefer the
1349 // most "optimistic" result in response -- that is, the
1350 // one least likely to report downstream errors. But
1351 // because this routine is shared by coherence and by
1352 // trait selection, there isn't an obvious "right" choice
1353 // here in that respect, so we opt to just return
1354 // ambiguity and let the upstream clients sort it out.
1355 return Ok(None);
1356 }
1357
1358 if let Some(conflict) = self.is_knowable(stack) {
1359 debug!("coherence stage: not knowable");
1360 if self.intercrate_ambiguity_causes.is_some() {
1361 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
1362 // Heuristics: show the diagnostics when there are no candidates in crate.
1363 if let Ok(candidate_set) = self.assemble_candidates(stack) {
1364 let mut no_candidates_apply = true;
1365 {
1366 let evaluated_candidates = candidate_set
1367 .vec
1368 .iter()
1369 .map(|c| self.evaluate_candidate(stack, &c));
1370
1371 for ec in evaluated_candidates {
1372 match ec {
1373 Ok(c) => {
1374 if c.may_apply() {
1375 no_candidates_apply = false;
1376 break;
1377 }
1378 }
1379 Err(e) => return Err(e.into()),
1380 }
1381 }
1382 }
1383
1384 if !candidate_set.ambiguous && no_candidates_apply {
1385 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
1386 let self_ty = trait_ref.self_ty();
1387 let trait_desc = trait_ref.to_string();
1388 let self_desc = if self_ty.has_concrete_skeleton() {
1389 Some(self_ty.to_string())
1390 } else {
1391 None
1392 };
1393 let cause = if let Conflict::Upstream = conflict {
1394 IntercrateAmbiguityCause::UpstreamCrateUpdate {
1395 trait_desc,
1396 self_desc,
1397 }
1398 } else {
1399 IntercrateAmbiguityCause::DownstreamCrate {
1400 trait_desc,
1401 self_desc,
1402 }
1403 };
1404 debug!("evaluate_stack: pushing cause = {:?}", cause);
1405 self.intercrate_ambiguity_causes
1406 .as_mut()
1407 .unwrap()
1408 .push(cause);
1409 }
1410 }
1411 }
1412 return Ok(None);
1413 }
1414
1415 let candidate_set = self.assemble_candidates(stack)?;
1416
1417 if candidate_set.ambiguous {
1418 debug!("candidate set contains ambig");
1419 return Ok(None);
1420 }
1421
1422 let mut candidates = candidate_set.vec;
1423
1424 debug!(
1425 "assembled {} candidates for {:?}: {:?}",
1426 candidates.len(),
1427 stack,
1428 candidates
1429 );
1430
1431 // At this point, we know that each of the entries in the
1432 // candidate set is *individually* applicable. Now we have to
1433 // figure out if they contain mutual incompatibilities. This
1434 // frequently arises if we have an unconstrained input type --
1435 // for example, we are looking for $0:Eq where $0 is some
1436 // unconstrained type variable. In that case, we'll get a
1437 // candidate which assumes $0 == int, one that assumes $0 ==
1438 // usize, etc. This spells an ambiguity.
1439
1440 // If there is more than one candidate, first winnow them down
1441 // by considering extra conditions (nested obligations and so
1442 // forth). We don't winnow if there is exactly one
1443 // candidate. This is a relatively minor distinction but it
1444 // can lead to better inference and error-reporting. An
1445 // example would be if there was an impl:
1446 //
1447 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
1448 //
1449 // and we were to see some code `foo.push_clone()` where `boo`
1450 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
1451 // we were to winnow, we'd wind up with zero candidates.
1452 // Instead, we select the right impl now but report `Bar does
1453 // not implement Clone`.
1454 if candidates.len() == 1 {
1455 return self.filter_negative_impls(candidates.pop().unwrap());
1456 }
1457
1458 // Winnow, but record the exact outcome of evaluation, which
1459 // is needed for specialization. Propagate overflow if it occurs.
1460 let mut candidates = candidates
1461 .into_iter()
1462 .map(|c| match self.evaluate_candidate(stack, &c) {
1463 Ok(eval) if eval.may_apply() => Ok(Some(EvaluatedCandidate {
1464 candidate: c,
1465 evaluation: eval,
1466 })),
1467 Ok(_) => Ok(None),
1468 Err(OverflowError) => Err(Overflow),
1469 })
1470 .flat_map(Result::transpose)
1471 .collect::<Result<Vec<_>, _>>()?;
1472
1473 debug!(
1474 "winnowed to {} candidates for {:?}: {:?}",
1475 candidates.len(),
1476 stack,
1477 candidates
1478 );
1479
1480 // If there are STILL multiple candidates, we can further
1481 // reduce the list by dropping duplicates -- including
1482 // resolving specializations.
1483 if candidates.len() > 1 {
1484 let mut i = 0;
1485 while i < candidates.len() {
1486 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
1487 self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
1488 });
1489 if is_dup {
1490 debug!(
1491 "Dropping candidate #{}/{}: {:?}",
1492 i,
1493 candidates.len(),
1494 candidates[i]
1495 );
1496 candidates.swap_remove(i);
1497 } else {
1498 debug!(
1499 "Retaining candidate #{}/{}: {:?}",
1500 i,
1501 candidates.len(),
1502 candidates[i]
1503 );
1504 i += 1;
1505
1506 // If there are *STILL* multiple candidates, give up
1507 // and report ambiguity.
1508 if i > 1 {
1509 debug!("multiple matches, ambig");
1510 return Ok(None);
1511 }
1512 }
1513 }
1514 }
1515
1516 // If there are *NO* candidates, then there are no impls --
1517 // that we know of, anyway. Note that in the case where there
1518 // are unbound type variables within the obligation, it might
1519 // be the case that you could still satisfy the obligation
1520 // from another crate by instantiating the type variables with
1521 // a type from another crate that does have an impl. This case
1522 // is checked for in `evaluate_stack` (and hence users
1523 // who might care about this case, like coherence, should use
1524 // that function).
1525 if candidates.is_empty() {
1526 return Err(Unimplemented);
1527 }
1528
1529 // Just one candidate left.
1530 self.filter_negative_impls(candidates.pop().unwrap().candidate)
1531 }
1532
1533 fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
1534 debug!("is_knowable(intercrate={:?})", self.intercrate);
1535
1536 if !self.intercrate.is_some() {
1537 return None;
1538 }
1539
1540 let obligation = &stack.obligation;
1541 let predicate = self.infcx()
1542 .resolve_vars_if_possible(&obligation.predicate);
1543
1544 // Okay to skip binder because of the nature of the
1545 // trait-ref-is-knowable check, which does not care about
1546 // bound regions.
1547 let trait_ref = predicate.skip_binder().trait_ref;
1548
1549 let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
1550 if let (
1551 Some(Conflict::Downstream {
1552 used_to_be_broken: true,
1553 }),
1554 Some(IntercrateMode::Issue43355),
1555 ) = (result, self.intercrate)
1556 {
1557 debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
1558 None
1559 } else {
1560 result
1561 }
1562 }
1563
1564 /// Returns `true` if the global caches can be used.
1565 /// Do note that if the type itself is not in the
1566 /// global tcx, the local caches will be used.
1567 fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
1568 // If there are any where-clauses in scope, then we always use
1569 // a cache local to this particular scope. Otherwise, we
1570 // switch to a global cache. We used to try and draw
1571 // finer-grained distinctions, but that led to a serious of
1572 // annoying and weird bugs like #22019 and #18290. This simple
1573 // rule seems to be pretty clearly safe and also still retains
1574 // a very high hit rate (~95% when compiling rustc).
1575 if !param_env.caller_bounds.is_empty() {
1576 return false;
1577 }
1578
1579 // Avoid using the master cache during coherence and just rely
1580 // on the local cache. This effectively disables caching
1581 // during coherence. It is really just a simplification to
1582 // avoid us having to fear that coherence results "pollute"
1583 // the master cache. Since coherence executes pretty quickly,
1584 // it's not worth going to more trouble to increase the
1585 // hit-rate I don't think.
1586 if self.intercrate.is_some() {
1587 return false;
1588 }
1589
1590 // Otherwise, we can use the global cache.
1591 true
1592 }
1593
1594 fn check_candidate_cache(
1595 &mut self,
1596 param_env: ty::ParamEnv<'tcx>,
1597 cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
1598 ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
1599 let tcx = self.tcx();
1600 let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
1601 if self.can_use_global_caches(param_env) {
1602 let cache = tcx.selection_cache.hashmap.borrow();
1603 if let Some(cached) = cache.get(&trait_ref) {
1604 return Some(cached.get(tcx));
1605 }
1606 }
1607 self.infcx
1608 .selection_cache
1609 .hashmap
1610 .borrow()
1611 .get(trait_ref)
1612 .map(|v| v.get(tcx))
1613 }
1614
1615 /// Determines whether can we safely cache the result
1616 /// of selecting an obligation. This is almost always 'true',
1617 /// except when dealing with certain ParamCandidates.
1618 ///
1619 /// Ordinarily, a ParamCandidate will contain no inference variables,
1620 /// since it was usually produced directly from a DefId. However,
1621 /// certain cases (currently only librustdoc's blanket impl finder),
1622 /// a ParamEnv may be explicitly constructed with inference types.
1623 /// When this is the case, we do *not* want to cache the resulting selection
1624 /// candidate. This is due to the fact that it might not always be possible
1625 /// to equate the obligation's trait ref and the candidate's trait ref,
1626 /// if more constraints end up getting added to an inference variable.
1627 ///
1628 /// Because of this, we always want to re-run the full selection
1629 /// process for our obligation the next time we see it, since
1630 /// we might end up picking a different SelectionCandidate (or none at all)
1631 fn can_cache_candidate(&self,
1632 result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>
1633 ) -> bool {
1634 match result {
1635 Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => {
1636 !trait_ref.skip_binder().input_types().any(|t| t.walk().any(|t_| t_.is_ty_infer()))
1637 },
1638 _ => true
1639 }
1640 }
1641
1642 fn insert_candidate_cache(
1643 &mut self,
1644 param_env: ty::ParamEnv<'tcx>,
1645 cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
1646 dep_node: DepNodeIndex,
1647 candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
1648 ) {
1649 let tcx = self.tcx();
1650 let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
1651
1652 if !self.can_cache_candidate(&candidate) {
1653 debug!("insert_candidate_cache(trait_ref={:?}, candidate={:?} -\
1654 candidate is not cacheable", trait_ref, candidate);
1655 return;
1656
1657 }
1658
1659 if self.can_use_global_caches(param_env) {
1660 if let Err(Overflow) = candidate {
1661 // Don't cache overflow globally; we only produce this
1662 // in certain modes.
1663 } else if !trait_ref.has_local_value() {
1664 if !candidate.has_local_value() {
1665 debug!(
1666 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
1667 trait_ref, candidate,
1668 );
1669 // This may overwrite the cache with the same value
1670 tcx.selection_cache
1671 .hashmap
1672 .borrow_mut()
1673 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1674 return;
1675 }
1676 }
1677 }
1678
1679 debug!(
1680 "insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
1681 trait_ref, candidate,
1682 );
1683 self.infcx
1684 .selection_cache
1685 .hashmap
1686 .borrow_mut()
1687 .insert(trait_ref, WithDepNode::new(dep_node, candidate));
1688 }
1689
1690 fn assemble_candidates<'o>(
1691 &mut self,
1692 stack: &TraitObligationStack<'o, 'tcx>,
1693 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
1694 let TraitObligationStack { obligation, .. } = *stack;
1695 let ref obligation = Obligation {
1696 param_env: obligation.param_env,
1697 cause: obligation.cause.clone(),
1698 recursion_depth: obligation.recursion_depth,
1699 predicate: self.infcx()
1700 .resolve_vars_if_possible(&obligation.predicate),
1701 };
1702
1703 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
1704 // Self is a type variable (e.g., `_: AsRef<str>`).
1705 //
1706 // This is somewhat problematic, as the current scheme can't really
1707 // handle it turning to be a projection. This does end up as truly
1708 // ambiguous in most cases anyway.
1709 //
1710 // Take the fast path out - this also improves
1711 // performance by preventing assemble_candidates_from_impls from
1712 // matching every impl for this trait.
1713 return Ok(SelectionCandidateSet {
1714 vec: vec![],
1715 ambiguous: true,
1716 });
1717 }
1718
1719 let mut candidates = SelectionCandidateSet {
1720 vec: Vec::new(),
1721 ambiguous: false,
1722 };
1723
1724 self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
1725
1726 // Other bounds. Consider both in-scope bounds from fn decl
1727 // and applicable impls. There is a certain set of precedence rules here.
1728 let def_id = obligation.predicate.def_id();
1729 let lang_items = self.tcx().lang_items();
1730
1731 if lang_items.copy_trait() == Some(def_id) {
1732 debug!(
1733 "obligation self ty is {:?}",
1734 obligation.predicate.skip_binder().self_ty()
1735 );
1736
1737 // User-defined copy impls are permitted, but only for
1738 // structs and enums.
1739 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1740
1741 // For other types, we'll use the builtin rules.
1742 let copy_conditions = self.copy_clone_conditions(obligation);
1743 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
1744 } else if lang_items.sized_trait() == Some(def_id) {
1745 // Sized is never implementable by end-users, it is
1746 // always automatically computed.
1747 let sized_conditions = self.sized_conditions(obligation);
1748 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
1749 } else if lang_items.unsize_trait() == Some(def_id) {
1750 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
1751 } else {
1752 if lang_items.clone_trait() == Some(def_id) {
1753 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
1754 // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone`
1755 // types have builtin support for `Clone`.
1756 let clone_conditions = self.copy_clone_conditions(obligation);
1757 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
1758 }
1759
1760 self.assemble_generator_candidates(obligation, &mut candidates)?;
1761 self.assemble_closure_candidates(obligation, &mut candidates)?;
1762 self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
1763 self.assemble_candidates_from_impls(obligation, &mut candidates)?;
1764 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
1765 }
1766
1767 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
1768 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
1769 // Auto implementations have lower priority, so we only
1770 // consider triggering a default if there is no other impl that can apply.
1771 if candidates.vec.is_empty() {
1772 self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
1773 }
1774 debug!("candidate list size: {}", candidates.vec.len());
1775 Ok(candidates)
1776 }
1777
1778 fn assemble_candidates_from_projected_tys(
1779 &mut self,
1780 obligation: &TraitObligation<'tcx>,
1781 candidates: &mut SelectionCandidateSet<'tcx>,
1782 ) {
1783 debug!("assemble_candidates_for_projected_tys({:?})", obligation);
1784
1785 // before we go into the whole placeholder thing, just
1786 // quickly check if the self-type is a projection at all.
1787 match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
1788 ty::Projection(_) | ty::Opaque(..) => {}
1789 ty::Infer(ty::TyVar(_)) => {
1790 span_bug!(
1791 obligation.cause.span,
1792 "Self=_ should have been handled by assemble_candidates"
1793 );
1794 }
1795 _ => return,
1796 }
1797
1798 let result = self.infcx.probe(|snapshot| {
1799 self.match_projection_obligation_against_definition_bounds(
1800 obligation,
1801 snapshot,
1802 )
1803 });
1804
1805 if result {
1806 candidates.vec.push(ProjectionCandidate);
1807 }
1808 }
1809
1810 fn match_projection_obligation_against_definition_bounds(
1811 &mut self,
1812 obligation: &TraitObligation<'tcx>,
1813 snapshot: &CombinedSnapshot<'_, 'tcx>,
1814 ) -> bool {
1815 let poly_trait_predicate = self.infcx()
1816 .resolve_vars_if_possible(&obligation.predicate);
1817 let (placeholder_trait_predicate, placeholder_map) = self.infcx()
1818 .replace_bound_vars_with_placeholders(&poly_trait_predicate);
1819 debug!(
1820 "match_projection_obligation_against_definition_bounds: \
1821 placeholder_trait_predicate={:?}",
1822 placeholder_trait_predicate,
1823 );
1824
1825 let (def_id, substs) = match placeholder_trait_predicate.trait_ref.self_ty().sty {
1826 ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
1827 ty::Opaque(def_id, substs) => (def_id, substs),
1828 _ => {
1829 span_bug!(
1830 obligation.cause.span,
1831 "match_projection_obligation_against_definition_bounds() called \
1832 but self-ty is not a projection: {:?}",
1833 placeholder_trait_predicate.trait_ref.self_ty()
1834 );
1835 }
1836 };
1837 debug!(
1838 "match_projection_obligation_against_definition_bounds: \
1839 def_id={:?}, substs={:?}",
1840 def_id, substs
1841 );
1842
1843 let predicates_of = self.tcx().predicates_of(def_id);
1844 let bounds = predicates_of.instantiate(self.tcx(), substs);
1845 debug!(
1846 "match_projection_obligation_against_definition_bounds: \
1847 bounds={:?}",
1848 bounds
1849 );
1850
1851 let elaborated_predicates = util::elaborate_predicates(self.tcx(), bounds.predicates);
1852 let matching_bound = elaborated_predicates
1853 .filter_to_traits()
1854 .find(|bound| {
1855 self.infcx.probe(|_| {
1856 self.match_projection(
1857 obligation,
1858 bound.clone(),
1859 placeholder_trait_predicate.trait_ref.clone(),
1860 &placeholder_map,
1861 snapshot,
1862 )
1863 })
1864 });
1865
1866 debug!(
1867 "match_projection_obligation_against_definition_bounds: \
1868 matching_bound={:?}",
1869 matching_bound
1870 );
1871 match matching_bound {
1872 None => false,
1873 Some(bound) => {
1874 // Repeat the successful match, if any, this time outside of a probe.
1875 let result = self.match_projection(
1876 obligation,
1877 bound,
1878 placeholder_trait_predicate.trait_ref.clone(),
1879 &placeholder_map,
1880 snapshot,
1881 );
1882
1883 assert!(result);
1884 true
1885 }
1886 }
1887 }
1888
1889 fn match_projection(
1890 &mut self,
1891 obligation: &TraitObligation<'tcx>,
1892 trait_bound: ty::PolyTraitRef<'tcx>,
1893 placeholder_trait_ref: ty::TraitRef<'tcx>,
1894 placeholder_map: &PlaceholderMap<'tcx>,
1895 snapshot: &CombinedSnapshot<'_, 'tcx>,
1896 ) -> bool {
1897 debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
1898 self.infcx
1899 .at(&obligation.cause, obligation.param_env)
1900 .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
1901 .is_ok()
1902 &&
1903 self.infcx.leak_check(false, placeholder_map, snapshot).is_ok()
1904 }
1905
1906 /// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
1907 /// supplied to find out whether it is listed among them.
1908 ///
1909 /// Never affects inference environment.
1910 fn assemble_candidates_from_caller_bounds<'o>(
1911 &mut self,
1912 stack: &TraitObligationStack<'o, 'tcx>,
1913 candidates: &mut SelectionCandidateSet<'tcx>,
1914 ) -> Result<(), SelectionError<'tcx>> {
1915 debug!(
1916 "assemble_candidates_from_caller_bounds({:?})",
1917 stack.obligation
1918 );
1919
1920 let all_bounds = stack
1921 .obligation
1922 .param_env
1923 .caller_bounds
1924 .iter()
1925 .filter_map(|o| o.to_opt_poly_trait_ref());
1926
1927 // Micro-optimization: filter out predicates relating to different traits.
1928 let matching_bounds =
1929 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
1930
1931 // Keep only those bounds which may apply, and propagate overflow if it occurs.
1932 let mut param_candidates = vec![];
1933 for bound in matching_bounds {
1934 let wc = self.evaluate_where_clause(stack, bound.clone())?;
1935 if wc.may_apply() {
1936 param_candidates.push(ParamCandidate(bound));
1937 }
1938 }
1939
1940 candidates.vec.extend(param_candidates);
1941
1942 Ok(())
1943 }
1944
1945 fn evaluate_where_clause<'o>(
1946 &mut self,
1947 stack: &TraitObligationStack<'o, 'tcx>,
1948 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
1949 ) -> Result<EvaluationResult, OverflowError> {
1950 self.evaluation_probe(|this| {
1951 match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
1952 Ok(obligations) => {
1953 this.evaluate_predicates_recursively(stack.list(), obligations.into_iter())
1954 }
1955 Err(()) => Ok(EvaluatedToErr),
1956 }
1957 })
1958 }
1959
1960 fn assemble_generator_candidates(
1961 &mut self,
1962 obligation: &TraitObligation<'tcx>,
1963 candidates: &mut SelectionCandidateSet<'tcx>,
1964 ) -> Result<(), SelectionError<'tcx>> {
1965 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
1966 return Ok(());
1967 }
1968
1969 // Okay to skip binder because the substs on generator types never
1970 // touch bound regions, they just capture the in-scope
1971 // type/region parameters.
1972 let self_ty = *obligation.self_ty().skip_binder();
1973 match self_ty.sty {
1974 ty::Generator(..) => {
1975 debug!(
1976 "assemble_generator_candidates: self_ty={:?} obligation={:?}",
1977 self_ty, obligation
1978 );
1979
1980 candidates.vec.push(GeneratorCandidate);
1981 }
1982 ty::Infer(ty::TyVar(_)) => {
1983 debug!("assemble_generator_candidates: ambiguous self-type");
1984 candidates.ambiguous = true;
1985 }
1986 _ => {}
1987 }
1988
1989 Ok(())
1990 }
1991
1992 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
1993 /// FnMut<..>` where `X` is a closure type.
1994 ///
1995 /// Note: the type parameters on a closure candidate are modeled as *output* type
1996 /// parameters and hence do not affect whether this trait is a match or not. They will be
1997 /// unified during the confirmation step.
1998 fn assemble_closure_candidates(
1999 &mut self,
2000 obligation: &TraitObligation<'tcx>,
2001 candidates: &mut SelectionCandidateSet<'tcx>,
2002 ) -> Result<(), SelectionError<'tcx>> {
2003 let kind = match self.tcx()
2004 .lang_items()
2005 .fn_trait_kind(obligation.predicate.def_id())
2006 {
2007 Some(k) => k,
2008 None => {
2009 return Ok(());
2010 }
2011 };
2012
2013 // Okay to skip binder because the substs on closure types never
2014 // touch bound regions, they just capture the in-scope
2015 // type/region parameters
2016 match obligation.self_ty().skip_binder().sty {
2017 ty::Closure(closure_def_id, closure_substs) => {
2018 debug!(
2019 "assemble_unboxed_candidates: kind={:?} obligation={:?}",
2020 kind, obligation
2021 );
2022 match self.infcx.closure_kind(closure_def_id, closure_substs) {
2023 Some(closure_kind) => {
2024 debug!(
2025 "assemble_unboxed_candidates: closure_kind = {:?}",
2026 closure_kind
2027 );
2028 if closure_kind.extends(kind) {
2029 candidates.vec.push(ClosureCandidate);
2030 }
2031 }
2032 None => {
2033 debug!("assemble_unboxed_candidates: closure_kind not yet known");
2034 candidates.vec.push(ClosureCandidate);
2035 }
2036 }
2037 }
2038 ty::Infer(ty::TyVar(_)) => {
2039 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
2040 candidates.ambiguous = true;
2041 }
2042 _ => {}
2043 }
2044
2045 Ok(())
2046 }
2047
2048 /// Implement one of the `Fn()` family for a fn pointer.
2049 fn assemble_fn_pointer_candidates(
2050 &mut self,
2051 obligation: &TraitObligation<'tcx>,
2052 candidates: &mut SelectionCandidateSet<'tcx>,
2053 ) -> Result<(), SelectionError<'tcx>> {
2054 // We provide impl of all fn traits for fn pointers.
2055 if self.tcx()
2056 .lang_items()
2057 .fn_trait_kind(obligation.predicate.def_id())
2058 .is_none()
2059 {
2060 return Ok(());
2061 }
2062
2063 // Okay to skip binder because what we are inspecting doesn't involve bound regions
2064 let self_ty = *obligation.self_ty().skip_binder();
2065 match self_ty.sty {
2066 ty::Infer(ty::TyVar(_)) => {
2067 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
2068 candidates.ambiguous = true; // could wind up being a fn() type
2069 }
2070 // provide an impl, but only for suitable `fn` pointers
2071 ty::FnDef(..) | ty::FnPtr(_) => {
2072 if let ty::FnSig {
2073 unsafety: hir::Unsafety::Normal,
2074 abi: Abi::Rust,
2075 c_variadic: false,
2076 ..
2077 } = self_ty.fn_sig(self.tcx()).skip_binder()
2078 {
2079 candidates.vec.push(FnPointerCandidate);
2080 }
2081 }
2082 _ => {}
2083 }
2084
2085 Ok(())
2086 }
2087
2088 /// Search for impls that might apply to `obligation`.
2089 fn assemble_candidates_from_impls(
2090 &mut self,
2091 obligation: &TraitObligation<'tcx>,
2092 candidates: &mut SelectionCandidateSet<'tcx>,
2093 ) -> Result<(), SelectionError<'tcx>> {
2094 debug!(
2095 "assemble_candidates_from_impls(obligation={:?})",
2096 obligation
2097 );
2098
2099 self.tcx().for_each_relevant_impl(
2100 obligation.predicate.def_id(),
2101 obligation.predicate.skip_binder().trait_ref.self_ty(),
2102 |impl_def_id| {
2103 self.infcx.probe(|snapshot| {
2104 if let Ok(_substs) = self.match_impl(impl_def_id, obligation, snapshot)
2105 {
2106 candidates.vec.push(ImplCandidate(impl_def_id));
2107 }
2108 });
2109 },
2110 );
2111
2112 Ok(())
2113 }
2114
2115 fn assemble_candidates_from_auto_impls(
2116 &mut self,
2117 obligation: &TraitObligation<'tcx>,
2118 candidates: &mut SelectionCandidateSet<'tcx>,
2119 ) -> Result<(), SelectionError<'tcx>> {
2120 // Okay to skip binder here because the tests we do below do not involve bound regions.
2121 let self_ty = *obligation.self_ty().skip_binder();
2122 debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
2123
2124 let def_id = obligation.predicate.def_id();
2125
2126 if self.tcx().trait_is_auto(def_id) {
2127 match self_ty.sty {
2128 ty::Dynamic(..) => {
2129 // For object types, we don't know what the closed
2130 // over types are. This means we conservatively
2131 // say nothing; a candidate may be added by
2132 // `assemble_candidates_from_object_ty`.
2133 }
2134 ty::Foreign(..) => {
2135 // Since the contents of foreign types is unknown,
2136 // we don't add any `..` impl. Default traits could
2137 // still be provided by a manual implementation for
2138 // this trait and type.
2139 }
2140 ty::Param(..) | ty::Projection(..) => {
2141 // In these cases, we don't know what the actual
2142 // type is. Therefore, we cannot break it down
2143 // into its constituent types. So we don't
2144 // consider the `..` impl but instead just add no
2145 // candidates: this means that typeck will only
2146 // succeed if there is another reason to believe
2147 // that this obligation holds. That could be a
2148 // where-clause or, in the case of an object type,
2149 // it could be that the object type lists the
2150 // trait (e.g., `Foo+Send : Send`). See
2151 // `compile-fail/typeck-default-trait-impl-send-param.rs`
2152 // for an example of a test case that exercises
2153 // this path.
2154 }
2155 ty::Infer(ty::TyVar(_)) => {
2156 // the auto impl might apply, we don't know
2157 candidates.ambiguous = true;
2158 }
2159 ty::Generator(_, _, movability)
2160 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
2161 {
2162 match movability {
2163 hir::GeneratorMovability::Static => {
2164 // Immovable generators are never `Unpin`, so
2165 // suppress the normal auto-impl candidate for it.
2166 }
2167 hir::GeneratorMovability::Movable => {
2168 // Movable generators are always `Unpin`, so add an
2169 // unconditional builtin candidate.
2170 candidates.vec.push(BuiltinCandidate {
2171 has_nested: false,
2172 });
2173 }
2174 }
2175 }
2176
2177 _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
2178 }
2179 }
2180
2181 Ok(())
2182 }
2183
2184 /// Search for impls that might apply to `obligation`.
2185 fn assemble_candidates_from_object_ty(
2186 &mut self,
2187 obligation: &TraitObligation<'tcx>,
2188 candidates: &mut SelectionCandidateSet<'tcx>,
2189 ) {
2190 debug!(
2191 "assemble_candidates_from_object_ty(self_ty={:?})",
2192 obligation.self_ty().skip_binder()
2193 );
2194
2195 self.infcx.probe(|_snapshot| {
2196 // The code below doesn't care about regions, and the
2197 // self-ty here doesn't escape this probe, so just erase
2198 // any LBR.
2199 let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
2200 let poly_trait_ref = match self_ty.sty {
2201 ty::Dynamic(ref data, ..) => {
2202 if data.auto_traits()
2203 .any(|did| did == obligation.predicate.def_id())
2204 {
2205 debug!(
2206 "assemble_candidates_from_object_ty: matched builtin bound, \
2207 pushing candidate"
2208 );
2209 candidates.vec.push(BuiltinObjectCandidate);
2210 return;
2211 }
2212
2213 if let Some(principal) = data.principal() {
2214 principal.with_self_ty(self.tcx(), self_ty)
2215 } else {
2216 // Only auto-trait bounds exist.
2217 return;
2218 }
2219 }
2220 ty::Infer(ty::TyVar(_)) => {
2221 debug!("assemble_candidates_from_object_ty: ambiguous");
2222 candidates.ambiguous = true; // could wind up being an object type
2223 return;
2224 }
2225 _ => return,
2226 };
2227
2228 debug!(
2229 "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
2230 poly_trait_ref
2231 );
2232
2233 // Count only those upcast versions that match the trait-ref
2234 // we are looking for. Specifically, do not only check for the
2235 // correct trait, but also the correct type parameters.
2236 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
2237 // but `Foo` is declared as `trait Foo : Bar<u32>`.
2238 let upcast_trait_refs = util::supertraits(self.tcx(), poly_trait_ref)
2239 .filter(|upcast_trait_ref| {
2240 self.infcx.probe(|_| {
2241 let upcast_trait_ref = upcast_trait_ref.clone();
2242 self.match_poly_trait_ref(obligation, upcast_trait_ref)
2243 .is_ok()
2244 })
2245 })
2246 .count();
2247
2248 if upcast_trait_refs > 1 {
2249 // Can be upcast in many ways; need more type information.
2250 candidates.ambiguous = true;
2251 } else if upcast_trait_refs == 1 {
2252 candidates.vec.push(ObjectCandidate);
2253 }
2254 })
2255 }
2256
2257 /// Search for unsizing that might apply to `obligation`.
2258 fn assemble_candidates_for_unsizing(
2259 &mut self,
2260 obligation: &TraitObligation<'tcx>,
2261 candidates: &mut SelectionCandidateSet<'tcx>,
2262 ) {
2263 // We currently never consider higher-ranked obligations e.g.
2264 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
2265 // because they are a priori invalid, and we could potentially add support
2266 // for them later, it's just that there isn't really a strong need for it.
2267 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
2268 // impl, and those are generally applied to concrete types.
2269 //
2270 // That said, one might try to write a fn with a where clause like
2271 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
2272 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
2273 // Still, you'd be more likely to write that where clause as
2274 // T: Trait
2275 // so it seems ok if we (conservatively) fail to accept that `Unsize`
2276 // obligation above. Should be possible to extend this in the future.
2277 let source = match obligation.self_ty().no_bound_vars() {
2278 Some(t) => t,
2279 None => {
2280 // Don't add any candidates if there are bound regions.
2281 return;
2282 }
2283 };
2284 let target = obligation
2285 .predicate
2286 .skip_binder()
2287 .trait_ref
2288 .substs
2289 .type_at(1);
2290
2291 debug!(
2292 "assemble_candidates_for_unsizing(source={:?}, target={:?})",
2293 source, target
2294 );
2295
2296 let may_apply = match (&source.sty, &target.sty) {
2297 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
2298 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
2299 // Upcasts permit two things:
2300 //
2301 // 1. Dropping builtin bounds, e.g., `Foo+Send` to `Foo`
2302 // 2. Tightening the region bound, e.g., `Foo+'a` to `Foo+'b` if `'a : 'b`
2303 //
2304 // Note that neither of these changes requires any
2305 // change at runtime. Eventually this will be
2306 // generalized.
2307 //
2308 // We always upcast when we can because of reason
2309 // #2 (region bounds).
2310 data_a.principal_def_id() == data_b.principal_def_id()
2311 && data_b.auto_traits()
2312 // All of a's auto traits need to be in b's auto traits.
2313 .all(|b| data_a.auto_traits().any(|a| a == b))
2314 }
2315
2316 // T -> Trait.
2317 (_, &ty::Dynamic(..)) => true,
2318
2319 // Ambiguous handling is below T -> Trait, because inference
2320 // variables can still implement Unsize<Trait> and nested
2321 // obligations will have the final say (likely deferred).
2322 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
2323 debug!("assemble_candidates_for_unsizing: ambiguous");
2324 candidates.ambiguous = true;
2325 false
2326 }
2327
2328 // [T; n] -> [T].
2329 (&ty::Array(..), &ty::Slice(_)) => true,
2330
2331 // Struct<T> -> Struct<U>.
2332 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
2333 def_id_a == def_id_b
2334 }
2335
2336 // (.., T) -> (.., U).
2337 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
2338
2339 _ => false,
2340 };
2341
2342 if may_apply {
2343 candidates.vec.push(BuiltinUnsizeCandidate);
2344 }
2345 }
2346
2347 fn assemble_candidates_for_trait_alias(
2348 &mut self,
2349 obligation: &TraitObligation<'tcx>,
2350 candidates: &mut SelectionCandidateSet<'tcx>,
2351 ) -> Result<(), SelectionError<'tcx>> {
2352 // Okay to skip binder here because the tests we do below do not involve bound regions.
2353 let self_ty = *obligation.self_ty().skip_binder();
2354 debug!("assemble_candidates_for_trait_alias(self_ty={:?})", self_ty);
2355
2356 let def_id = obligation.predicate.def_id();
2357
2358 if self.tcx().is_trait_alias(def_id) {
2359 candidates.vec.push(TraitAliasCandidate(def_id.clone()));
2360 }
2361
2362 Ok(())
2363 }
2364
2365 ///////////////////////////////////////////////////////////////////////////
2366 // WINNOW
2367 //
2368 // Winnowing is the process of attempting to resolve ambiguity by
2369 // probing further. During the winnowing process, we unify all
2370 // type variables and then we also attempt to evaluate recursive
2371 // bounds to see if they are satisfied.
2372
2373 /// Returns `true` if `victim` should be dropped in favor of
2374 /// `other`. Generally speaking we will drop duplicate
2375 /// candidates and prefer where-clause candidates.
2376 ///
2377 /// See the comment for "SelectionCandidate" for more details.
2378 fn candidate_should_be_dropped_in_favor_of(
2379 &mut self,
2380 victim: &EvaluatedCandidate<'tcx>,
2381 other: &EvaluatedCandidate<'tcx>,
2382 ) -> bool {
2383 if victim.candidate == other.candidate {
2384 return true;
2385 }
2386
2387 // Check if a bound would previously have been removed when normalizing
2388 // the param_env so that it can be given the lowest priority. See
2389 // #50825 for the motivation for this.
2390 let is_global =
2391 |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
2392
2393 match other.candidate {
2394 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2395 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2396 // lifetime of a variable.
2397 BuiltinCandidate { has_nested: false } => true,
2398 ParamCandidate(ref cand) => match victim.candidate {
2399 AutoImplCandidate(..) => {
2400 bug!(
2401 "default implementations shouldn't be recorded \
2402 when there are other valid candidates"
2403 );
2404 }
2405 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2406 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2407 // lifetime of a variable.
2408 BuiltinCandidate { has_nested: false } => false,
2409 ImplCandidate(..)
2410 | ClosureCandidate
2411 | GeneratorCandidate
2412 | FnPointerCandidate
2413 | BuiltinObjectCandidate
2414 | BuiltinUnsizeCandidate
2415 | BuiltinCandidate { .. }
2416 | TraitAliasCandidate(..) => {
2417 // Global bounds from the where clause should be ignored
2418 // here (see issue #50825). Otherwise, we have a where
2419 // clause so don't go around looking for impls.
2420 !is_global(cand)
2421 }
2422 ObjectCandidate | ProjectionCandidate => {
2423 // Arbitrarily give param candidates priority
2424 // over projection and object candidates.
2425 !is_global(cand)
2426 }
2427 ParamCandidate(..) => false,
2428 },
2429 ObjectCandidate | ProjectionCandidate => match victim.candidate {
2430 AutoImplCandidate(..) => {
2431 bug!(
2432 "default implementations shouldn't be recorded \
2433 when there are other valid candidates"
2434 );
2435 }
2436 // Prefer BuiltinCandidate { has_nested: false } to anything else.
2437 // This is a fix for #53123 and prevents winnowing from accidentally extending the
2438 // lifetime of a variable.
2439 BuiltinCandidate { has_nested: false } => false,
2440 ImplCandidate(..)
2441 | ClosureCandidate
2442 | GeneratorCandidate
2443 | FnPointerCandidate
2444 | BuiltinObjectCandidate
2445 | BuiltinUnsizeCandidate
2446 | BuiltinCandidate { .. }
2447 | TraitAliasCandidate(..) => true,
2448 ObjectCandidate | ProjectionCandidate => {
2449 // Arbitrarily give param candidates priority
2450 // over projection and object candidates.
2451 true
2452 }
2453 ParamCandidate(ref cand) => is_global(cand),
2454 },
2455 ImplCandidate(other_def) => {
2456 // See if we can toss out `victim` based on specialization.
2457 // This requires us to know *for sure* that the `other` impl applies
2458 // i.e., EvaluatedToOk:
2459 if other.evaluation.must_apply_modulo_regions() {
2460 match victim.candidate {
2461 ImplCandidate(victim_def) => {
2462 let tcx = self.tcx().global_tcx();
2463 return tcx.specializes((other_def, victim_def))
2464 || tcx.impls_are_allowed_to_overlap(
2465 other_def, victim_def).is_some();
2466 }
2467 ParamCandidate(ref cand) => {
2468 // Prefer the impl to a global where clause candidate.
2469 return is_global(cand);
2470 }
2471 _ => (),
2472 }
2473 }
2474
2475 false
2476 }
2477 ClosureCandidate
2478 | GeneratorCandidate
2479 | FnPointerCandidate
2480 | BuiltinObjectCandidate
2481 | BuiltinUnsizeCandidate
2482 | BuiltinCandidate { has_nested: true } => {
2483 match victim.candidate {
2484 ParamCandidate(ref cand) => {
2485 // Prefer these to a global where-clause bound
2486 // (see issue #50825)
2487 is_global(cand) && other.evaluation.must_apply_modulo_regions()
2488 }
2489 _ => false,
2490 }
2491 }
2492 _ => false,
2493 }
2494 }
2495
2496 ///////////////////////////////////////////////////////////////////////////
2497 // BUILTIN BOUNDS
2498 //
2499 // These cover the traits that are built-in to the language
2500 // itself: `Copy`, `Clone` and `Sized`.
2501
2502 fn assemble_builtin_bound_candidates(
2503 &mut self,
2504 conditions: BuiltinImplConditions<'tcx>,
2505 candidates: &mut SelectionCandidateSet<'tcx>,
2506 ) -> Result<(), SelectionError<'tcx>> {
2507 match conditions {
2508 BuiltinImplConditions::Where(nested) => {
2509 debug!("builtin_bound: nested={:?}", nested);
2510 candidates.vec.push(BuiltinCandidate {
2511 has_nested: nested.skip_binder().len() > 0,
2512 });
2513 }
2514 BuiltinImplConditions::None => {}
2515 BuiltinImplConditions::Ambiguous => {
2516 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
2517 candidates.ambiguous = true;
2518 }
2519 }
2520
2521 Ok(())
2522 }
2523
2524 fn sized_conditions(
2525 &mut self,
2526 obligation: &TraitObligation<'tcx>,
2527 ) -> BuiltinImplConditions<'tcx> {
2528 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2529
2530 // NOTE: binder moved to (*)
2531 let self_ty = self.infcx
2532 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2533
2534 match self_ty.sty {
2535 ty::Infer(ty::IntVar(_))
2536 | ty::Infer(ty::FloatVar(_))
2537 | ty::Uint(_)
2538 | ty::Int(_)
2539 | ty::Bool
2540 | ty::Float(_)
2541 | ty::FnDef(..)
2542 | ty::FnPtr(_)
2543 | ty::RawPtr(..)
2544 | ty::Char
2545 | ty::Ref(..)
2546 | ty::Generator(..)
2547 | ty::GeneratorWitness(..)
2548 | ty::Array(..)
2549 | ty::Closure(..)
2550 | ty::Never
2551 | ty::Error => {
2552 // safe for everything
2553 Where(ty::Binder::dummy(Vec::new()))
2554 }
2555
2556 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
2557
2558 ty::Tuple(tys) => {
2559 Where(ty::Binder::bind(tys.last().into_iter().map(|k| k.expect_ty()).collect()))
2560 }
2561
2562 ty::Adt(def, substs) => {
2563 let sized_crit = def.sized_constraint(self.tcx());
2564 // (*) binder moved here
2565 Where(ty::Binder::bind(
2566 sized_crit
2567 .iter()
2568 .map(|ty| ty.subst(self.tcx(), substs))
2569 .collect(),
2570 ))
2571 }
2572
2573 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
2574 ty::Infer(ty::TyVar(_)) => Ambiguous,
2575
2576 ty::UnnormalizedProjection(..)
2577 | ty::Placeholder(..)
2578 | ty::Bound(..)
2579 | ty::Infer(ty::FreshTy(_))
2580 | ty::Infer(ty::FreshIntTy(_))
2581 | ty::Infer(ty::FreshFloatTy(_)) => {
2582 bug!(
2583 "asked to assemble builtin bounds of unexpected type: {:?}",
2584 self_ty
2585 );
2586 }
2587 }
2588 }
2589
2590 fn copy_clone_conditions(
2591 &mut self,
2592 obligation: &TraitObligation<'tcx>,
2593 ) -> BuiltinImplConditions<'tcx> {
2594 // NOTE: binder moved to (*)
2595 let self_ty = self.infcx
2596 .shallow_resolve(obligation.predicate.skip_binder().self_ty());
2597
2598 use self::BuiltinImplConditions::{Ambiguous, None, Where};
2599
2600 match self_ty.sty {
2601 ty::Infer(ty::IntVar(_))
2602 | ty::Infer(ty::FloatVar(_))
2603 | ty::FnDef(..)
2604 | ty::FnPtr(_)
2605 | ty::Error => Where(ty::Binder::dummy(Vec::new())),
2606
2607 ty::Uint(_)
2608 | ty::Int(_)
2609 | ty::Bool
2610 | ty::Float(_)
2611 | ty::Char
2612 | ty::RawPtr(..)
2613 | ty::Never
2614 | ty::Ref(_, _, hir::MutImmutable) => {
2615 // Implementations provided in libcore
2616 None
2617 }
2618
2619 ty::Dynamic(..)
2620 | ty::Str
2621 | ty::Slice(..)
2622 | ty::Generator(..)
2623 | ty::GeneratorWitness(..)
2624 | ty::Foreign(..)
2625 | ty::Ref(_, _, hir::MutMutable) => None,
2626
2627 ty::Array(element_ty, _) => {
2628 // (*) binder moved here
2629 Where(ty::Binder::bind(vec![element_ty]))
2630 }
2631
2632 ty::Tuple(tys) => {
2633 // (*) binder moved here
2634 Where(ty::Binder::bind(tys.iter().map(|k| k.expect_ty()).collect()))
2635 }
2636
2637 ty::Closure(def_id, substs) => {
2638 // (*) binder moved here
2639 Where(ty::Binder::bind(
2640 substs.upvar_tys(def_id, self.tcx()).collect(),
2641 ))
2642 }
2643
2644 ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
2645 // Fallback to whatever user-defined impls exist in this case.
2646 None
2647 }
2648
2649 ty::Infer(ty::TyVar(_)) => {
2650 // Unbound type variable. Might or might not have
2651 // applicable impls and so forth, depending on what
2652 // those type variables wind up being bound to.
2653 Ambiguous
2654 }
2655
2656 ty::UnnormalizedProjection(..)
2657 | ty::Placeholder(..)
2658 | ty::Bound(..)
2659 | ty::Infer(ty::FreshTy(_))
2660 | ty::Infer(ty::FreshIntTy(_))
2661 | ty::Infer(ty::FreshFloatTy(_)) => {
2662 bug!(
2663 "asked to assemble builtin bounds of unexpected type: {:?}",
2664 self_ty
2665 );
2666 }
2667 }
2668 }
2669
2670 /// For default impls, we need to break apart a type into its
2671 /// "constituent types" -- meaning, the types that it contains.
2672 ///
2673 /// Here are some (simple) examples:
2674 ///
2675 /// ```
2676 /// (i32, u32) -> [i32, u32]
2677 /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
2678 /// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
2679 /// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
2680 /// ```
2681 fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
2682 match t.sty {
2683 ty::Uint(_)
2684 | ty::Int(_)
2685 | ty::Bool
2686 | ty::Float(_)
2687 | ty::FnDef(..)
2688 | ty::FnPtr(_)
2689 | ty::Str
2690 | ty::Error
2691 | ty::Infer(ty::IntVar(_))
2692 | ty::Infer(ty::FloatVar(_))
2693 | ty::Never
2694 | ty::Char => Vec::new(),
2695
2696 ty::UnnormalizedProjection(..)
2697 | ty::Placeholder(..)
2698 | ty::Dynamic(..)
2699 | ty::Param(..)
2700 | ty::Foreign(..)
2701 | ty::Projection(..)
2702 | ty::Bound(..)
2703 | ty::Infer(ty::TyVar(_))
2704 | ty::Infer(ty::FreshTy(_))
2705 | ty::Infer(ty::FreshIntTy(_))
2706 | ty::Infer(ty::FreshFloatTy(_)) => {
2707 bug!(
2708 "asked to assemble constituent types of unexpected type: {:?}",
2709 t
2710 );
2711 }
2712
2713 ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
2714 vec![element_ty]
2715 }
2716
2717 ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
2718
2719 ty::Tuple(ref tys) => {
2720 // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
2721 tys.iter().map(|k| k.expect_ty()).collect()
2722 }
2723
2724 ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
2725
2726 ty::Generator(def_id, ref substs, _) => {
2727 let witness = substs.witness(def_id, self.tcx());
2728 substs
2729 .upvar_tys(def_id, self.tcx())
2730 .chain(iter::once(witness))
2731 .collect()
2732 }
2733
2734 ty::GeneratorWitness(types) => {
2735 // This is sound because no regions in the witness can refer to
2736 // the binder outside the witness. So we'll effectivly reuse
2737 // the implicit binder around the witness.
2738 types.skip_binder().to_vec()
2739 }
2740
2741 // for `PhantomData<T>`, we pass `T`
2742 ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
2743
2744 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
2745
2746 ty::Opaque(def_id, substs) => {
2747 // We can resolve the `impl Trait` to its concrete type,
2748 // which enforces a DAG between the functions requiring
2749 // the auto trait bounds in question.
2750 vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]
2751 }
2752 }
2753 }
2754
2755 fn collect_predicates_for_types(
2756 &mut self,
2757 param_env: ty::ParamEnv<'tcx>,
2758 cause: ObligationCause<'tcx>,
2759 recursion_depth: usize,
2760 trait_def_id: DefId,
2761 types: ty::Binder<Vec<Ty<'tcx>>>,
2762 ) -> Vec<PredicateObligation<'tcx>> {
2763 // Because the types were potentially derived from
2764 // higher-ranked obligations they may reference late-bound
2765 // regions. For example, `for<'a> Foo<&'a int> : Copy` would
2766 // yield a type like `for<'a> &'a int`. In general, we
2767 // maintain the invariant that we never manipulate bound
2768 // regions, so we have to process these bound regions somehow.
2769 //
2770 // The strategy is to:
2771 //
2772 // 1. Instantiate those regions to placeholder regions (e.g.,
2773 // `for<'a> &'a int` becomes `&0 int`.
2774 // 2. Produce something like `&'0 int : Copy`
2775 // 3. Re-bind the regions back to `for<'a> &'a int : Copy`
2776
2777 types
2778 .skip_binder()
2779 .into_iter()
2780 .flat_map(|ty| {
2781 // binder moved -\
2782 let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
2783
2784 self.infcx.in_snapshot(|_| {
2785 let (skol_ty, _) = self.infcx
2786 .replace_bound_vars_with_placeholders(&ty);
2787 let Normalized {
2788 value: normalized_ty,
2789 mut obligations,
2790 } = project::normalize_with_depth(
2791 self,
2792 param_env,
2793 cause.clone(),
2794 recursion_depth,
2795 &skol_ty,
2796 );
2797 let skol_obligation = self.tcx().predicate_for_trait_def(
2798 param_env,
2799 cause.clone(),
2800 trait_def_id,
2801 recursion_depth,
2802 normalized_ty,
2803 &[],
2804 );
2805 obligations.push(skol_obligation);
2806 obligations
2807 })
2808 })
2809 .collect()
2810 }
2811
2812 ///////////////////////////////////////////////////////////////////////////
2813 // CONFIRMATION
2814 //
2815 // Confirmation unifies the output type parameters of the trait
2816 // with the values found in the obligation, possibly yielding a
2817 // type error. See the [rustc guide] for more details.
2818 //
2819 // [rustc guide]:
2820 // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation
2821
2822 fn confirm_candidate(
2823 &mut self,
2824 obligation: &TraitObligation<'tcx>,
2825 candidate: SelectionCandidate<'tcx>,
2826 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
2827 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
2828
2829 match candidate {
2830 BuiltinCandidate { has_nested } => {
2831 let data = self.confirm_builtin_candidate(obligation, has_nested);
2832 Ok(VtableBuiltin(data))
2833 }
2834
2835 ParamCandidate(param) => {
2836 let obligations = self.confirm_param_candidate(obligation, param);
2837 Ok(VtableParam(obligations))
2838 }
2839
2840 ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
2841 obligation,
2842 impl_def_id,
2843 ))),
2844
2845 AutoImplCandidate(trait_def_id) => {
2846 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
2847 Ok(VtableAutoImpl(data))
2848 }
2849
2850 ProjectionCandidate => {
2851 self.confirm_projection_candidate(obligation);
2852 Ok(VtableParam(Vec::new()))
2853 }
2854
2855 ClosureCandidate => {
2856 let vtable_closure = self.confirm_closure_candidate(obligation)?;
2857 Ok(VtableClosure(vtable_closure))
2858 }
2859
2860 GeneratorCandidate => {
2861 let vtable_generator = self.confirm_generator_candidate(obligation)?;
2862 Ok(VtableGenerator(vtable_generator))
2863 }
2864
2865 FnPointerCandidate => {
2866 let data = self.confirm_fn_pointer_candidate(obligation)?;
2867 Ok(VtableFnPointer(data))
2868 }
2869
2870 TraitAliasCandidate(alias_def_id) => {
2871 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
2872 Ok(VtableTraitAlias(data))
2873 }
2874
2875 ObjectCandidate => {
2876 let data = self.confirm_object_candidate(obligation);
2877 Ok(VtableObject(data))
2878 }
2879
2880 BuiltinObjectCandidate => {
2881 // This indicates something like `(Trait+Send) :
2882 // Send`. In this case, we know that this holds
2883 // because that's what the object type is telling us,
2884 // and there's really no additional obligations to
2885 // prove and no types in particular to unify etc.
2886 Ok(VtableParam(Vec::new()))
2887 }
2888
2889 BuiltinUnsizeCandidate => {
2890 let data = self.confirm_builtin_unsize_candidate(obligation)?;
2891 Ok(VtableBuiltin(data))
2892 }
2893 }
2894 }
2895
2896 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
2897 self.infcx.in_snapshot(|snapshot| {
2898 let result =
2899 self.match_projection_obligation_against_definition_bounds(
2900 obligation,
2901 snapshot,
2902 );
2903 assert!(result);
2904 })
2905 }
2906
2907 fn confirm_param_candidate(
2908 &mut self,
2909 obligation: &TraitObligation<'tcx>,
2910 param: ty::PolyTraitRef<'tcx>,
2911 ) -> Vec<PredicateObligation<'tcx>> {
2912 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
2913
2914 // During evaluation, we already checked that this
2915 // where-clause trait-ref could be unified with the obligation
2916 // trait-ref. Repeat that unification now without any
2917 // transactional boundary; it should not fail.
2918 match self.match_where_clause_trait_ref(obligation, param.clone()) {
2919 Ok(obligations) => obligations,
2920 Err(()) => {
2921 bug!(
2922 "Where clause `{:?}` was applicable to `{:?}` but now is not",
2923 param,
2924 obligation
2925 );
2926 }
2927 }
2928 }
2929
2930 fn confirm_builtin_candidate(
2931 &mut self,
2932 obligation: &TraitObligation<'tcx>,
2933 has_nested: bool,
2934 ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
2935 debug!(
2936 "confirm_builtin_candidate({:?}, {:?})",
2937 obligation, has_nested
2938 );
2939
2940 let lang_items = self.tcx().lang_items();
2941 let obligations = if has_nested {
2942 let trait_def = obligation.predicate.def_id();
2943 let conditions = if Some(trait_def) == lang_items.sized_trait() {
2944 self.sized_conditions(obligation)
2945 } else if Some(trait_def) == lang_items.copy_trait() {
2946 self.copy_clone_conditions(obligation)
2947 } else if Some(trait_def) == lang_items.clone_trait() {
2948 self.copy_clone_conditions(obligation)
2949 } else {
2950 bug!("unexpected builtin trait {:?}", trait_def)
2951 };
2952 let nested = match conditions {
2953 BuiltinImplConditions::Where(nested) => nested,
2954 _ => bug!(
2955 "obligation {:?} had matched a builtin impl but now doesn't",
2956 obligation
2957 ),
2958 };
2959
2960 let cause = obligation.derived_cause(BuiltinDerivedObligation);
2961 self.collect_predicates_for_types(
2962 obligation.param_env,
2963 cause,
2964 obligation.recursion_depth + 1,
2965 trait_def,
2966 nested,
2967 )
2968 } else {
2969 vec![]
2970 };
2971
2972 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
2973
2974 VtableBuiltinData {
2975 nested: obligations,
2976 }
2977 }
2978
2979 /// This handles the case where a `auto trait Foo` impl is being used.
2980 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
2981 ///
2982 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
2983 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
2984 fn confirm_auto_impl_candidate(
2985 &mut self,
2986 obligation: &TraitObligation<'tcx>,
2987 trait_def_id: DefId,
2988 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
2989 debug!(
2990 "confirm_auto_impl_candidate({:?}, {:?})",
2991 obligation, trait_def_id
2992 );
2993
2994 let types = obligation.predicate.map_bound(|inner| {
2995 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
2996 self.constituent_types_for_ty(self_ty)
2997 });
2998 self.vtable_auto_impl(obligation, trait_def_id, types)
2999 }
3000
3001 /// See `confirm_auto_impl_candidate`.
3002 fn vtable_auto_impl(
3003 &mut self,
3004 obligation: &TraitObligation<'tcx>,
3005 trait_def_id: DefId,
3006 nested: ty::Binder<Vec<Ty<'tcx>>>,
3007 ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
3008 debug!("vtable_auto_impl: nested={:?}", nested);
3009
3010 let cause = obligation.derived_cause(BuiltinDerivedObligation);
3011 let mut obligations = self.collect_predicates_for_types(
3012 obligation.param_env,
3013 cause,
3014 obligation.recursion_depth + 1,
3015 trait_def_id,
3016 nested,
3017 );
3018
3019 let trait_obligations: Vec<PredicateObligation<'_>> = self.infcx.in_snapshot(|_| {
3020 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
3021 let (trait_ref, _) = self.infcx
3022 .replace_bound_vars_with_placeholders(&poly_trait_ref);
3023 let cause = obligation.derived_cause(ImplDerivedObligation);
3024 self.impl_or_trait_obligations(
3025 cause,
3026 obligation.recursion_depth + 1,
3027 obligation.param_env,
3028 trait_def_id,
3029 &trait_ref.substs,
3030 )
3031 });
3032
3033 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
3034 // predicate as usual. It won't have any effect since auto traits are coinductive.
3035 obligations.extend(trait_obligations);
3036
3037 debug!("vtable_auto_impl: obligations={:?}", obligations);
3038
3039 VtableAutoImplData {
3040 trait_def_id,
3041 nested: obligations,
3042 }
3043 }
3044
3045 fn confirm_impl_candidate(
3046 &mut self,
3047 obligation: &TraitObligation<'tcx>,
3048 impl_def_id: DefId,
3049 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3050 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
3051
3052 // First, create the substitutions by matching the impl again,
3053 // this time not in a probe.
3054 self.infcx.in_snapshot(|snapshot| {
3055 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
3056 debug!("confirm_impl_candidate: substs={:?}", substs);
3057 let cause = obligation.derived_cause(ImplDerivedObligation);
3058 self.vtable_impl(
3059 impl_def_id,
3060 substs,
3061 cause,
3062 obligation.recursion_depth + 1,
3063 obligation.param_env,
3064 )
3065 })
3066 }
3067
3068 fn vtable_impl(
3069 &mut self,
3070 impl_def_id: DefId,
3071 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
3072 cause: ObligationCause<'tcx>,
3073 recursion_depth: usize,
3074 param_env: ty::ParamEnv<'tcx>,
3075 ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
3076 debug!(
3077 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
3078 impl_def_id, substs, recursion_depth,
3079 );
3080
3081 let mut impl_obligations = self.impl_or_trait_obligations(
3082 cause,
3083 recursion_depth,
3084 param_env,
3085 impl_def_id,
3086 &substs.value,
3087 );
3088
3089 debug!(
3090 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
3091 impl_def_id, impl_obligations
3092 );
3093
3094 // Because of RFC447, the impl-trait-ref and obligations
3095 // are sufficient to determine the impl substs, without
3096 // relying on projections in the impl-trait-ref.
3097 //
3098 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
3099 impl_obligations.append(&mut substs.obligations);
3100
3101 VtableImplData {
3102 impl_def_id,
3103 substs: substs.value,
3104 nested: impl_obligations,
3105 }
3106 }
3107
3108 fn confirm_object_candidate(
3109 &mut self,
3110 obligation: &TraitObligation<'tcx>,
3111 ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
3112 debug!("confirm_object_candidate({:?})", obligation);
3113
3114 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
3115 // probably flatten the binder from the obligation and the binder
3116 // from the object. Have to try to make a broken test case that
3117 // results.
3118 let self_ty = self.infcx
3119 .shallow_resolve(*obligation.self_ty().skip_binder());
3120 let poly_trait_ref = match self_ty.sty {
3121 ty::Dynamic(ref data, ..) =>
3122 data.principal().unwrap_or_else(|| {
3123 span_bug!(obligation.cause.span, "object candidate with no principal")
3124 }).with_self_ty(self.tcx(), self_ty),
3125 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
3126 };
3127
3128 let mut upcast_trait_ref = None;
3129 let mut nested = vec![];
3130 let vtable_base;
3131
3132 {
3133 let tcx = self.tcx();
3134
3135 // We want to find the first supertrait in the list of
3136 // supertraits that we can unify with, and do that
3137 // unification. We know that there is exactly one in the list
3138 // where we can unify because otherwise select would have
3139 // reported an ambiguity. (When we do find a match, also
3140 // record it for later.)
3141 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
3142 |&t| match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
3143 Ok(obligations) => {
3144 upcast_trait_ref = Some(t);
3145 nested.extend(obligations);
3146 false
3147 }
3148 Err(_) => true,
3149 },
3150 );
3151
3152 // Additionally, for each of the nonmatching predicates that
3153 // we pass over, we sum up the set of number of vtable
3154 // entries, so that we can compute the offset for the selected
3155 // trait.
3156 vtable_base = nonmatching.map(|t| tcx.count_own_vtable_entries(t)).sum();
3157 }
3158
3159 VtableObjectData {
3160 upcast_trait_ref: upcast_trait_ref.unwrap(),
3161 vtable_base,
3162 nested,
3163 }
3164 }
3165
3166 fn confirm_fn_pointer_candidate(
3167 &mut self,
3168 obligation: &TraitObligation<'tcx>,
3169 ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3170 debug!("confirm_fn_pointer_candidate({:?})", obligation);
3171
3172 // Okay to skip binder; it is reintroduced below.
3173 let self_ty = self.infcx
3174 .shallow_resolve(*obligation.self_ty().skip_binder());
3175 let sig = self_ty.fn_sig(self.tcx());
3176 let trait_ref = self.tcx()
3177 .closure_trait_ref_and_return_type(
3178 obligation.predicate.def_id(),
3179 self_ty,
3180 sig,
3181 util::TupleArgumentsFlag::Yes,
3182 )
3183 .map_bound(|(trait_ref, _)| trait_ref);
3184
3185 let Normalized {
3186 value: trait_ref,
3187 obligations,
3188 } = project::normalize_with_depth(
3189 self,
3190 obligation.param_env,
3191 obligation.cause.clone(),
3192 obligation.recursion_depth + 1,
3193 &trait_ref,
3194 );
3195
3196 self.confirm_poly_trait_refs(
3197 obligation.cause.clone(),
3198 obligation.param_env,
3199 obligation.predicate.to_poly_trait_ref(),
3200 trait_ref,
3201 )?;
3202 Ok(VtableFnPointerData {
3203 fn_ty: self_ty,
3204 nested: obligations,
3205 })
3206 }
3207
3208 fn confirm_trait_alias_candidate(
3209 &mut self,
3210 obligation: &TraitObligation<'tcx>,
3211 alias_def_id: DefId,
3212 ) -> VtableTraitAliasData<'tcx, PredicateObligation<'tcx>> {
3213 debug!(
3214 "confirm_trait_alias_candidate({:?}, {:?})",
3215 obligation, alias_def_id
3216 );
3217
3218 self.infcx.in_snapshot(|_| {
3219 let (predicate, _) = self.infcx()
3220 .replace_bound_vars_with_placeholders(&obligation.predicate);
3221 let trait_ref = predicate.trait_ref;
3222 let trait_def_id = trait_ref.def_id;
3223 let substs = trait_ref.substs;
3224
3225 let trait_obligations = self.impl_or_trait_obligations(
3226 obligation.cause.clone(),
3227 obligation.recursion_depth,
3228 obligation.param_env,
3229 trait_def_id,
3230 &substs,
3231 );
3232
3233 debug!(
3234 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
3235 trait_def_id, trait_obligations
3236 );
3237
3238 VtableTraitAliasData {
3239 alias_def_id,
3240 substs: substs,
3241 nested: trait_obligations,
3242 }
3243 })
3244 }
3245
3246 fn confirm_generator_candidate(
3247 &mut self,
3248 obligation: &TraitObligation<'tcx>,
3249 ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3250 // Okay to skip binder because the substs on generator types never
3251 // touch bound regions, they just capture the in-scope
3252 // type/region parameters.
3253 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3254 let (generator_def_id, substs) = match self_ty.sty {
3255 ty::Generator(id, substs, _) => (id, substs),
3256 _ => bug!("closure candidate for non-closure {:?}", obligation),
3257 };
3258
3259 debug!(
3260 "confirm_generator_candidate({:?},{:?},{:?})",
3261 obligation, generator_def_id, substs
3262 );
3263
3264 let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
3265 let Normalized {
3266 value: trait_ref,
3267 mut obligations,
3268 } = normalize_with_depth(
3269 self,
3270 obligation.param_env,
3271 obligation.cause.clone(),
3272 obligation.recursion_depth + 1,
3273 &trait_ref,
3274 );
3275
3276 debug!(
3277 "confirm_generator_candidate(generator_def_id={:?}, \
3278 trait_ref={:?}, obligations={:?})",
3279 generator_def_id, trait_ref, obligations
3280 );
3281
3282 obligations.extend(self.confirm_poly_trait_refs(
3283 obligation.cause.clone(),
3284 obligation.param_env,
3285 obligation.predicate.to_poly_trait_ref(),
3286 trait_ref,
3287 )?);
3288
3289 Ok(VtableGeneratorData {
3290 generator_def_id: generator_def_id,
3291 substs: substs.clone(),
3292 nested: obligations,
3293 })
3294 }
3295
3296 fn confirm_closure_candidate(
3297 &mut self,
3298 obligation: &TraitObligation<'tcx>,
3299 ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3300 debug!("confirm_closure_candidate({:?})", obligation);
3301
3302 let kind = self.tcx()
3303 .lang_items()
3304 .fn_trait_kind(obligation.predicate.def_id())
3305 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
3306
3307 // Okay to skip binder because the substs on closure types never
3308 // touch bound regions, they just capture the in-scope
3309 // type/region parameters.
3310 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
3311 let (closure_def_id, substs) = match self_ty.sty {
3312 ty::Closure(id, substs) => (id, substs),
3313 _ => bug!("closure candidate for non-closure {:?}", obligation),
3314 };
3315
3316 let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
3317 let Normalized {
3318 value: trait_ref,
3319 mut obligations,
3320 } = normalize_with_depth(
3321 self,
3322 obligation.param_env,
3323 obligation.cause.clone(),
3324 obligation.recursion_depth + 1,
3325 &trait_ref,
3326 );
3327
3328 debug!(
3329 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
3330 closure_def_id, trait_ref, obligations
3331 );
3332
3333 obligations.extend(self.confirm_poly_trait_refs(
3334 obligation.cause.clone(),
3335 obligation.param_env,
3336 obligation.predicate.to_poly_trait_ref(),
3337 trait_ref,
3338 )?);
3339
3340 // FIXME: chalk
3341 if !self.tcx().sess.opts.debugging_opts.chalk {
3342 obligations.push(Obligation::new(
3343 obligation.cause.clone(),
3344 obligation.param_env,
3345 ty::Predicate::ClosureKind(closure_def_id, substs, kind),
3346 ));
3347 }
3348
3349 Ok(VtableClosureData {
3350 closure_def_id,
3351 substs: substs.clone(),
3352 nested: obligations,
3353 })
3354 }
3355
3356 /// In the case of closure types and fn pointers,
3357 /// we currently treat the input type parameters on the trait as
3358 /// outputs. This means that when we have a match we have only
3359 /// considered the self type, so we have to go back and make sure
3360 /// to relate the argument types too. This is kind of wrong, but
3361 /// since we control the full set of impls, also not that wrong,
3362 /// and it DOES yield better error messages (since we don't report
3363 /// errors as if there is no applicable impl, but rather report
3364 /// errors are about mismatched argument types.
3365 ///
3366 /// Here is an example. Imagine we have a closure expression
3367 /// and we desugared it so that the type of the expression is
3368 /// `Closure`, and `Closure` expects an int as argument. Then it
3369 /// is "as if" the compiler generated this impl:
3370 ///
3371 /// impl Fn(int) for Closure { ... }
3372 ///
3373 /// Now imagine our obligation is `Fn(usize) for Closure`. So far
3374 /// we have matched the self type `Closure`. At this point we'll
3375 /// compare the `int` to `usize` and generate an error.
3376 ///
3377 /// Note that this checking occurs *after* the impl has selected,
3378 /// because these output type parameters should not affect the
3379 /// selection of the impl. Therefore, if there is a mismatch, we
3380 /// report an error to the user.
3381 fn confirm_poly_trait_refs(
3382 &mut self,
3383 obligation_cause: ObligationCause<'tcx>,
3384 obligation_param_env: ty::ParamEnv<'tcx>,
3385 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
3386 expected_trait_ref: ty::PolyTraitRef<'tcx>,
3387 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3388 let obligation_trait_ref = obligation_trait_ref.clone();
3389 self.infcx
3390 .at(&obligation_cause, obligation_param_env)
3391 .sup(obligation_trait_ref, expected_trait_ref)
3392 .map(|InferOk { obligations, .. }| obligations)
3393 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
3394 }
3395
3396 fn confirm_builtin_unsize_candidate(
3397 &mut self,
3398 obligation: &TraitObligation<'tcx>,
3399 ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
3400 let tcx = self.tcx();
3401
3402 // assemble_candidates_for_unsizing should ensure there are no late bound
3403 // regions here. See the comment there for more details.
3404 let source = self.infcx
3405 .shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
3406 let target = obligation
3407 .predicate
3408 .skip_binder()
3409 .trait_ref
3410 .substs
3411 .type_at(1);
3412 let target = self.infcx.shallow_resolve(target);
3413
3414 debug!(
3415 "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
3416 source, target
3417 );
3418
3419 let mut nested = vec![];
3420 match (&source.sty, &target.sty) {
3421 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
3422 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
3423 // See assemble_candidates_for_unsizing for more info.
3424 let existential_predicates = data_a.map_bound(|data_a| {
3425 let iter =
3426 data_a.principal().map(|x| ty::ExistentialPredicate::Trait(x))
3427 .into_iter().chain(
3428 data_a
3429 .projection_bounds()
3430 .map(|x| ty::ExistentialPredicate::Projection(x)),
3431 )
3432 .chain(
3433 data_b
3434 .auto_traits()
3435 .map(ty::ExistentialPredicate::AutoTrait),
3436 );
3437 tcx.mk_existential_predicates(iter)
3438 });
3439 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
3440
3441 // Require that the traits involved in this upcast are **equal**;
3442 // only the **lifetime bound** is changed.
3443 //
3444 // FIXME: This condition is arguably too strong -- it
3445 // would suffice for the source trait to be a
3446 // *subtype* of the target trait. In particular
3447 // changing from something like `for<'a, 'b> Foo<'a,
3448 // 'b>` to `for<'a> Foo<'a, 'a>` should be
3449 // permitted. And, indeed, in the in commit
3450 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
3451 // condition was loosened. However, when the leak check was added
3452 // back, using subtype here actually guies the coercion code in
3453 // such a way that it accepts `old-lub-glb-object.rs`. This is probably
3454 // a good thing, but I've modified this to `.eq` because I want
3455 // to continue rejecting that test (as we have done for quite some time)
3456 // before we are firmly comfortable with what our behavior
3457 // should be there. -nikomatsakis
3458 let InferOk { obligations, .. } = self.infcx
3459 .at(&obligation.cause, obligation.param_env)
3460 .eq(target, source_trait) // FIXME -- see below
3461 .map_err(|_| Unimplemented)?;
3462 nested.extend(obligations);
3463
3464 // Register one obligation for 'a: 'b.
3465 let cause = ObligationCause::new(
3466 obligation.cause.span,
3467 obligation.cause.body_id,
3468 ObjectCastObligation(target),
3469 );
3470 let outlives = ty::OutlivesPredicate(r_a, r_b);
3471 nested.push(Obligation::with_depth(
3472 cause,
3473 obligation.recursion_depth + 1,
3474 obligation.param_env,
3475 ty::Binder::bind(outlives).to_predicate(),
3476 ));
3477 }
3478
3479 // T -> Trait.
3480 (_, &ty::Dynamic(ref data, r)) => {
3481 let mut object_dids = data.auto_traits()
3482 .chain(data.principal_def_id());
3483 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
3484 return Err(TraitNotObjectSafe(did));
3485 }
3486
3487 let cause = ObligationCause::new(
3488 obligation.cause.span,
3489 obligation.cause.body_id,
3490 ObjectCastObligation(target),
3491 );
3492
3493 let predicate_to_obligation = |predicate| {
3494 Obligation::with_depth(
3495 cause.clone(),
3496 obligation.recursion_depth + 1,
3497 obligation.param_env,
3498 predicate,
3499 )
3500 };
3501
3502 // Create obligations:
3503 // - Casting T to Trait
3504 // - For all the various builtin bounds attached to the object cast. (In other
3505 // words, if the object type is Foo+Send, this would create an obligation for the
3506 // Send check.)
3507 // - Projection predicates
3508 nested.extend(
3509 data.iter()
3510 .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
3511 );
3512
3513 // We can only make objects from sized types.
3514 let tr = ty::TraitRef {
3515 def_id: tcx.require_lang_item(lang_items::SizedTraitLangItem),
3516 substs: tcx.mk_substs_trait(source, &[]),
3517 };
3518 nested.push(predicate_to_obligation(tr.to_predicate()));
3519
3520 // If the type is `Foo+'a`, ensures that the type
3521 // being cast to `Foo+'a` outlives `'a`:
3522 let outlives = ty::OutlivesPredicate(source, r);
3523 nested.push(predicate_to_obligation(
3524 ty::Binder::dummy(outlives).to_predicate(),
3525 ));
3526 }
3527
3528 // [T; n] -> [T].
3529 (&ty::Array(a, _), &ty::Slice(b)) => {
3530 let InferOk { obligations, .. } = self.infcx
3531 .at(&obligation.cause, obligation.param_env)
3532 .eq(b, a)
3533 .map_err(|_| Unimplemented)?;
3534 nested.extend(obligations);
3535 }
3536
3537 // Struct<T> -> Struct<U>.
3538 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
3539 let fields = def.all_fields()
3540 .map(|f| tcx.type_of(f.did))
3541 .collect::<Vec<_>>();
3542
3543 // The last field of the structure has to exist and contain type parameters.
3544 let field = if let Some(&field) = fields.last() {
3545 field
3546 } else {
3547 return Err(Unimplemented);
3548 };
3549 let mut ty_params = GrowableBitSet::new_empty();
3550 let mut found = false;
3551 for ty in field.walk() {
3552 if let ty::Param(p) = ty.sty {
3553 ty_params.insert(p.index as usize);
3554 found = true;
3555 }
3556 }
3557 if !found {
3558 return Err(Unimplemented);
3559 }
3560
3561 // Replace type parameters used in unsizing with
3562 // Error and ensure they do not affect any other fields.
3563 // This could be checked after type collection for any struct
3564 // with a potentially unsized trailing field.
3565 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3566 if ty_params.contains(i) {
3567 tcx.types.err.into()
3568 } else {
3569 k
3570 }
3571 });
3572 let substs = tcx.mk_substs(params);
3573 for &ty in fields.split_last().unwrap().1 {
3574 if ty.subst(tcx, substs).references_error() {
3575 return Err(Unimplemented);
3576 }
3577 }
3578
3579 // Extract Field<T> and Field<U> from Struct<T> and Struct<U>.
3580 let inner_source = field.subst(tcx, substs_a);
3581 let inner_target = field.subst(tcx, substs_b);
3582
3583 // Check that the source struct with the target's
3584 // unsized parameters is equal to the target.
3585 let params = substs_a.iter().enumerate().map(|(i, &k)| {
3586 if ty_params.contains(i) {
3587 substs_b.type_at(i).into()
3588 } else {
3589 k
3590 }
3591 });
3592 let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
3593 let InferOk { obligations, .. } = self.infcx
3594 .at(&obligation.cause, obligation.param_env)
3595 .eq(target, new_struct)
3596 .map_err(|_| Unimplemented)?;
3597 nested.extend(obligations);
3598
3599 // Construct the nested Field<T>: Unsize<Field<U>> predicate.
3600 nested.push(tcx.predicate_for_trait_def(
3601 obligation.param_env,
3602 obligation.cause.clone(),
3603 obligation.predicate.def_id(),
3604 obligation.recursion_depth + 1,
3605 inner_source,
3606 &[inner_target.into()],
3607 ));
3608 }
3609
3610 // (.., T) -> (.., U).
3611 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
3612 assert_eq!(tys_a.len(), tys_b.len());
3613
3614 // The last field of the tuple has to exist.
3615 let (&a_last, a_mid) = if let Some(x) = tys_a.split_last() {
3616 x
3617 } else {
3618 return Err(Unimplemented);
3619 };
3620 let &b_last = tys_b.last().unwrap();
3621
3622 // Check that the source tuple with the target's
3623 // last element is equal to the target.
3624 let new_tuple = tcx.mk_tup(
3625 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
3626 );
3627 let InferOk { obligations, .. } = self.infcx
3628 .at(&obligation.cause, obligation.param_env)
3629 .eq(target, new_tuple)
3630 .map_err(|_| Unimplemented)?;
3631 nested.extend(obligations);
3632
3633 // Construct the nested T: Unsize<U> predicate.
3634 nested.push(tcx.predicate_for_trait_def(
3635 obligation.param_env,
3636 obligation.cause.clone(),
3637 obligation.predicate.def_id(),
3638 obligation.recursion_depth + 1,
3639 a_last.expect_ty(),
3640 &[b_last.into()],
3641 ));
3642 }
3643
3644 _ => bug!(),
3645 };
3646
3647 Ok(VtableBuiltinData { nested })
3648 }
3649
3650 ///////////////////////////////////////////////////////////////////////////
3651 // Matching
3652 //
3653 // Matching is a common path used for both evaluation and
3654 // confirmation. It basically unifies types that appear in impls
3655 // and traits. This does affect the surrounding environment;
3656 // therefore, when used during evaluation, match routines must be
3657 // run inside of a `probe()` so that their side-effects are
3658 // contained.
3659
3660 fn rematch_impl(
3661 &mut self,
3662 impl_def_id: DefId,
3663 obligation: &TraitObligation<'tcx>,
3664 snapshot: &CombinedSnapshot<'_, 'tcx>,
3665 ) -> Normalized<'tcx, SubstsRef<'tcx>> {
3666 match self.match_impl(impl_def_id, obligation, snapshot) {
3667 Ok(substs) => substs,
3668 Err(()) => {
3669 bug!(
3670 "Impl {:?} was matchable against {:?} but now is not",
3671 impl_def_id,
3672 obligation
3673 );
3674 }
3675 }
3676 }
3677
3678 fn match_impl(
3679 &mut self,
3680 impl_def_id: DefId,
3681 obligation: &TraitObligation<'tcx>,
3682 snapshot: &CombinedSnapshot<'_, 'tcx>,
3683 ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
3684 let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
3685
3686 // Before we create the substitutions and everything, first
3687 // consider a "quick reject". This avoids creating more types
3688 // and so forth that we need to.
3689 if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
3690 return Err(());
3691 }
3692
3693 let (skol_obligation, placeholder_map) = self.infcx()
3694 .replace_bound_vars_with_placeholders(&obligation.predicate);
3695 let skol_obligation_trait_ref = skol_obligation.trait_ref;
3696
3697 let impl_substs = self.infcx
3698 .fresh_substs_for_item(obligation.cause.span, impl_def_id);
3699
3700 let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
3701
3702 let Normalized {
3703 value: impl_trait_ref,
3704 obligations: mut nested_obligations,
3705 } = project::normalize_with_depth(
3706 self,
3707 obligation.param_env,
3708 obligation.cause.clone(),
3709 obligation.recursion_depth + 1,
3710 &impl_trait_ref,
3711 );
3712
3713 debug!(
3714 "match_impl(impl_def_id={:?}, obligation={:?}, \
3715 impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
3716 impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
3717 );
3718
3719 let InferOk { obligations, .. } = self.infcx
3720 .at(&obligation.cause, obligation.param_env)
3721 .eq(skol_obligation_trait_ref, impl_trait_ref)
3722 .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
3723 nested_obligations.extend(obligations);
3724
3725 if let Err(e) = self.infcx.leak_check(false, &placeholder_map, snapshot) {
3726 debug!("match_impl: failed leak check due to `{}`", e);
3727 return Err(());
3728 }
3729
3730 debug!("match_impl: success impl_substs={:?}", impl_substs);
3731 Ok(Normalized {
3732 value: impl_substs,
3733 obligations: nested_obligations,
3734 })
3735 }
3736
3737 fn fast_reject_trait_refs(
3738 &mut self,
3739 obligation: &TraitObligation<'_>,
3740 impl_trait_ref: &ty::TraitRef<'_>,
3741 ) -> bool {
3742 // We can avoid creating type variables and doing the full
3743 // substitution if we find that any of the input types, when
3744 // simplified, do not match.
3745
3746 obligation
3747 .predicate
3748 .skip_binder()
3749 .input_types()
3750 .zip(impl_trait_ref.input_types())
3751 .any(|(obligation_ty, impl_ty)| {
3752 let simplified_obligation_ty =
3753 fast_reject::simplify_type(self.tcx(), obligation_ty, true);
3754 let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
3755
3756 simplified_obligation_ty.is_some()
3757 && simplified_impl_ty.is_some()
3758 && simplified_obligation_ty != simplified_impl_ty
3759 })
3760 }
3761
3762 /// Normalize `where_clause_trait_ref` and try to match it against
3763 /// `obligation`. If successful, return any predicates that
3764 /// result from the normalization. Normalization is necessary
3765 /// because where-clauses are stored in the parameter environment
3766 /// unnormalized.
3767 fn match_where_clause_trait_ref(
3768 &mut self,
3769 obligation: &TraitObligation<'tcx>,
3770 where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
3771 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3772 self.match_poly_trait_ref(obligation, where_clause_trait_ref)
3773 }
3774
3775 /// Returns `Ok` if `poly_trait_ref` being true implies that the
3776 /// obligation is satisfied.
3777 fn match_poly_trait_ref(
3778 &mut self,
3779 obligation: &TraitObligation<'tcx>,
3780 poly_trait_ref: ty::PolyTraitRef<'tcx>,
3781 ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
3782 debug!(
3783 "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
3784 obligation, poly_trait_ref
3785 );
3786
3787 self.infcx
3788 .at(&obligation.cause, obligation.param_env)
3789 .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
3790 .map(|InferOk { obligations, .. }| obligations)
3791 .map_err(|_| ())
3792 }
3793
3794 ///////////////////////////////////////////////////////////////////////////
3795 // Miscellany
3796
3797 fn match_fresh_trait_refs(
3798 &self,
3799 previous: &ty::PolyTraitRef<'tcx>,
3800 current: &ty::PolyTraitRef<'tcx>,
3801 ) -> bool {
3802 let mut matcher = ty::_match::Match::new(self.tcx());
3803 matcher.relate(previous, current).is_ok()
3804 }
3805
3806 fn push_stack<'o>(
3807 &mut self,
3808 previous_stack: TraitObligationStackList<'o, 'tcx>,
3809 obligation: &'o TraitObligation<'tcx>,
3810 ) -> TraitObligationStack<'o, 'tcx> {
3811 let fresh_trait_ref = obligation
3812 .predicate
3813 .to_poly_trait_ref()
3814 .fold_with(&mut self.freshener);
3815
3816 let dfn = previous_stack.cache.next_dfn();
3817 let depth = previous_stack.depth() + 1;
3818 TraitObligationStack {
3819 obligation,
3820 fresh_trait_ref,
3821 reached_depth: Cell::new(depth),
3822 previous: previous_stack,
3823 dfn,
3824 depth,
3825 }
3826 }
3827
3828 fn closure_trait_ref_unnormalized(
3829 &mut self,
3830 obligation: &TraitObligation<'tcx>,
3831 closure_def_id: DefId,
3832 substs: ty::ClosureSubsts<'tcx>,
3833 ) -> ty::PolyTraitRef<'tcx> {
3834 debug!(
3835 "closure_trait_ref_unnormalized(obligation={:?}, closure_def_id={:?}, substs={:?})",
3836 obligation, closure_def_id, substs,
3837 );
3838 let closure_type = self.infcx.closure_sig(closure_def_id, substs);
3839
3840 debug!(
3841 "closure_trait_ref_unnormalized: closure_type = {:?}",
3842 closure_type
3843 );
3844
3845 // (1) Feels icky to skip the binder here, but OTOH we know
3846 // that the self-type is an unboxed closure type and hence is
3847 // in fact unparameterized (or at least does not reference any
3848 // regions bound in the obligation). Still probably some
3849 // refactoring could make this nicer.
3850 self.tcx()
3851 .closure_trait_ref_and_return_type(
3852 obligation.predicate.def_id(),
3853 obligation.predicate.skip_binder().self_ty(), // (1)
3854 closure_type,
3855 util::TupleArgumentsFlag::No,
3856 )
3857 .map_bound(|(trait_ref, _)| trait_ref)
3858 }
3859
3860 fn generator_trait_ref_unnormalized(
3861 &mut self,
3862 obligation: &TraitObligation<'tcx>,
3863 closure_def_id: DefId,
3864 substs: ty::GeneratorSubsts<'tcx>,
3865 ) -> ty::PolyTraitRef<'tcx> {
3866 let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
3867
3868 // (1) Feels icky to skip the binder here, but OTOH we know
3869 // that the self-type is an generator type and hence is
3870 // in fact unparameterized (or at least does not reference any
3871 // regions bound in the obligation). Still probably some
3872 // refactoring could make this nicer.
3873
3874 self.tcx()
3875 .generator_trait_ref_and_outputs(
3876 obligation.predicate.def_id(),
3877 obligation.predicate.skip_binder().self_ty(), // (1)
3878 gen_sig,
3879 )
3880 .map_bound(|(trait_ref, ..)| trait_ref)
3881 }
3882
3883 /// Returns the obligations that are implied by instantiating an
3884 /// impl or trait. The obligations are substituted and fully
3885 /// normalized. This is used when confirming an impl or default
3886 /// impl.
3887 fn impl_or_trait_obligations(
3888 &mut self,
3889 cause: ObligationCause<'tcx>,
3890 recursion_depth: usize,
3891 param_env: ty::ParamEnv<'tcx>,
3892 def_id: DefId, // of impl or trait
3893 substs: SubstsRef<'tcx>, // for impl or trait
3894 ) -> Vec<PredicateObligation<'tcx>> {
3895 debug!("impl_or_trait_obligations(def_id={:?})", def_id);
3896 let tcx = self.tcx();
3897
3898 // To allow for one-pass evaluation of the nested obligation,
3899 // each predicate must be preceded by the obligations required
3900 // to normalize it.
3901 // for example, if we have:
3902 // impl<U: Iterator, V: Iterator<Item=U>> Foo for V where U::Item: Copy
3903 // the impl will have the following predicates:
3904 // <V as Iterator>::Item = U,
3905 // U: Iterator, U: Sized,
3906 // V: Iterator, V: Sized,
3907 // <U as Iterator>::Item: Copy
3908 // When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
3909 // obligation will normalize to `<$0 as Iterator>::Item = $1` and
3910 // `$1: Copy`, so we must ensure the obligations are emitted in
3911 // that order.
3912 let predicates = tcx.predicates_of(def_id);
3913 assert_eq!(predicates.parent, None);
3914 let mut predicates: Vec<_> = predicates
3915 .predicates
3916 .iter()
3917 .flat_map(|(predicate, _)| {
3918 let predicate = normalize_with_depth(
3919 self,
3920 param_env,
3921 cause.clone(),
3922 recursion_depth,
3923 &predicate.subst(tcx, substs),
3924 );
3925 predicate.obligations.into_iter().chain(Some(Obligation {
3926 cause: cause.clone(),
3927 recursion_depth,
3928 param_env,
3929 predicate: predicate.value,
3930 }))
3931 })
3932 .collect();
3933
3934 // We are performing deduplication here to avoid exponential blowups
3935 // (#38528) from happening, but the real cause of the duplication is
3936 // unknown. What we know is that the deduplication avoids exponential
3937 // amount of predicates being propagated when processing deeply nested
3938 // types.
3939 //
3940 // This code is hot enough that it's worth avoiding the allocation
3941 // required for the FxHashSet when possible. Special-casing lengths 0,
3942 // 1 and 2 covers roughly 75--80% of the cases.
3943 if predicates.len() <= 1 {
3944 // No possibility of duplicates.
3945 } else if predicates.len() == 2 {
3946 // Only two elements. Drop the second if they are equal.
3947 if predicates[0] == predicates[1] {
3948 predicates.truncate(1);
3949 }
3950 } else {
3951 // Three or more elements. Use a general deduplication process.
3952 let mut seen = FxHashSet::default();
3953 predicates.retain(|i| seen.insert(i.clone()));
3954 }
3955
3956 predicates
3957 }
3958 }
3959
3960 impl<'tcx> TraitObligation<'tcx> {
3961 #[allow(unused_comparisons)]
3962 pub fn derived_cause(
3963 &self,
3964 variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
3965 ) -> ObligationCause<'tcx> {
3966 /*!
3967 * Creates a cause for obligations that are derived from
3968 * `obligation` by a recursive search (e.g., for a builtin
3969 * bound, or eventually a `auto trait Foo`). If `obligation`
3970 * is itself a derived obligation, this is just a clone, but
3971 * otherwise we create a "derived obligation" cause so as to
3972 * keep track of the original root obligation for error
3973 * reporting.
3974 */
3975
3976 let obligation = self;
3977
3978 // NOTE(flaper87): As of now, it keeps track of the whole error
3979 // chain. Ideally, we should have a way to configure this either
3980 // by using -Z verbose or just a CLI argument.
3981 if obligation.recursion_depth >= 0 {
3982 let derived_cause = DerivedObligationCause {
3983 parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
3984 parent_code: Rc::new(obligation.cause.code.clone()),
3985 };
3986 let derived_code = variant(derived_cause);
3987 ObligationCause::new(
3988 obligation.cause.span,
3989 obligation.cause.body_id,
3990 derived_code,
3991 )
3992 } else {
3993 obligation.cause.clone()
3994 }
3995 }
3996 }
3997
3998 impl<'tcx> SelectionCache<'tcx> {
3999 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4000 pub fn clear(&self) {
4001 *self.hashmap.borrow_mut() = Default::default();
4002 }
4003 }
4004
4005 impl<'tcx> EvaluationCache<'tcx> {
4006 /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
4007 pub fn clear(&self) {
4008 *self.hashmap.borrow_mut() = Default::default();
4009 }
4010 }
4011
4012 impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
4013 fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4014 TraitObligationStackList::with(self)
4015 }
4016
4017 fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
4018 self.previous.cache
4019 }
4020
4021 fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
4022 self.list()
4023 }
4024
4025 /// Indicates that attempting to evaluate this stack entry
4026 /// required accessing something from the stack at depth `reached_depth`.
4027 fn update_reached_depth(&self, reached_depth: usize) {
4028 assert!(
4029 self.depth > reached_depth,
4030 "invoked `update_reached_depth` with something under this stack: \
4031 self.depth={} reached_depth={}",
4032 self.depth,
4033 reached_depth,
4034 );
4035 debug!("update_reached_depth(reached_depth={})", reached_depth);
4036 let mut p = self;
4037 while reached_depth < p.depth {
4038 debug!("update_reached_depth: marking {:?} as cycle participant", p.fresh_trait_ref);
4039 p.reached_depth.set(p.reached_depth.get().min(reached_depth));
4040 p = p.previous.head.unwrap();
4041 }
4042 }
4043 }
4044
4045 /// The "provisional evaluation cache" is used to store intermediate cache results
4046 /// when solving auto traits. Auto traits are unusual in that they can support
4047 /// cycles. So, for example, a "proof tree" like this would be ok:
4048 ///
4049 /// - `Foo<T>: Send` :-
4050 /// - `Bar<T>: Send` :-
4051 /// - `Foo<T>: Send` -- cycle, but ok
4052 /// - `Baz<T>: Send`
4053 ///
4054 /// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
4055 /// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
4056 /// For non-auto traits, this cycle would be an error, but for auto traits (because
4057 /// they are coinductive) it is considered ok.
4058 ///
4059 /// However, there is a complication: at the point where we have
4060 /// "proven" `Bar<T>: Send`, we have in fact only proven it
4061 /// *provisionally*. In particular, we proved that `Bar<T>: Send`
4062 /// *under the assumption* that `Foo<T>: Send`. But what if we later
4063 /// find out this assumption is wrong? Specifically, we could
4064 /// encounter some kind of error proving `Baz<T>: Send`. In that case,
4065 /// `Bar<T>: Send` didn't turn out to be true.
4066 ///
4067 /// In Issue #60010, we found a bug in rustc where it would cache
4068 /// these intermediate results. This was fixed in #60444 by disabling
4069 /// *all* caching for things involved in a cycle -- in our example,
4070 /// that would mean we don't cache that `Bar<T>: Send`. But this led
4071 /// to large slowdowns.
4072 ///
4073 /// Specifically, imagine this scenario, where proving `Baz<T>: Send`
4074 /// first requires proving `Bar<T>: Send` (which is true:
4075 ///
4076 /// - `Foo<T>: Send` :-
4077 /// - `Bar<T>: Send` :-
4078 /// - `Foo<T>: Send` -- cycle, but ok
4079 /// - `Baz<T>: Send`
4080 /// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
4081 /// - `*const T: Send` -- but what if we later encounter an error?
4082 ///
4083 /// The *provisional evaluation cache* resolves this issue. It stores
4084 /// cache results that we've proven but which were involved in a cycle
4085 /// in some way. We track the minimal stack depth (i.e., the
4086 /// farthest from the top of the stack) that we are dependent on.
4087 /// The idea is that the cache results within are all valid -- so long as
4088 /// none of the nodes in between the current node and the node at that minimum
4089 /// depth result in an error (in which case the cached results are just thrown away).
4090 ///
4091 /// During evaluation, we consult this provisional cache and rely on
4092 /// it. Accessing a cached value is considered equivalent to accessing
4093 /// a result at `reached_depth`, so it marks the *current* solution as
4094 /// provisional as well. If an error is encountered, we toss out any
4095 /// provisional results added from the subtree that encountered the
4096 /// error. When we pop the node at `reached_depth` from the stack, we
4097 /// can commit all the things that remain in the provisional cache.
4098 struct ProvisionalEvaluationCache<'tcx> {
4099 /// next "depth first number" to issue -- just a counter
4100 dfn: Cell<usize>,
4101
4102 /// Stores the "coldest" depth (bottom of stack) reached by any of
4103 /// the evaluation entries. The idea here is that all things in the provisional
4104 /// cache are always dependent on *something* that is colder in the stack:
4105 /// therefore, if we add a new entry that is dependent on something *colder still*,
4106 /// we have to modify the depth for all entries at once.
4107 ///
4108 /// Example:
4109 ///
4110 /// Imagine we have a stack `A B C D E` (with `E` being the top of
4111 /// the stack). We cache something with depth 2, which means that
4112 /// it was dependent on C. Then we pop E but go on and process a
4113 /// new node F: A B C D F. Now F adds something to the cache with
4114 /// depth 1, meaning it is dependent on B. Our original cache
4115 /// entry is also dependent on B, because there is a path from E
4116 /// to C and then from C to F and from F to B.
4117 reached_depth: Cell<usize>,
4118
4119 /// Map from cache key to the provisionally evaluated thing.
4120 /// The cache entries contain the result but also the DFN in which they
4121 /// were added. The DFN is used to clear out values on failure.
4122 ///
4123 /// Imagine we have a stack like:
4124 ///
4125 /// - `A B C` and we add a cache for the result of C (DFN 2)
4126 /// - Then we have a stack `A B D` where `D` has DFN 3
4127 /// - We try to solve D by evaluating E: `A B D E` (DFN 4)
4128 /// - `E` generates various cache entries which have cyclic dependices on `B`
4129 /// - `A B D E F` and so forth
4130 /// - the DFN of `F` for example would be 5
4131 /// - then we determine that `E` is in error -- we will then clear
4132 /// all cache values whose DFN is >= 4 -- in this case, that
4133 /// means the cached value for `F`.
4134 map: RefCell<FxHashMap<ty::PolyTraitRef<'tcx>, ProvisionalEvaluation>>,
4135 }
4136
4137 /// A cache value for the provisional cache: contains the depth-first
4138 /// number (DFN) and result.
4139 #[derive(Copy, Clone, Debug)]
4140 struct ProvisionalEvaluation {
4141 from_dfn: usize,
4142 result: EvaluationResult,
4143 }
4144
4145 impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
4146 fn default() -> Self {
4147 Self {
4148 dfn: Cell::new(0),
4149 reached_depth: Cell::new(std::usize::MAX),
4150 map: Default::default(),
4151 }
4152 }
4153 }
4154
4155 impl<'tcx> ProvisionalEvaluationCache<'tcx> {
4156 /// Get the next DFN in sequence (basically a counter).
4157 fn next_dfn(&self) -> usize {
4158 let result = self.dfn.get();
4159 self.dfn.set(result + 1);
4160 result
4161 }
4162
4163 /// Check the provisional cache for any result for
4164 /// `fresh_trait_ref`. If there is a hit, then you must consider
4165 /// it an access to the stack slots at depth
4166 /// `self.current_reached_depth()` and above.
4167 fn get_provisional(&self, fresh_trait_ref: ty::PolyTraitRef<'tcx>) -> Option<EvaluationResult> {
4168 debug!(
4169 "get_provisional(fresh_trait_ref={:?}) = {:#?} with reached-depth {}",
4170 fresh_trait_ref,
4171 self.map.borrow().get(&fresh_trait_ref),
4172 self.reached_depth.get(),
4173 );
4174 Some(self.map.borrow().get(&fresh_trait_ref)?.result)
4175 }
4176
4177 /// Current value of the `reached_depth` counter -- all the
4178 /// provisional cache entries are dependent on the item at this
4179 /// depth.
4180 fn current_reached_depth(&self) -> usize {
4181 self.reached_depth.get()
4182 }
4183
4184 /// Insert a provisional result into the cache. The result came
4185 /// from the node with the given DFN. It accessed a minimum depth
4186 /// of `reached_depth` to compute. It evaluated `fresh_trait_ref`
4187 /// and resulted in `result`.
4188 fn insert_provisional(
4189 &self,
4190 from_dfn: usize,
4191 reached_depth: usize,
4192 fresh_trait_ref: ty::PolyTraitRef<'tcx>,
4193 result: EvaluationResult,
4194 ) {
4195 debug!(
4196 "insert_provisional(from_dfn={}, reached_depth={}, fresh_trait_ref={:?}, result={:?})",
4197 from_dfn,
4198 reached_depth,
4199 fresh_trait_ref,
4200 result,
4201 );
4202 let r_d = self.reached_depth.get();
4203 self.reached_depth.set(r_d.min(reached_depth));
4204
4205 debug!("insert_provisional: reached_depth={:?}", self.reached_depth.get());
4206
4207 self.map.borrow_mut().insert(fresh_trait_ref, ProvisionalEvaluation { from_dfn, result });
4208 }
4209
4210 /// Invoked when the node with dfn `dfn` does not get a successful
4211 /// result. This will clear out any provisional cache entries
4212 /// that were added since `dfn` was created. This is because the
4213 /// provisional entries are things which must assume that the
4214 /// things on the stack at the time of their creation succeeded --
4215 /// since the failing node is presently at the top of the stack,
4216 /// these provisional entries must either depend on it or some
4217 /// ancestor of it.
4218 fn on_failure(&self, dfn: usize) {
4219 debug!(
4220 "on_failure(dfn={:?})",
4221 dfn,
4222 );
4223 self.map.borrow_mut().retain(|key, eval| {
4224 if !eval.from_dfn >= dfn {
4225 debug!("on_failure: removing {:?}", key);
4226 false
4227 } else {
4228 true
4229 }
4230 });
4231 }
4232
4233 /// Invoked when the node at depth `depth` completed without
4234 /// depending on anything higher in the stack (if that completion
4235 /// was a failure, then `on_failure` should have been invoked
4236 /// already). The callback `op` will be invoked for each
4237 /// provisional entry that we can now confirm.
4238 fn on_completion(
4239 &self,
4240 depth: usize,
4241 mut op: impl FnMut(ty::PolyTraitRef<'tcx>, EvaluationResult),
4242 ) {
4243 debug!(
4244 "on_completion(depth={}, reached_depth={})",
4245 depth,
4246 self.reached_depth.get(),
4247 );
4248
4249 if self.reached_depth.get() < depth {
4250 debug!("on_completion: did not yet reach depth to complete");
4251 return;
4252 }
4253
4254 for (fresh_trait_ref, eval) in self.map.borrow_mut().drain() {
4255 debug!(
4256 "on_completion: fresh_trait_ref={:?} eval={:?}",
4257 fresh_trait_ref,
4258 eval,
4259 );
4260
4261 op(fresh_trait_ref, eval.result);
4262 }
4263
4264 self.reached_depth.set(std::usize::MAX);
4265 }
4266 }
4267
4268 #[derive(Copy, Clone)]
4269 struct TraitObligationStackList<'o, 'tcx> {
4270 cache: &'o ProvisionalEvaluationCache<'tcx>,
4271 head: Option<&'o TraitObligationStack<'o, 'tcx>>,
4272 }
4273
4274 impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
4275 fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4276 TraitObligationStackList { cache, head: None }
4277 }
4278
4279 fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
4280 TraitObligationStackList { cache: r.cache(), head: Some(r) }
4281 }
4282
4283 fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4284 self.head
4285 }
4286
4287 fn depth(&self) -> usize {
4288 if let Some(head) = self.head {
4289 head.depth
4290 } else {
4291 0
4292 }
4293 }
4294 }
4295
4296 impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
4297 type Item = &'o TraitObligationStack<'o, 'tcx>;
4298
4299 fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
4300 match self.head {
4301 Some(o) => {
4302 *self = o.previous;
4303 Some(o)
4304 }
4305 None => None,
4306 }
4307 }
4308 }
4309
4310 impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
4311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4312 write!(f, "TraitObligationStack({:?})", self.obligation)
4313 }
4314 }
4315
4316 #[derive(Clone, Eq, PartialEq)]
4317 pub struct WithDepNode<T> {
4318 dep_node: DepNodeIndex,
4319 cached_value: T,
4320 }
4321
4322 impl<T: Clone> WithDepNode<T> {
4323 pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
4324 WithDepNode {
4325 dep_node,
4326 cached_value,
4327 }
4328 }
4329
4330 pub fn get(&self, tcx: TyCtxt<'_>) -> T {
4331 tcx.dep_graph.read_index(self.dep_node);
4332 self.cached_value.clone()
4333 }
4334 }