1 //! Candidate assembly.
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.
7 //! [rustc dev guide]:https://rustc-dev-guide.rust-lang.org/traits/resolution.html#candidate-assembly
9 use rustc_hir::def_id::DefId;
10 use rustc_infer::traits::TraitEngine;
11 use rustc_infer::traits::{Obligation, SelectionError, TraitObligation};
12 use rustc_lint_defs::builtin::DEREF_INTO_DYN_SUPERTRAIT;
13 use rustc_middle::ty::print::with_no_trimmed_paths;
14 use rustc_middle::ty::{self, ToPredicate, Ty, TypeFoldable};
15 use rustc_target::spec::abi::Abi;
18 use crate::traits::coherence::Conflict;
19 use crate::traits::query::evaluate_obligation::InferCtxtExt;
20 use crate::traits::{util, SelectionResult};
21 use crate::traits::{Ambiguous, ErrorReporting, Overflow, Unimplemented};
23 use super::BuiltinImplConditions;
24 use super::IntercrateAmbiguityCause;
25 use super::OverflowError;
26 use super::SelectionCandidate::{self, *};
27 use super::{EvaluatedCandidate, SelectionCandidateSet, SelectionContext, TraitObligationStack};
29 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
30 #[instrument(level = "debug", skip(self))]
31 pub(super) fn candidate_from_obligation<'o>(
33 stack: &TraitObligationStack<'o, 'tcx>,
34 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
35 // Watch out for overflow. This intentionally bypasses (and does
36 // not update) the cache.
37 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
39 // Check the cache. Note that we freshen the trait-ref
40 // separately rather than using `stack.fresh_trait_ref` --
41 // this is because we want the unbound variables to be
42 // replaced with fresh types starting from index 0.
43 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
44 debug!(?cache_fresh_trait_pred);
45 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
48 self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
50 debug!(candidate = ?c, "CACHE HIT");
54 // If no match, compute result and insert into cache.
56 // FIXME(nikomatsakis) -- this cache is not taking into
57 // account cycles that may have occurred in forming the
58 // candidate. I don't know of any specific problems that
59 // result but it seems awfully suspicious.
60 let (candidate, dep_node) =
61 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
63 debug!(?candidate, "CACHE MISS");
64 self.insert_candidate_cache(
65 stack.obligation.param_env,
66 cache_fresh_trait_pred,
73 fn candidate_from_obligation_no_cache<'o>(
75 stack: &TraitObligationStack<'o, 'tcx>,
76 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
77 if let Some(conflict) = self.is_knowable(stack) {
78 debug!("coherence stage: not knowable");
79 if self.intercrate_ambiguity_causes.is_some() {
80 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
81 // Heuristics: show the diagnostics when there are no candidates in crate.
82 if let Ok(candidate_set) = self.assemble_candidates(stack) {
83 let mut no_candidates_apply = true;
85 for c in candidate_set.vec.iter() {
86 if self.evaluate_candidate(stack, &c)?.may_apply() {
87 no_candidates_apply = false;
92 if !candidate_set.ambiguous && no_candidates_apply {
93 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
94 let self_ty = trait_ref.self_ty();
95 let (trait_desc, self_desc) = with_no_trimmed_paths(|| {
96 let trait_desc = trait_ref.print_only_trait_path().to_string();
97 let self_desc = if self_ty.has_concrete_skeleton() {
98 Some(self_ty.to_string())
102 (trait_desc, self_desc)
104 let cause = if let Conflict::Upstream = conflict {
105 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
107 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
109 debug!(?cause, "evaluate_stack: pushing cause");
110 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
117 let candidate_set = self.assemble_candidates(stack)?;
119 if candidate_set.ambiguous {
120 debug!("candidate set contains ambig");
124 let candidates = candidate_set.vec;
126 debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
128 // At this point, we know that each of the entries in the
129 // candidate set is *individually* applicable. Now we have to
130 // figure out if they contain mutual incompatibilities. This
131 // frequently arises if we have an unconstrained input type --
132 // for example, we are looking for `$0: Eq` where `$0` is some
133 // unconstrained type variable. In that case, we'll get a
134 // candidate which assumes $0 == int, one that assumes `$0 ==
135 // usize`, etc. This spells an ambiguity.
137 let mut candidates = self.filter_impls(candidates, stack.obligation);
139 // If there is more than one candidate, first winnow them down
140 // by considering extra conditions (nested obligations and so
141 // forth). We don't winnow if there is exactly one
142 // candidate. This is a relatively minor distinction but it
143 // can lead to better inference and error-reporting. An
144 // example would be if there was an impl:
146 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
148 // and we were to see some code `foo.push_clone()` where `boo`
149 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
150 // we were to winnow, we'd wind up with zero candidates.
151 // Instead, we select the right impl now but report "`Bar` does
152 // not implement `Clone`".
153 if candidates.len() == 1 {
154 return self.filter_reservation_impls(candidates.pop().unwrap(), stack.obligation);
157 // Winnow, but record the exact outcome of evaluation, which
158 // is needed for specialization. Propagate overflow if it occurs.
159 let mut candidates = candidates
161 .map(|c| match self.evaluate_candidate(stack, &c) {
162 Ok(eval) if eval.may_apply() => {
163 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
166 Err(OverflowError::Canonical) => Err(Overflow),
167 Err(OverflowError::ErrorReporting) => Err(ErrorReporting),
169 .flat_map(Result::transpose)
170 .collect::<Result<Vec<_>, _>>()?;
172 debug!(?stack, ?candidates, "winnowed to {} candidates", candidates.len());
174 let needs_infer = stack.obligation.predicate.has_infer_types_or_consts();
176 let sized_predicate = self.tcx().lang_items().sized_trait()
177 == Some(stack.obligation.predicate.skip_binder().def_id());
179 // If there are STILL multiple candidates, we can further
180 // reduce the list by dropping duplicates -- including
181 // resolving specializations.
182 if candidates.len() > 1 {
184 while i < candidates.len() {
185 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
186 self.candidate_should_be_dropped_in_favor_of(
194 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
195 candidates.swap_remove(i);
197 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
200 // If there are *STILL* multiple candidates, give up
201 // and report ambiguity.
203 debug!("multiple matches, ambig");
204 return Err(Ambiguous(
207 .filter_map(|c| match c.candidate {
208 SelectionCandidate::ImplCandidate(def_id) => Some(def_id),
218 // If there are *NO* candidates, then there are no impls --
219 // that we know of, anyway. Note that in the case where there
220 // are unbound type variables within the obligation, it might
221 // be the case that you could still satisfy the obligation
222 // from another crate by instantiating the type variables with
223 // a type from another crate that does have an impl. This case
224 // is checked for in `evaluate_stack` (and hence users
225 // who might care about this case, like coherence, should use
227 if candidates.is_empty() {
228 // If there's an error type, 'downgrade' our result from
229 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
230 // emitting additional spurious errors, since we're guaranteed
231 // to have emitted at least one.
232 if stack.obligation.references_error() {
233 debug!("no results for error type, treating as ambiguous");
236 return Err(Unimplemented);
239 // Just one candidate left.
240 self.filter_reservation_impls(candidates.pop().unwrap().candidate, stack.obligation)
243 #[instrument(skip(self, stack), level = "debug")]
244 pub(super) fn assemble_candidates<'o>(
246 stack: &TraitObligationStack<'o, 'tcx>,
247 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
248 let TraitObligationStack { obligation, .. } = *stack;
249 let obligation = &Obligation {
250 param_env: obligation.param_env,
251 cause: obligation.cause.clone(),
252 recursion_depth: obligation.recursion_depth,
253 predicate: self.infcx().resolve_vars_if_possible(obligation.predicate),
256 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
257 debug!(ty = ?obligation.predicate.skip_binder().self_ty(), "ambiguous inference var or opaque type");
258 // Self is a type variable (e.g., `_: AsRef<str>`).
260 // This is somewhat problematic, as the current scheme can't really
261 // handle it turning to be a projection. This does end up as truly
262 // ambiguous in most cases anyway.
264 // Take the fast path out - this also improves
265 // performance by preventing assemble_candidates_from_impls from
266 // matching every impl for this trait.
267 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
270 let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
272 // The only way to prove a NotImplemented(T: Foo) predicate is via a negative impl.
273 // There are no compiler built-in rules for this.
274 if obligation.polarity() == ty::ImplPolarity::Negative {
275 self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
276 self.assemble_candidates_from_impls(obligation, &mut candidates);
278 self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
280 // Other bounds. Consider both in-scope bounds from fn decl
281 // and applicable impls. There is a certain set of precedence rules here.
282 let def_id = obligation.predicate.def_id();
283 let lang_items = self.tcx().lang_items();
285 if lang_items.copy_trait() == Some(def_id) {
286 debug!(obligation_self_ty = ?obligation.predicate.skip_binder().self_ty());
288 // User-defined copy impls are permitted, but only for
289 // structs and enums.
290 self.assemble_candidates_from_impls(obligation, &mut candidates);
292 // For other types, we'll use the builtin rules.
293 let copy_conditions = self.copy_clone_conditions(obligation);
294 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates);
295 } else if lang_items.discriminant_kind_trait() == Some(def_id) {
296 // `DiscriminantKind` is automatically implemented for every type.
297 candidates.vec.push(DiscriminantKindCandidate);
298 } else if lang_items.pointee_trait() == Some(def_id) {
299 // `Pointee` is automatically implemented for every type.
300 candidates.vec.push(PointeeCandidate);
301 } else if lang_items.sized_trait() == Some(def_id) {
302 // Sized is never implementable by end-users, it is
303 // always automatically computed.
304 let sized_conditions = self.sized_conditions(obligation);
305 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates);
306 } else if lang_items.unsize_trait() == Some(def_id) {
307 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
308 } else if lang_items.drop_trait() == Some(def_id)
309 && obligation.predicate.is_const_if_const()
311 self.assemble_const_drop_candidates(obligation, &mut candidates);
313 if lang_items.clone_trait() == Some(def_id) {
314 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
315 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
316 // types have builtin support for `Clone`.
317 let clone_conditions = self.copy_clone_conditions(obligation);
318 self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates);
321 self.assemble_generator_candidates(obligation, &mut candidates);
322 self.assemble_closure_candidates(obligation, &mut candidates);
323 self.assemble_fn_pointer_candidates(obligation, &mut candidates);
324 self.assemble_candidates_from_impls(obligation, &mut candidates);
325 self.assemble_candidates_from_object_ty(obligation, &mut candidates);
328 self.assemble_candidates_from_projected_tys(obligation, &mut candidates);
329 self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?;
330 // Auto implementations have lower priority, so we only
331 // consider triggering a default if there is no other impl that can apply.
332 if candidates.vec.is_empty() {
333 self.assemble_candidates_from_auto_impls(obligation, &mut candidates);
336 debug!("candidate list size: {}", candidates.vec.len());
340 #[tracing::instrument(level = "debug", skip(self, candidates))]
341 fn assemble_candidates_from_projected_tys(
343 obligation: &TraitObligation<'tcx>,
344 candidates: &mut SelectionCandidateSet<'tcx>,
346 // Before we go into the whole placeholder thing, just
347 // quickly check if the self-type is a projection at all.
348 match obligation.predicate.skip_binder().trait_ref.self_ty().kind() {
349 ty::Projection(_) | ty::Opaque(..) => {}
350 ty::Infer(ty::TyVar(_)) => {
352 obligation.cause.span,
353 "Self=_ should have been handled by assemble_candidates"
361 .probe(|_| self.match_projection_obligation_against_definition_bounds(obligation));
363 candidates.vec.extend(result.into_iter().map(ProjectionCandidate));
366 /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
367 /// supplied to find out whether it is listed among them.
369 /// Never affects the inference environment.
370 #[tracing::instrument(level = "debug", skip(self, stack, candidates))]
371 fn assemble_candidates_from_caller_bounds<'o>(
373 stack: &TraitObligationStack<'o, 'tcx>,
374 candidates: &mut SelectionCandidateSet<'tcx>,
375 ) -> Result<(), SelectionError<'tcx>> {
376 debug!(?stack.obligation);
378 let all_bounds = stack
383 .filter_map(|o| o.to_opt_poly_trait_pred());
385 // Micro-optimization: filter out predicates relating to different traits.
386 let matching_bounds =
387 all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id());
389 // Keep only those bounds which may apply, and propagate overflow if it occurs.
390 for bound in matching_bounds {
391 // FIXME(oli-obk): it is suspicious that we are dropping the constness and
393 let wc = self.evaluate_where_clause(stack, bound.map_bound(|t| t.trait_ref))?;
395 candidates.vec.push(ParamCandidate(bound));
402 fn assemble_generator_candidates(
404 obligation: &TraitObligation<'tcx>,
405 candidates: &mut SelectionCandidateSet<'tcx>,
407 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
411 // Okay to skip binder because the substs on generator types never
412 // touch bound regions, they just capture the in-scope
413 // type/region parameters.
414 let self_ty = obligation.self_ty().skip_binder();
415 match self_ty.kind() {
416 ty::Generator(..) => {
417 debug!(?self_ty, ?obligation, "assemble_generator_candidates",);
419 candidates.vec.push(GeneratorCandidate);
421 ty::Infer(ty::TyVar(_)) => {
422 debug!("assemble_generator_candidates: ambiguous self-type");
423 candidates.ambiguous = true;
429 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
430 /// FnMut<..>` where `X` is a closure type.
432 /// Note: the type parameters on a closure candidate are modeled as *output* type
433 /// parameters and hence do not affect whether this trait is a match or not. They will be
434 /// unified during the confirmation step.
435 fn assemble_closure_candidates(
437 obligation: &TraitObligation<'tcx>,
438 candidates: &mut SelectionCandidateSet<'tcx>,
440 let kind = match self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) {
447 // Okay to skip binder because the substs on closure types never
448 // touch bound regions, they just capture the in-scope
449 // type/region parameters
450 match *obligation.self_ty().skip_binder().kind() {
451 ty::Closure(_, closure_substs) => {
452 debug!(?kind, ?obligation, "assemble_unboxed_candidates");
453 match self.infcx.closure_kind(closure_substs) {
454 Some(closure_kind) => {
455 debug!(?closure_kind, "assemble_unboxed_candidates");
456 if closure_kind.extends(kind) {
457 candidates.vec.push(ClosureCandidate);
461 debug!("assemble_unboxed_candidates: closure_kind not yet known");
462 candidates.vec.push(ClosureCandidate);
466 ty::Infer(ty::TyVar(_)) => {
467 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
468 candidates.ambiguous = true;
474 /// Implements one of the `Fn()` family for a fn pointer.
475 fn assemble_fn_pointer_candidates(
477 obligation: &TraitObligation<'tcx>,
478 candidates: &mut SelectionCandidateSet<'tcx>,
480 // We provide impl of all fn traits for fn pointers.
481 if self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()).is_none() {
485 // Okay to skip binder because what we are inspecting doesn't involve bound regions.
486 let self_ty = obligation.self_ty().skip_binder();
487 match *self_ty.kind() {
488 ty::Infer(ty::TyVar(_)) => {
489 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
490 candidates.ambiguous = true; // Could wind up being a fn() type.
492 // Provide an impl, but only for suitable `fn` pointers.
495 unsafety: hir::Unsafety::Normal,
499 } = self_ty.fn_sig(self.tcx()).skip_binder()
501 candidates.vec.push(FnPointerCandidate { is_const: false });
504 // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396).
505 ty::FnDef(def_id, _) => {
507 unsafety: hir::Unsafety::Normal,
511 } = self_ty.fn_sig(self.tcx()).skip_binder()
513 if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() {
516 .push(FnPointerCandidate { is_const: self.tcx().is_const_fn(def_id) });
524 /// Searches for impls that might apply to `obligation`.
525 fn assemble_candidates_from_impls(
527 obligation: &TraitObligation<'tcx>,
528 candidates: &mut SelectionCandidateSet<'tcx>,
530 debug!(?obligation, "assemble_candidates_from_impls");
532 // Essentially any user-written impl will match with an error type,
533 // so creating `ImplCandidates` isn't useful. However, we might
534 // end up finding a candidate elsewhere (e.g. a `BuiltinCandidate` for `Sized)
535 // This helps us avoid overflow: see issue #72839
536 // Since compilation is already guaranteed to fail, this is just
537 // to try to show the 'nicest' possible errors to the user.
538 // We don't check for errors in the `ParamEnv` - in practice,
539 // it seems to cause us to be overly aggressive in deciding
540 // to give up searching for candidates, leading to spurious errors.
541 if obligation.predicate.references_error() {
545 self.tcx().for_each_relevant_impl(
546 obligation.predicate.def_id(),
547 obligation.predicate.skip_binder().trait_ref.self_ty(),
549 self.infcx.probe(|_| {
550 if let Ok(_substs) = self.match_impl(impl_def_id, obligation) {
551 candidates.vec.push(ImplCandidate(impl_def_id));
558 fn assemble_candidates_from_auto_impls(
560 obligation: &TraitObligation<'tcx>,
561 candidates: &mut SelectionCandidateSet<'tcx>,
563 // Okay to skip binder here because the tests we do below do not involve bound regions.
564 let self_ty = obligation.self_ty().skip_binder();
565 debug!(?self_ty, "assemble_candidates_from_auto_impls");
567 let def_id = obligation.predicate.def_id();
569 if self.tcx().trait_is_auto(def_id) {
570 match self_ty.kind() {
572 // For object types, we don't know what the closed
573 // over types are. This means we conservatively
574 // say nothing; a candidate may be added by
575 // `assemble_candidates_from_object_ty`.
578 // Since the contents of foreign types is unknown,
579 // we don't add any `..` impl. Default traits could
580 // still be provided by a manual implementation for
581 // this trait and type.
583 ty::Param(..) | ty::Projection(..) => {
584 // In these cases, we don't know what the actual
585 // type is. Therefore, we cannot break it down
586 // into its constituent types. So we don't
587 // consider the `..` impl but instead just add no
588 // candidates: this means that typeck will only
589 // succeed if there is another reason to believe
590 // that this obligation holds. That could be a
591 // where-clause or, in the case of an object type,
592 // it could be that the object type lists the
593 // trait (e.g., `Foo+Send : Send`). See
594 // `ui/typeck/typeck-default-trait-impl-send-param.rs`
595 // for an example of a test case that exercises
598 ty::Infer(ty::TyVar(_)) => {
599 // The auto impl might apply; we don't know.
600 candidates.ambiguous = true;
602 ty::Generator(_, _, movability)
603 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
606 hir::Movability::Static => {
607 // Immovable generators are never `Unpin`, so
608 // suppress the normal auto-impl candidate for it.
610 hir::Movability::Movable => {
611 // Movable generators are always `Unpin`, so add an
612 // unconditional builtin candidate.
613 candidates.vec.push(BuiltinCandidate { has_nested: false });
618 _ => candidates.vec.push(AutoImplCandidate(def_id)),
623 /// Searches for impls that might apply to `obligation`.
624 fn assemble_candidates_from_object_ty(
626 obligation: &TraitObligation<'tcx>,
627 candidates: &mut SelectionCandidateSet<'tcx>,
630 self_ty = ?obligation.self_ty().skip_binder(),
631 "assemble_candidates_from_object_ty",
634 self.infcx.probe(|_snapshot| {
635 // The code below doesn't care about regions, and the
636 // self-ty here doesn't escape this probe, so just erase
638 let self_ty = self.tcx().erase_late_bound_regions(obligation.self_ty());
639 let poly_trait_ref = match self_ty.kind() {
640 ty::Dynamic(ref data, ..) => {
641 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
643 "assemble_candidates_from_object_ty: matched builtin bound, \
646 candidates.vec.push(BuiltinObjectCandidate);
650 if let Some(principal) = data.principal() {
651 if !self.infcx.tcx.features().object_safe_for_dispatch {
652 principal.with_self_ty(self.tcx(), self_ty)
653 } else if self.tcx().is_object_safe(principal.def_id()) {
654 principal.with_self_ty(self.tcx(), self_ty)
659 // Only auto trait bounds exist.
663 ty::Infer(ty::TyVar(_)) => {
664 debug!("assemble_candidates_from_object_ty: ambiguous");
665 candidates.ambiguous = true; // could wind up being an object type
671 debug!(?poly_trait_ref, "assemble_candidates_from_object_ty");
673 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
674 let placeholder_trait_predicate =
675 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
677 // Count only those upcast versions that match the trait-ref
678 // we are looking for. Specifically, do not only check for the
679 // correct trait, but also the correct type parameters.
680 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
681 // but `Foo` is declared as `trait Foo: Bar<u32>`.
682 let candidate_supertraits = util::supertraits(self.tcx(), poly_trait_ref)
684 .filter(|&(_, upcast_trait_ref)| {
685 self.infcx.probe(|_| {
686 self.match_normalize_trait_ref(
689 placeholder_trait_predicate.trait_ref,
694 .map(|(idx, _)| ObjectCandidate(idx));
696 candidates.vec.extend(candidate_supertraits);
700 /// Temporary migration for #89190
701 fn need_migrate_deref_output_trait_object(
704 cause: &traits::ObligationCause<'tcx>,
705 param_env: ty::ParamEnv<'tcx>,
706 ) -> Option<(Ty<'tcx>, DefId)> {
707 let tcx = self.tcx();
708 if tcx.features().trait_upcasting {
713 let trait_ref = ty::TraitRef {
714 def_id: tcx.lang_items().deref_trait()?,
715 substs: tcx.mk_substs_trait(ty, &[]),
718 let obligation = traits::Obligation::new(
721 ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
723 if !self.infcx.predicate_may_hold(&obligation) {
727 let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
728 let normalized_ty = fulfillcx.normalize_projection_type(
732 item_def_id: tcx.lang_items().deref_target()?,
733 substs: trait_ref.substs,
738 let ty::Dynamic(data, ..) = normalized_ty.kind() else {
742 let def_id = data.principal_def_id()?;
744 return Some((normalized_ty, def_id));
747 /// Searches for unsizing that might apply to `obligation`.
748 fn assemble_candidates_for_unsizing(
750 obligation: &TraitObligation<'tcx>,
751 candidates: &mut SelectionCandidateSet<'tcx>,
753 // We currently never consider higher-ranked obligations e.g.
754 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
755 // because they are a priori invalid, and we could potentially add support
756 // for them later, it's just that there isn't really a strong need for it.
757 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
758 // impl, and those are generally applied to concrete types.
760 // That said, one might try to write a fn with a where clause like
761 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
762 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
763 // Still, you'd be more likely to write that where clause as
765 // so it seems ok if we (conservatively) fail to accept that `Unsize`
766 // obligation above. Should be possible to extend this in the future.
767 let source = match obligation.self_ty().no_bound_vars() {
770 // Don't add any candidates if there are bound regions.
774 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
776 debug!(?source, ?target, "assemble_candidates_for_unsizing");
778 match (source.kind(), target.kind()) {
779 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
780 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
781 // Upcast coercions permit several things:
783 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
784 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
785 // 3. Tightening trait to its super traits, eg. `Foo` to `Bar` if `Foo: Bar`
787 // Note that neither of the first two of these changes requires any
788 // change at runtime. The third needs to change pointer metadata at runtime.
790 // We always perform upcasting coercions when we can because of reason
791 // #2 (region bounds).
792 let auto_traits_compatible = data_b
794 // All of a's auto traits need to be in b's auto traits.
795 .all(|b| data_a.auto_traits().any(|a| a == b));
796 if auto_traits_compatible {
797 let principal_def_id_a = data_a.principal_def_id();
798 let principal_def_id_b = data_b.principal_def_id();
799 if principal_def_id_a == principal_def_id_b {
801 candidates.vec.push(BuiltinUnsizeCandidate);
802 } else if principal_def_id_a.is_some() && principal_def_id_b.is_some() {
803 // not casual unsizing, now check whether this is trait upcasting coercion.
804 let principal_a = data_a.principal().unwrap();
805 let target_trait_did = principal_def_id_b.unwrap();
806 let source_trait_ref = principal_a.with_self_ty(self.tcx(), source);
807 if let Some((deref_output_ty, deref_output_trait_did)) = self
808 .need_migrate_deref_output_trait_object(
811 obligation.param_env,
814 if deref_output_trait_did == target_trait_did {
815 self.tcx().struct_span_lint_hir(
816 DEREF_INTO_DYN_SUPERTRAIT,
817 obligation.cause.body_id,
818 obligation.cause.span,
821 "`{}` implements `Deref` with supertrait `{}` as output",
831 for (idx, upcast_trait_ref) in
832 util::supertraits(self.tcx(), source_trait_ref).enumerate()
834 if upcast_trait_ref.def_id() == target_trait_did {
835 candidates.vec.push(TraitUpcastingUnsizeCandidate(idx));
843 (_, &ty::Dynamic(..)) => {
844 candidates.vec.push(BuiltinUnsizeCandidate);
847 // Ambiguous handling is below `T` -> `Trait`, because inference
848 // variables can still implement `Unsize<Trait>` and nested
849 // obligations will have the final say (likely deferred).
850 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
851 debug!("assemble_candidates_for_unsizing: ambiguous");
852 candidates.ambiguous = true;
856 (&ty::Array(..), &ty::Slice(_)) => {
857 candidates.vec.push(BuiltinUnsizeCandidate);
860 // `Struct<T>` -> `Struct<U>`
861 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
862 if def_id_a == def_id_b {
863 candidates.vec.push(BuiltinUnsizeCandidate);
867 // `(.., T)` -> `(.., U)`
868 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
869 if tys_a.len() == tys_b.len() {
870 candidates.vec.push(BuiltinUnsizeCandidate);
878 #[tracing::instrument(level = "debug", skip(self, obligation, candidates))]
879 fn assemble_candidates_for_trait_alias(
881 obligation: &TraitObligation<'tcx>,
882 candidates: &mut SelectionCandidateSet<'tcx>,
884 // Okay to skip binder here because the tests we do below do not involve bound regions.
885 let self_ty = obligation.self_ty().skip_binder();
888 let def_id = obligation.predicate.def_id();
890 if self.tcx().is_trait_alias(def_id) {
891 candidates.vec.push(TraitAliasCandidate(def_id));
895 /// Assembles the trait which are built-in to the language itself:
896 /// `Copy`, `Clone` and `Sized`.
897 #[tracing::instrument(level = "debug", skip(self, candidates))]
898 fn assemble_builtin_bound_candidates(
900 conditions: BuiltinImplConditions<'tcx>,
901 candidates: &mut SelectionCandidateSet<'tcx>,
904 BuiltinImplConditions::Where(nested) => {
907 .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
909 BuiltinImplConditions::None => {}
910 BuiltinImplConditions::Ambiguous => {
911 candidates.ambiguous = true;
916 fn assemble_const_drop_candidates(
918 obligation: &TraitObligation<'tcx>,
919 candidates: &mut SelectionCandidateSet<'tcx>,
921 // If the predicate is `~const Drop` in a non-const environment, we don't actually need
922 // to check anything. We'll short-circuit checking any obligations in confirmation, too.
923 if obligation.param_env.constness() == hir::Constness::NotConst {
924 candidates.vec.push(ConstDropCandidate(None));
928 let self_ty = self.infcx().shallow_resolve(obligation.self_ty());
929 match self_ty.skip_binder().kind() {
936 | ty::Projection(_) => {
937 // We don't know if these are `~const Drop`, at least
938 // not structurally... so don't push a candidate.
946 | ty::Infer(ty::IntVar(_))
947 | ty::Infer(ty::FloatVar(_))
960 | ty::GeneratorWitness(_) => {
961 // These are built-in, and cannot have a custom `impl const Drop`.
962 candidates.vec.push(ConstDropCandidate(None));
966 // Find a custom `impl Drop` impl, if it exists
967 let relevant_impl = self.tcx().find_map_relevant_impl(
968 obligation.predicate.def_id(),
969 obligation.predicate.skip_binder().trait_ref.self_ty(),
973 if let Some(impl_def_id) = relevant_impl {
974 // Check that `impl Drop` is actually const, if there is a custom impl
975 if self.tcx().impl_constness(impl_def_id) == hir::Constness::Const {
976 candidates.vec.push(ConstDropCandidate(Some(impl_def_id)));
979 // Otherwise check the ADT like a built-in type (structurally)
980 candidates.vec.push(ConstDropCandidate(None));
985 candidates.ambiguous = true;