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