]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
b0bfb4ad173719c791a3f228f87997aac1c11a50
[rust.git] / compiler / rustc_trait_selection / src / traits / select / candidate_assembly.rs
1 //! Candidate assembly.
2 //!
3 //! The selection process begins by examining all in-scope impls,
4 //! caller obligations, and so forth and assembling a list of
5 //! candidates. See the [rustc dev guide] for more details.
6 //!
7 //! [rustc dev guide]:https://rustc-dev-guide.rust-lang.org/traits/resolution.html#candidate-assembly
8 use rustc_hir as hir;
9 use rustc_infer::traits::{Obligation, SelectionError, TraitObligation};
10 use rustc_middle::ty::print::with_no_trimmed_paths;
11 use rustc_middle::ty::{self, TypeFoldable};
12 use rustc_target::spec::abi::Abi;
13
14 use crate::traits::coherence::Conflict;
15 use crate::traits::{util, SelectionResult};
16 use crate::traits::{Overflow, Unimplemented};
17
18 use super::BuiltinImplConditions;
19 use super::IntercrateAmbiguityCause;
20 use super::OverflowError;
21 use super::SelectionCandidate::{self, *};
22 use super::{EvaluatedCandidate, SelectionCandidateSet, SelectionContext, TraitObligationStack};
23
24 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
25     #[instrument(level = "debug", skip(self))]
26     pub(super) fn candidate_from_obligation<'o>(
27         &mut self,
28         stack: &TraitObligationStack<'o, 'tcx>,
29     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
30         // Watch out for overflow. This intentionally bypasses (and does
31         // not update) the cache.
32         self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
33
34         // Check the cache. Note that we freshen the trait-ref
35         // separately rather than using `stack.fresh_trait_ref` --
36         // this is because we want the unbound variables to be
37         // replaced with fresh types starting from index 0.
38         let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
39         debug!(?cache_fresh_trait_pred);
40         debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
41
42         if let Some(c) =
43             self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
44         {
45             debug!(candidate = ?c, "CACHE HIT");
46             return c;
47         }
48
49         // If no match, compute result and insert into cache.
50         //
51         // FIXME(nikomatsakis) -- this cache is not taking into
52         // account cycles that may have occurred in forming the
53         // candidate. I don't know of any specific problems that
54         // result but it seems awfully suspicious.
55         let (candidate, dep_node) =
56             self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
57
58         debug!(?candidate, "CACHE MISS");
59         self.insert_candidate_cache(
60             stack.obligation.param_env,
61             cache_fresh_trait_pred,
62             dep_node,
63             candidate.clone(),
64         );
65         candidate
66     }
67
68     fn candidate_from_obligation_no_cache<'o>(
69         &mut self,
70         stack: &TraitObligationStack<'o, 'tcx>,
71     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
72         if let Some(conflict) = self.is_knowable(stack) {
73             debug!("coherence stage: not knowable");
74             if self.intercrate_ambiguity_causes.is_some() {
75                 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
76                 // Heuristics: show the diagnostics when there are no candidates in crate.
77                 if let Ok(candidate_set) = self.assemble_candidates(stack) {
78                     let mut no_candidates_apply = true;
79
80                     for c in candidate_set.vec.iter() {
81                         if self.evaluate_candidate(stack, &c)?.may_apply() {
82                             no_candidates_apply = false;
83                             break;
84                         }
85                     }
86
87                     if !candidate_set.ambiguous && no_candidates_apply {
88                         let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
89                         let self_ty = trait_ref.self_ty();
90                         let (trait_desc, self_desc) = with_no_trimmed_paths(|| {
91                             let trait_desc = trait_ref.print_only_trait_path().to_string();
92                             let self_desc = if self_ty.has_concrete_skeleton() {
93                                 Some(self_ty.to_string())
94                             } else {
95                                 None
96                             };
97                             (trait_desc, self_desc)
98                         });
99                         let cause = if let Conflict::Upstream = conflict {
100                             IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
101                         } else {
102                             IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
103                         };
104                         debug!(?cause, "evaluate_stack: pushing cause");
105                         self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
106                     }
107                 }
108             }
109             return Ok(None);
110         }
111
112         let candidate_set = self.assemble_candidates(stack)?;
113
114         if candidate_set.ambiguous {
115             debug!("candidate set contains ambig");
116             return Ok(None);
117         }
118
119         let mut candidates = candidate_set.vec;
120
121         debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
122
123         // At this point, we know that each of the entries in the
124         // candidate set is *individually* applicable. Now we have to
125         // figure out if they contain mutual incompatibilities. This
126         // frequently arises if we have an unconstrained input type --
127         // for example, we are looking for `$0: Eq` where `$0` is some
128         // unconstrained type variable. In that case, we'll get a
129         // candidate which assumes $0 == int, one that assumes `$0 ==
130         // usize`, etc. This spells an ambiguity.
131
132         // If there is more than one candidate, first winnow them down
133         // by considering extra conditions (nested obligations and so
134         // forth). We don't winnow if there is exactly one
135         // candidate. This is a relatively minor distinction but it
136         // can lead to better inference and error-reporting. An
137         // example would be if there was an impl:
138         //
139         //     impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
140         //
141         // and we were to see some code `foo.push_clone()` where `boo`
142         // is a `Vec<Bar>` and `Bar` does not implement `Clone`.  If
143         // we were to winnow, we'd wind up with zero candidates.
144         // Instead, we select the right impl now but report "`Bar` does
145         // not implement `Clone`".
146         if candidates.len() == 1 {
147             return self.filter_negative_and_reservation_impls(candidates.pop().unwrap());
148         }
149
150         // Winnow, but record the exact outcome of evaluation, which
151         // is needed for specialization. Propagate overflow if it occurs.
152         let mut candidates = candidates
153             .into_iter()
154             .map(|c| match self.evaluate_candidate(stack, &c) {
155                 Ok(eval) if eval.may_apply() => {
156                     Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
157                 }
158                 Ok(_) => Ok(None),
159                 Err(OverflowError) => Err(Overflow),
160             })
161             .flat_map(Result::transpose)
162             .collect::<Result<Vec<_>, _>>()?;
163
164         debug!(?stack, ?candidates, "winnowed to {} candidates", candidates.len());
165
166         let needs_infer = stack.obligation.predicate.has_infer_types_or_consts();
167
168         // If there are STILL multiple candidates, we can further
169         // reduce the list by dropping duplicates -- including
170         // resolving specializations.
171         if candidates.len() > 1 {
172             let mut i = 0;
173             while i < candidates.len() {
174                 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
175                     self.candidate_should_be_dropped_in_favor_of(
176                         &candidates[i],
177                         &candidates[j],
178                         needs_infer,
179                     )
180                 });
181                 if is_dup {
182                     debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
183                     candidates.swap_remove(i);
184                 } else {
185                     debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
186                     i += 1;
187
188                     // If there are *STILL* multiple candidates, give up
189                     // and report ambiguity.
190                     if i > 1 {
191                         debug!("multiple matches, ambig");
192                         return Ok(None);
193                     }
194                 }
195             }
196         }
197
198         // If there are *NO* candidates, then there are no impls --
199         // that we know of, anyway. Note that in the case where there
200         // are unbound type variables within the obligation, it might
201         // be the case that you could still satisfy the obligation
202         // from another crate by instantiating the type variables with
203         // a type from another crate that does have an impl. This case
204         // is checked for in `evaluate_stack` (and hence users
205         // who might care about this case, like coherence, should use
206         // that function).
207         if candidates.is_empty() {
208             // If there's an error type, 'downgrade' our result from
209             // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
210             // emitting additional spurious errors, since we're guaranteed
211             // to have emitted at least one.
212             if stack.obligation.references_error() {
213                 debug!("no results for error type, treating as ambiguous");
214                 return Ok(None);
215             }
216             return Err(Unimplemented);
217         }
218
219         // Just one candidate left.
220         self.filter_negative_and_reservation_impls(candidates.pop().unwrap().candidate)
221     }
222
223     pub(super) fn assemble_candidates<'o>(
224         &mut self,
225         stack: &TraitObligationStack<'o, 'tcx>,
226     ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
227         let TraitObligationStack { obligation, .. } = *stack;
228         let obligation = &Obligation {
229             param_env: obligation.param_env,
230             cause: obligation.cause.clone(),
231             recursion_depth: obligation.recursion_depth,
232             predicate: self.infcx().resolve_vars_if_possible(&obligation.predicate),
233         };
234
235         if obligation.predicate.skip_binder().self_ty().is_ty_var() {
236             // Self is a type variable (e.g., `_: AsRef<str>`).
237             //
238             // This is somewhat problematic, as the current scheme can't really
239             // handle it turning to be a projection. This does end up as truly
240             // ambiguous in most cases anyway.
241             //
242             // Take the fast path out - this also improves
243             // performance by preventing assemble_candidates_from_impls from
244             // matching every impl for this trait.
245             return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
246         }
247
248         let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
249
250         self.assemble_candidates_for_trait_alias(obligation, &mut candidates)?;
251
252         // Other bounds. Consider both in-scope bounds from fn decl
253         // and applicable impls. There is a certain set of precedence rules here.
254         let def_id = obligation.predicate.def_id();
255         let lang_items = self.tcx().lang_items();
256
257         if lang_items.copy_trait() == Some(def_id) {
258             debug!(obligation_self_ty = ?obligation.predicate.skip_binder().self_ty());
259
260             // User-defined copy impls are permitted, but only for
261             // structs and enums.
262             self.assemble_candidates_from_impls(obligation, &mut candidates)?;
263
264             // For other types, we'll use the builtin rules.
265             let copy_conditions = self.copy_clone_conditions(obligation);
266             self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates)?;
267         } else if lang_items.discriminant_kind_trait() == Some(def_id) {
268             // `DiscriminantKind` is automatically implemented for every type.
269             candidates.vec.push(DiscriminantKindCandidate);
270         } else if lang_items.sized_trait() == Some(def_id) {
271             // Sized is never implementable by end-users, it is
272             // always automatically computed.
273             let sized_conditions = self.sized_conditions(obligation);
274             self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
275         } else if lang_items.unsize_trait() == Some(def_id) {
276             self.assemble_candidates_for_unsizing(obligation, &mut candidates);
277         } else {
278             if lang_items.clone_trait() == Some(def_id) {
279                 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
280                 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
281                 // types have builtin support for `Clone`.
282                 let clone_conditions = self.copy_clone_conditions(obligation);
283                 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates)?;
284             }
285
286             self.assemble_generator_candidates(obligation, &mut candidates)?;
287             self.assemble_closure_candidates(obligation, &mut candidates)?;
288             self.assemble_fn_pointer_candidates(obligation, &mut candidates)?;
289             self.assemble_candidates_from_impls(obligation, &mut candidates)?;
290             self.assemble_candidates_from_object_ty(obligation, &mut candidates);
291         }
292
293         self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
294         self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
295         // Auto implementations have lower priority, so we only
296         // consider triggering a default if there is no other impl that can apply.
297         if candidates.vec.is_empty() {
298             self.assemble_candidates_from_auto_impls(obligation, &mut candidates)?;
299         }
300         debug!("candidate list size: {}", candidates.vec.len());
301         Ok(candidates)
302     }
303
304     fn assemble_candidates_from_projected_tys(
305         &mut self,
306         obligation: &TraitObligation<'tcx>,
307         candidates: &mut SelectionCandidateSet<'tcx>,
308     ) {
309         debug!(?obligation, "assemble_candidates_from_projected_tys");
310
311         // Before we go into the whole placeholder thing, just
312         // quickly check if the self-type is a projection at all.
313         match obligation.predicate.skip_binder().trait_ref.self_ty().kind() {
314             ty::Projection(_) | ty::Opaque(..) => {}
315             ty::Infer(ty::TyVar(_)) => {
316                 span_bug!(
317                     obligation.cause.span,
318                     "Self=_ should have been handled by assemble_candidates"
319                 );
320             }
321             _ => return,
322         }
323
324         let result = self
325             .infcx
326             .probe(|_| self.match_projection_obligation_against_definition_bounds(obligation));
327
328         for predicate_index in result {
329             candidates.vec.push(ProjectionCandidate(predicate_index));
330         }
331     }
332
333     /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
334     /// supplied to find out whether it is listed among them.
335     ///
336     /// Never affects the inference environment.
337     fn assemble_candidates_from_caller_bounds<'o>(
338         &mut self,
339         stack: &TraitObligationStack<'o, 'tcx>,
340         candidates: &mut SelectionCandidateSet<'tcx>,
341     ) -> Result<(), SelectionError<'tcx>> {
342         debug!(?stack.obligation, "assemble_candidates_from_caller_bounds");
343
344         let all_bounds = stack
345             .obligation
346             .param_env
347             .caller_bounds()
348             .iter()
349             .filter_map(|o| o.to_opt_poly_trait_ref());
350
351         // Micro-optimization: filter out predicates relating to different traits.
352         let matching_bounds =
353             all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
354
355         // Keep only those bounds which may apply, and propagate overflow if it occurs.
356         let mut param_candidates = vec![];
357         for bound in matching_bounds {
358             let wc = self.evaluate_where_clause(stack, bound)?;
359             if wc.may_apply() {
360                 param_candidates.push(ParamCandidate(bound));
361             }
362         }
363
364         candidates.vec.extend(param_candidates);
365
366         Ok(())
367     }
368
369     fn assemble_generator_candidates(
370         &mut self,
371         obligation: &TraitObligation<'tcx>,
372         candidates: &mut SelectionCandidateSet<'tcx>,
373     ) -> Result<(), SelectionError<'tcx>> {
374         if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
375             return Ok(());
376         }
377
378         // Okay to skip binder because the substs on generator types never
379         // touch bound regions, they just capture the in-scope
380         // type/region parameters.
381         let self_ty = obligation.self_ty().skip_binder();
382         match self_ty.kind() {
383             ty::Generator(..) => {
384                 debug!(?self_ty, ?obligation, "assemble_generator_candidates",);
385
386                 candidates.vec.push(GeneratorCandidate);
387             }
388             ty::Infer(ty::TyVar(_)) => {
389                 debug!("assemble_generator_candidates: ambiguous self-type");
390                 candidates.ambiguous = true;
391             }
392             _ => {}
393         }
394
395         Ok(())
396     }
397
398     /// Checks for the artificial impl that the compiler will create for an obligation like `X :
399     /// FnMut<..>` where `X` is a closure type.
400     ///
401     /// Note: the type parameters on a closure candidate are modeled as *output* type
402     /// parameters and hence do not affect whether this trait is a match or not. They will be
403     /// unified during the confirmation step.
404     fn assemble_closure_candidates(
405         &mut self,
406         obligation: &TraitObligation<'tcx>,
407         candidates: &mut SelectionCandidateSet<'tcx>,
408     ) -> Result<(), SelectionError<'tcx>> {
409         let kind = match self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) {
410             Some(k) => k,
411             None => {
412                 return Ok(());
413             }
414         };
415
416         // Okay to skip binder because the substs on closure types never
417         // touch bound regions, they just capture the in-scope
418         // type/region parameters
419         match *obligation.self_ty().skip_binder().kind() {
420             ty::Closure(_, closure_substs) => {
421                 debug!(?kind, ?obligation, "assemble_unboxed_candidates");
422                 match self.infcx.closure_kind(closure_substs) {
423                     Some(closure_kind) => {
424                         debug!(?closure_kind, "assemble_unboxed_candidates");
425                         if closure_kind.extends(kind) {
426                             candidates.vec.push(ClosureCandidate);
427                         }
428                     }
429                     None => {
430                         debug!("assemble_unboxed_candidates: closure_kind not yet known");
431                         candidates.vec.push(ClosureCandidate);
432                     }
433                 }
434             }
435             ty::Infer(ty::TyVar(_)) => {
436                 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
437                 candidates.ambiguous = true;
438             }
439             _ => {}
440         }
441
442         Ok(())
443     }
444
445     /// Implements one of the `Fn()` family for a fn pointer.
446     fn assemble_fn_pointer_candidates(
447         &mut self,
448         obligation: &TraitObligation<'tcx>,
449         candidates: &mut SelectionCandidateSet<'tcx>,
450     ) -> Result<(), SelectionError<'tcx>> {
451         // We provide impl of all fn traits for fn pointers.
452         if self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()).is_none() {
453             return Ok(());
454         }
455
456         // Okay to skip binder because what we are inspecting doesn't involve bound regions.
457         let self_ty = obligation.self_ty().skip_binder();
458         match *self_ty.kind() {
459             ty::Infer(ty::TyVar(_)) => {
460                 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
461                 candidates.ambiguous = true; // Could wind up being a fn() type.
462             }
463             // Provide an impl, but only for suitable `fn` pointers.
464             ty::FnPtr(_) => {
465                 if let ty::FnSig {
466                     unsafety: hir::Unsafety::Normal,
467                     abi: Abi::Rust,
468                     c_variadic: false,
469                     ..
470                 } = self_ty.fn_sig(self.tcx()).skip_binder()
471                 {
472                     candidates.vec.push(FnPointerCandidate);
473                 }
474             }
475             // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396).
476             ty::FnDef(def_id, _) => {
477                 if let ty::FnSig {
478                     unsafety: hir::Unsafety::Normal,
479                     abi: Abi::Rust,
480                     c_variadic: false,
481                     ..
482                 } = self_ty.fn_sig(self.tcx()).skip_binder()
483                 {
484                     if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() {
485                         candidates.vec.push(FnPointerCandidate);
486                     }
487                 }
488             }
489             _ => {}
490         }
491
492         Ok(())
493     }
494
495     /// Searches for impls that might apply to `obligation`.
496     fn assemble_candidates_from_impls(
497         &mut self,
498         obligation: &TraitObligation<'tcx>,
499         candidates: &mut SelectionCandidateSet<'tcx>,
500     ) -> Result<(), SelectionError<'tcx>> {
501         debug!(?obligation, "assemble_candidates_from_impls");
502
503         // Essentially any user-written impl will match with an error type,
504         // so creating `ImplCandidates` isn't useful. However, we might
505         // end up finding a candidate elsewhere (e.g. a `BuiltinCandidate` for `Sized)
506         // This helps us avoid overflow: see issue #72839
507         // Since compilation is already guaranteed to fail, this is just
508         // to try to show the 'nicest' possible errors to the user.
509         if obligation.references_error() {
510             return Ok(());
511         }
512
513         self.tcx().for_each_relevant_impl(
514             obligation.predicate.def_id(),
515             obligation.predicate.skip_binder().trait_ref.self_ty(),
516             |impl_def_id| {
517                 self.infcx.probe(|_| {
518                     if let Ok(_substs) = self.match_impl(impl_def_id, obligation) {
519                         candidates.vec.push(ImplCandidate(impl_def_id));
520                     }
521                 });
522             },
523         );
524
525         Ok(())
526     }
527
528     fn assemble_candidates_from_auto_impls(
529         &mut self,
530         obligation: &TraitObligation<'tcx>,
531         candidates: &mut SelectionCandidateSet<'tcx>,
532     ) -> Result<(), SelectionError<'tcx>> {
533         // Okay to skip binder here because the tests we do below do not involve bound regions.
534         let self_ty = obligation.self_ty().skip_binder();
535         debug!(?self_ty, "assemble_candidates_from_auto_impls");
536
537         let def_id = obligation.predicate.def_id();
538
539         if self.tcx().trait_is_auto(def_id) {
540             match self_ty.kind() {
541                 ty::Dynamic(..) => {
542                     // For object types, we don't know what the closed
543                     // over types are. This means we conservatively
544                     // say nothing; a candidate may be added by
545                     // `assemble_candidates_from_object_ty`.
546                 }
547                 ty::Foreign(..) => {
548                     // Since the contents of foreign types is unknown,
549                     // we don't add any `..` impl. Default traits could
550                     // still be provided by a manual implementation for
551                     // this trait and type.
552                 }
553                 ty::Param(..) | ty::Projection(..) => {
554                     // In these cases, we don't know what the actual
555                     // type is.  Therefore, we cannot break it down
556                     // into its constituent types. So we don't
557                     // consider the `..` impl but instead just add no
558                     // candidates: this means that typeck will only
559                     // succeed if there is another reason to believe
560                     // that this obligation holds. That could be a
561                     // where-clause or, in the case of an object type,
562                     // it could be that the object type lists the
563                     // trait (e.g., `Foo+Send : Send`). See
564                     // `compile-fail/typeck-default-trait-impl-send-param.rs`
565                     // for an example of a test case that exercises
566                     // this path.
567                 }
568                 ty::Infer(ty::TyVar(_)) => {
569                     // The auto impl might apply; we don't know.
570                     candidates.ambiguous = true;
571                 }
572                 ty::Generator(_, _, movability)
573                     if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
574                 {
575                     match movability {
576                         hir::Movability::Static => {
577                             // Immovable generators are never `Unpin`, so
578                             // suppress the normal auto-impl candidate for it.
579                         }
580                         hir::Movability::Movable => {
581                             // Movable generators are always `Unpin`, so add an
582                             // unconditional builtin candidate.
583                             candidates.vec.push(BuiltinCandidate { has_nested: false });
584                         }
585                     }
586                 }
587
588                 _ => candidates.vec.push(AutoImplCandidate(def_id)),
589             }
590         }
591
592         Ok(())
593     }
594
595     /// Searches for impls that might apply to `obligation`.
596     fn assemble_candidates_from_object_ty(
597         &mut self,
598         obligation: &TraitObligation<'tcx>,
599         candidates: &mut SelectionCandidateSet<'tcx>,
600     ) {
601         debug!(
602             self_ty = ?obligation.self_ty().skip_binder(),
603             "assemble_candidates_from_object_ty",
604         );
605
606         self.infcx.probe(|_snapshot| {
607             // The code below doesn't care about regions, and the
608             // self-ty here doesn't escape this probe, so just erase
609             // any LBR.
610             let self_ty = self.tcx().erase_late_bound_regions(&obligation.self_ty());
611             let poly_trait_ref = match self_ty.kind() {
612                 ty::Dynamic(ref data, ..) => {
613                     if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
614                         debug!(
615                             "assemble_candidates_from_object_ty: matched builtin bound, \
616                              pushing candidate"
617                         );
618                         candidates.vec.push(BuiltinObjectCandidate);
619                         return;
620                     }
621
622                     if let Some(principal) = data.principal() {
623                         if !self.infcx.tcx.features().object_safe_for_dispatch {
624                             principal.with_self_ty(self.tcx(), self_ty)
625                         } else if self.tcx().is_object_safe(principal.def_id()) {
626                             principal.with_self_ty(self.tcx(), self_ty)
627                         } else {
628                             return;
629                         }
630                     } else {
631                         // Only auto trait bounds exist.
632                         return;
633                     }
634                 }
635                 ty::Infer(ty::TyVar(_)) => {
636                     debug!("assemble_candidates_from_object_ty: ambiguous");
637                     candidates.ambiguous = true; // could wind up being an object type
638                     return;
639                 }
640                 _ => return,
641             };
642
643             debug!(?poly_trait_ref, "assemble_candidates_from_object_ty");
644
645             let poly_trait_predicate = self.infcx().resolve_vars_if_possible(&obligation.predicate);
646             let placeholder_trait_predicate =
647                 self.infcx().replace_bound_vars_with_placeholders(&poly_trait_predicate);
648
649             // Count only those upcast versions that match the trait-ref
650             // we are looking for. Specifically, do not only check for the
651             // correct trait, but also the correct type parameters.
652             // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
653             // but `Foo` is declared as `trait Foo: Bar<u32>`.
654             let candidate_supertraits = util::supertraits(self.tcx(), poly_trait_ref)
655                 .enumerate()
656                 .filter(|&(_, upcast_trait_ref)| {
657                     self.infcx.probe(|_| {
658                         self.match_normalize_trait_ref(
659                             obligation,
660                             upcast_trait_ref,
661                             placeholder_trait_predicate.trait_ref,
662                         )
663                         .is_ok()
664                     })
665                 })
666                 .map(|(idx, _)| ObjectCandidate(idx));
667
668             candidates.vec.extend(candidate_supertraits);
669         })
670     }
671
672     /// Searches for unsizing that might apply to `obligation`.
673     fn assemble_candidates_for_unsizing(
674         &mut self,
675         obligation: &TraitObligation<'tcx>,
676         candidates: &mut SelectionCandidateSet<'tcx>,
677     ) {
678         // We currently never consider higher-ranked obligations e.g.
679         // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
680         // because they are a priori invalid, and we could potentially add support
681         // for them later, it's just that there isn't really a strong need for it.
682         // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
683         // impl, and those are generally applied to concrete types.
684         //
685         // That said, one might try to write a fn with a where clause like
686         //     for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
687         // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
688         // Still, you'd be more likely to write that where clause as
689         //     T: Trait
690         // so it seems ok if we (conservatively) fail to accept that `Unsize`
691         // obligation above. Should be possible to extend this in the future.
692         let source = match obligation.self_ty().no_bound_vars() {
693             Some(t) => t,
694             None => {
695                 // Don't add any candidates if there are bound regions.
696                 return;
697             }
698         };
699         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
700
701         debug!(?source, ?target, "assemble_candidates_for_unsizing");
702
703         let may_apply = match (source.kind(), target.kind()) {
704             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
705             (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
706                 // Upcasts permit two things:
707                 //
708                 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
709                 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
710                 //
711                 // Note that neither of these changes requires any
712                 // change at runtime. Eventually this will be
713                 // generalized.
714                 //
715                 // We always upcast when we can because of reason
716                 // #2 (region bounds).
717                 data_a.principal_def_id() == data_b.principal_def_id()
718                     && data_b
719                         .auto_traits()
720                         // All of a's auto traits need to be in b's auto traits.
721                         .all(|b| data_a.auto_traits().any(|a| a == b))
722             }
723
724             // `T` -> `Trait`
725             (_, &ty::Dynamic(..)) => true,
726
727             // Ambiguous handling is below `T` -> `Trait`, because inference
728             // variables can still implement `Unsize<Trait>` and nested
729             // obligations will have the final say (likely deferred).
730             (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
731                 debug!("assemble_candidates_for_unsizing: ambiguous");
732                 candidates.ambiguous = true;
733                 false
734             }
735
736             // `[T; n]` -> `[T]`
737             (&ty::Array(..), &ty::Slice(_)) => true,
738
739             // `Struct<T>` -> `Struct<U>`
740             (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
741                 def_id_a == def_id_b
742             }
743
744             // `(.., T)` -> `(.., U)`
745             (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
746
747             _ => false,
748         };
749
750         if may_apply {
751             candidates.vec.push(BuiltinUnsizeCandidate);
752         }
753     }
754
755     fn assemble_candidates_for_trait_alias(
756         &mut self,
757         obligation: &TraitObligation<'tcx>,
758         candidates: &mut SelectionCandidateSet<'tcx>,
759     ) -> Result<(), SelectionError<'tcx>> {
760         // Okay to skip binder here because the tests we do below do not involve bound regions.
761         let self_ty = obligation.self_ty().skip_binder();
762         debug!(?self_ty, "assemble_candidates_for_trait_alias");
763
764         let def_id = obligation.predicate.def_id();
765
766         if self.tcx().is_trait_alias(def_id) {
767             candidates.vec.push(TraitAliasCandidate(def_id));
768         }
769
770         Ok(())
771     }
772
773     /// Assembles the trait which are built-in to the language itself:
774     /// `Copy`, `Clone` and `Sized`.
775     fn assemble_builtin_bound_candidates(
776         &mut self,
777         conditions: BuiltinImplConditions<'tcx>,
778         candidates: &mut SelectionCandidateSet<'tcx>,
779     ) -> Result<(), SelectionError<'tcx>> {
780         match conditions {
781             BuiltinImplConditions::Where(nested) => {
782                 debug!(?nested, "builtin_bound");
783                 candidates
784                     .vec
785                     .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
786             }
787             BuiltinImplConditions::None => {}
788             BuiltinImplConditions::Ambiguous => {
789                 debug!("assemble_builtin_bound_candidates: ambiguous builtin");
790                 candidates.ambiguous = true;
791             }
792         }
793
794         Ok(())
795     }
796 }