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
10 use rustc_hir::def_id::DefId;
11 use rustc_infer::traits::TraitEngine;
12 use rustc_infer::traits::{Obligation, SelectionError, TraitObligation};
13 use rustc_lint_defs::builtin::DEREF_INTO_DYN_SUPERTRAIT;
14 use rustc_middle::ty::print::with_no_trimmed_paths;
15 use rustc_middle::ty::{self, ToPredicate, Ty, TypeFoldable};
16 use rustc_target::spec::abi::Abi;
19 use crate::traits::coherence::Conflict;
20 use crate::traits::query::evaluate_obligation::InferCtxtExt;
21 use crate::traits::{util, SelectionResult};
22 use crate::traits::{Ambiguous, ErrorReporting, Overflow, Unimplemented};
24 use super::BuiltinImplConditions;
25 use super::IntercrateAmbiguityCause;
26 use super::OverflowError;
27 use super::SelectionCandidate::{self, *};
28 use super::{EvaluatedCandidate, SelectionCandidateSet, SelectionContext, TraitObligationStack};
30 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
31 #[instrument(level = "debug", skip(self))]
32 pub(super) fn candidate_from_obligation<'o>(
34 stack: &TraitObligationStack<'o, 'tcx>,
35 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
36 // Watch out for overflow. This intentionally bypasses (and does
37 // not update) the cache.
38 self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
40 // Check the cache. Note that we freshen the trait-ref
41 // separately rather than using `stack.fresh_trait_ref` --
42 // this is because we want the unbound variables to be
43 // replaced with fresh types starting from index 0.
44 let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
45 debug!(?cache_fresh_trait_pred);
46 debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
49 self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
51 debug!(candidate = ?c, "CACHE HIT");
55 // If no match, compute result and insert into cache.
57 // FIXME(nikomatsakis) -- this cache is not taking into
58 // account cycles that may have occurred in forming the
59 // candidate. I don't know of any specific problems that
60 // result but it seems awfully suspicious.
61 let (candidate, dep_node) =
62 self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
64 debug!(?candidate, "CACHE MISS");
65 self.insert_candidate_cache(
66 stack.obligation.param_env,
67 cache_fresh_trait_pred,
74 fn candidate_from_obligation_no_cache<'o>(
76 stack: &TraitObligationStack<'o, 'tcx>,
77 ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
78 if let Some(conflict) = self.is_knowable(stack) {
79 debug!("coherence stage: not knowable");
80 if self.intercrate_ambiguity_causes.is_some() {
81 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
82 // Heuristics: show the diagnostics when there are no candidates in crate.
83 if let Ok(candidate_set) = self.assemble_candidates(stack) {
84 let mut no_candidates_apply = true;
86 for c in candidate_set.vec.iter() {
87 if self.evaluate_candidate(stack, &c)?.may_apply() {
88 no_candidates_apply = false;
93 if !candidate_set.ambiguous && no_candidates_apply {
94 let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
95 let self_ty = trait_ref.self_ty();
96 let (trait_desc, self_desc) = with_no_trimmed_paths!({
97 let trait_desc = trait_ref.print_only_trait_path().to_string();
98 let self_desc = if self_ty.has_concrete_skeleton() {
99 Some(self_ty.to_string())
103 (trait_desc, self_desc)
105 let cause = if let Conflict::Upstream = conflict {
106 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
108 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
110 debug!(?cause, "evaluate_stack: pushing cause");
111 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
118 let candidate_set = self.assemble_candidates(stack)?;
120 if candidate_set.ambiguous {
121 debug!("candidate set contains ambig");
125 let candidates = candidate_set.vec;
127 debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
129 // At this point, we know that each of the entries in the
130 // candidate set is *individually* applicable. Now we have to
131 // figure out if they contain mutual incompatibilities. This
132 // frequently arises if we have an unconstrained input type --
133 // for example, we are looking for `$0: Eq` where `$0` is some
134 // unconstrained type variable. In that case, we'll get a
135 // candidate which assumes $0 == int, one that assumes `$0 ==
136 // usize`, etc. This spells an ambiguity.
138 let mut candidates = self.filter_impls(candidates, stack.obligation);
140 // If there is more than one candidate, first winnow them down
141 // by considering extra conditions (nested obligations and so
142 // forth). We don't winnow if there is exactly one
143 // candidate. This is a relatively minor distinction but it
144 // can lead to better inference and error-reporting. An
145 // example would be if there was an impl:
147 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
149 // and we were to see some code `foo.push_clone()` where `boo`
150 // is a `Vec<Bar>` and `Bar` does not implement `Clone`. If
151 // we were to winnow, we'd wind up with zero candidates.
152 // Instead, we select the right impl now but report "`Bar` does
153 // not implement `Clone`".
154 if candidates.len() == 1 {
155 return self.filter_reservation_impls(candidates.pop().unwrap(), stack.obligation);
158 // Winnow, but record the exact outcome of evaluation, which
159 // is needed for specialization. Propagate overflow if it occurs.
160 let mut candidates = candidates
162 .map(|c| match self.evaluate_candidate(stack, &c) {
163 Ok(eval) if eval.may_apply() => {
164 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
167 Err(OverflowError::Canonical) => Err(Overflow(OverflowError::Canonical)),
168 Err(OverflowError::ErrorReporting) => Err(ErrorReporting),
169 Err(OverflowError::Error(e)) => Err(Overflow(OverflowError::Error(e))),
171 .flat_map(Result::transpose)
172 .collect::<Result<Vec<_>, _>>()?;
174 debug!(?stack, ?candidates, "winnowed to {} candidates", candidates.len());
176 let needs_infer = stack.obligation.predicate.has_infer_types_or_consts();
178 let sized_predicate = self.tcx().lang_items().sized_trait()
179 == Some(stack.obligation.predicate.skip_binder().def_id());
181 // If there are STILL multiple candidates, we can further
182 // reduce the list by dropping duplicates -- including
183 // resolving specializations.
184 if candidates.len() > 1 {
186 while i < candidates.len() {
187 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
188 self.candidate_should_be_dropped_in_favor_of(
196 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
197 candidates.swap_remove(i);
199 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
202 // If there are *STILL* multiple candidates, give up
203 // and report ambiguity.
205 debug!("multiple matches, ambig");
206 return Err(Ambiguous(
209 .filter_map(|c| match c.candidate {
210 SelectionCandidate::ImplCandidate(def_id) => Some(def_id),
220 // If there are *NO* candidates, then there are no impls --
221 // that we know of, anyway. Note that in the case where there
222 // are unbound type variables within the obligation, it might
223 // be the case that you could still satisfy the obligation
224 // from another crate by instantiating the type variables with
225 // a type from another crate that does have an impl. This case
226 // is checked for in `evaluate_stack` (and hence users
227 // who might care about this case, like coherence, should use
229 if candidates.is_empty() {
230 // If there's an error type, 'downgrade' our result from
231 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
232 // emitting additional spurious errors, since we're guaranteed
233 // to have emitted at least one.
234 if stack.obligation.references_error() {
235 debug!("no results for error type, treating as ambiguous");
238 return Err(Unimplemented);
241 // Just one candidate left.
242 self.filter_reservation_impls(candidates.pop().unwrap().candidate, stack.obligation)
245 #[instrument(skip(self, stack), level = "debug")]
246 pub(super) fn assemble_candidates<'o>(
248 stack: &TraitObligationStack<'o, 'tcx>,
249 ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
250 let TraitObligationStack { obligation, .. } = *stack;
251 let obligation = &Obligation {
252 param_env: obligation.param_env,
253 cause: obligation.cause.clone(),
254 recursion_depth: obligation.recursion_depth,
255 predicate: self.infcx().resolve_vars_if_possible(obligation.predicate),
258 if obligation.predicate.skip_binder().self_ty().is_ty_var() {
259 debug!(ty = ?obligation.predicate.skip_binder().self_ty(), "ambiguous inference var or opaque type");
260 // Self is a type variable (e.g., `_: AsRef<str>`).
262 // This is somewhat problematic, as the current scheme can't really
263 // handle it turning to be a projection. This does end up as truly
264 // ambiguous in most cases anyway.
266 // Take the fast path out - this also improves
267 // performance by preventing assemble_candidates_from_impls from
268 // matching every impl for this trait.
269 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
272 let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
274 // The only way to prove a NotImplemented(T: Foo) predicate is via a negative impl.
275 // There are no compiler built-in rules for this.
276 if obligation.polarity() == ty::ImplPolarity::Negative {
277 self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
278 self.assemble_candidates_from_impls(obligation, &mut candidates);
280 self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
282 // Other bounds. Consider both in-scope bounds from fn decl
283 // and applicable impls. There is a certain set of precedence rules here.
284 let def_id = obligation.predicate.def_id();
285 let lang_items = self.tcx().lang_items();
287 if lang_items.copy_trait() == Some(def_id) {
288 debug!(obligation_self_ty = ?obligation.predicate.skip_binder().self_ty());
290 // User-defined copy impls are permitted, but only for
291 // structs and enums.
292 self.assemble_candidates_from_impls(obligation, &mut candidates);
294 // For other types, we'll use the builtin rules.
295 let copy_conditions = self.copy_clone_conditions(obligation);
296 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates);
297 } else if lang_items.discriminant_kind_trait() == Some(def_id) {
298 // `DiscriminantKind` is automatically implemented for every type.
299 candidates.vec.push(DiscriminantKindCandidate);
300 } else if lang_items.pointee_trait() == Some(def_id) {
301 // `Pointee` is automatically implemented for every type.
302 candidates.vec.push(PointeeCandidate);
303 } else if lang_items.sized_trait() == Some(def_id) {
304 // Sized is never implementable by end-users, it is
305 // always automatically computed.
306 let sized_conditions = self.sized_conditions(obligation);
307 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates);
308 } else if lang_items.unsize_trait() == Some(def_id) {
309 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
310 } else if lang_items.destruct_trait() == Some(def_id) {
311 self.assemble_const_destruct_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.where_clause_may_apply(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 Some(kind) = self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) else {
444 // Okay to skip binder because the substs on closure types never
445 // touch bound regions, they just capture the in-scope
446 // type/region parameters
447 match *obligation.self_ty().skip_binder().kind() {
448 ty::Closure(_, closure_substs) => {
449 debug!(?kind, ?obligation, "assemble_unboxed_candidates");
450 match self.infcx.closure_kind(closure_substs) {
451 Some(closure_kind) => {
452 debug!(?closure_kind, "assemble_unboxed_candidates");
453 if closure_kind.extends(kind) {
454 candidates.vec.push(ClosureCandidate);
458 debug!("assemble_unboxed_candidates: closure_kind not yet known");
459 candidates.vec.push(ClosureCandidate);
463 ty::Infer(ty::TyVar(_)) => {
464 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
465 candidates.ambiguous = true;
471 /// Implements one of the `Fn()` family for a fn pointer.
472 fn assemble_fn_pointer_candidates(
474 obligation: &TraitObligation<'tcx>,
475 candidates: &mut SelectionCandidateSet<'tcx>,
477 // We provide impl of all fn traits for fn pointers.
478 if self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()).is_none() {
482 // Okay to skip binder because what we are inspecting doesn't involve bound regions.
483 let self_ty = obligation.self_ty().skip_binder();
484 match *self_ty.kind() {
485 ty::Infer(ty::TyVar(_)) => {
486 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
487 candidates.ambiguous = true; // Could wind up being a fn() type.
489 // Provide an impl, but only for suitable `fn` pointers.
492 unsafety: hir::Unsafety::Normal,
496 } = self_ty.fn_sig(self.tcx()).skip_binder()
498 candidates.vec.push(FnPointerCandidate { is_const: false });
501 // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396).
502 ty::FnDef(def_id, _) => {
504 unsafety: hir::Unsafety::Normal,
508 } = self_ty.fn_sig(self.tcx()).skip_binder()
510 if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() {
513 .push(FnPointerCandidate { is_const: self.tcx().is_const_fn(def_id) });
521 /// Searches for impls that might apply to `obligation`.
522 fn assemble_candidates_from_impls(
524 obligation: &TraitObligation<'tcx>,
525 candidates: &mut SelectionCandidateSet<'tcx>,
527 debug!(?obligation, "assemble_candidates_from_impls");
529 // Essentially any user-written impl will match with an error type,
530 // so creating `ImplCandidates` isn't useful. However, we might
531 // end up finding a candidate elsewhere (e.g. a `BuiltinCandidate` for `Sized)
532 // This helps us avoid overflow: see issue #72839
533 // Since compilation is already guaranteed to fail, this is just
534 // to try to show the 'nicest' possible errors to the user.
535 // We don't check for errors in the `ParamEnv` - in practice,
536 // it seems to cause us to be overly aggressive in deciding
537 // to give up searching for candidates, leading to spurious errors.
538 if obligation.predicate.references_error() {
542 self.tcx().for_each_relevant_impl(
543 obligation.predicate.def_id(),
544 obligation.predicate.skip_binder().trait_ref.self_ty(),
546 self.infcx.probe(|_| {
547 if let Ok(_substs) = self.match_impl(impl_def_id, obligation) {
548 candidates.vec.push(ImplCandidate(impl_def_id));
555 fn assemble_candidates_from_auto_impls(
557 obligation: &TraitObligation<'tcx>,
558 candidates: &mut SelectionCandidateSet<'tcx>,
560 // Okay to skip binder here because the tests we do below do not involve bound regions.
561 let self_ty = obligation.self_ty().skip_binder();
562 debug!(?self_ty, "assemble_candidates_from_auto_impls");
564 let def_id = obligation.predicate.def_id();
566 if self.tcx().trait_is_auto(def_id) {
567 match self_ty.kind() {
569 // For object types, we don't know what the closed
570 // over types are. This means we conservatively
571 // say nothing; a candidate may be added by
572 // `assemble_candidates_from_object_ty`.
575 // Since the contents of foreign types is unknown,
576 // we don't add any `..` impl. Default traits could
577 // still be provided by a manual implementation for
578 // this trait and type.
580 ty::Param(..) | ty::Projection(..) => {
581 // In these cases, we don't know what the actual
582 // type is. Therefore, we cannot break it down
583 // into its constituent types. So we don't
584 // consider the `..` impl but instead just add no
585 // candidates: this means that typeck will only
586 // succeed if there is another reason to believe
587 // that this obligation holds. That could be a
588 // where-clause or, in the case of an object type,
589 // it could be that the object type lists the
590 // trait (e.g., `Foo+Send : Send`). See
591 // `ui/typeck/typeck-default-trait-impl-send-param.rs`
592 // for an example of a test case that exercises
595 ty::Infer(ty::TyVar(_)) => {
596 // The auto impl might apply; we don't know.
597 candidates.ambiguous = true;
599 ty::Generator(_, _, movability)
600 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
603 hir::Movability::Static => {
604 // Immovable generators are never `Unpin`, so
605 // suppress the normal auto-impl candidate for it.
607 hir::Movability::Movable => {
608 // Movable generators are always `Unpin`, so add an
609 // unconditional builtin candidate.
610 candidates.vec.push(BuiltinCandidate { has_nested: false });
615 _ => candidates.vec.push(AutoImplCandidate(def_id)),
620 /// Searches for impls that might apply to `obligation`.
621 fn assemble_candidates_from_object_ty(
623 obligation: &TraitObligation<'tcx>,
624 candidates: &mut SelectionCandidateSet<'tcx>,
627 self_ty = ?obligation.self_ty().skip_binder(),
628 "assemble_candidates_from_object_ty",
631 self.infcx.probe(|_snapshot| {
632 // The code below doesn't care about regions, and the
633 // self-ty here doesn't escape this probe, so just erase
635 let self_ty = self.tcx().erase_late_bound_regions(obligation.self_ty());
636 let poly_trait_ref = match self_ty.kind() {
637 ty::Dynamic(ref data, ..) => {
638 if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
640 "assemble_candidates_from_object_ty: matched builtin bound, \
643 candidates.vec.push(BuiltinObjectCandidate);
647 if let Some(principal) = data.principal() {
648 if !self.infcx.tcx.features().object_safe_for_dispatch {
649 principal.with_self_ty(self.tcx(), self_ty)
650 } else if self.tcx().is_object_safe(principal.def_id()) {
651 principal.with_self_ty(self.tcx(), self_ty)
656 // Only auto trait bounds exist.
660 ty::Infer(ty::TyVar(_)) => {
661 debug!("assemble_candidates_from_object_ty: ambiguous");
662 candidates.ambiguous = true; // could wind up being an object type
668 debug!(?poly_trait_ref, "assemble_candidates_from_object_ty");
670 let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
671 let placeholder_trait_predicate =
672 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
674 // Count only those upcast versions that match the trait-ref
675 // we are looking for. Specifically, do not only check for the
676 // correct trait, but also the correct type parameters.
677 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
678 // but `Foo` is declared as `trait Foo: Bar<u32>`.
679 let candidate_supertraits = util::supertraits(self.tcx(), poly_trait_ref)
681 .filter(|&(_, upcast_trait_ref)| {
682 self.infcx.probe(|_| {
683 self.match_normalize_trait_ref(
686 placeholder_trait_predicate.trait_ref,
691 .map(|(idx, _)| ObjectCandidate(idx));
693 candidates.vec.extend(candidate_supertraits);
697 /// Temporary migration for #89190
698 fn need_migrate_deref_output_trait_object(
701 cause: &traits::ObligationCause<'tcx>,
702 param_env: ty::ParamEnv<'tcx>,
703 ) -> Option<(Ty<'tcx>, DefId)> {
704 let tcx = self.tcx();
705 if tcx.features().trait_upcasting {
710 let trait_ref = ty::TraitRef {
711 def_id: tcx.lang_items().deref_trait()?,
712 substs: tcx.mk_substs_trait(ty, &[]),
715 let obligation = traits::Obligation::new(
718 ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
720 if !self.infcx.predicate_may_hold(&obligation) {
724 let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
725 let normalized_ty = fulfillcx.normalize_projection_type(
729 item_def_id: tcx.lang_items().deref_target()?,
730 substs: trait_ref.substs,
735 let ty::Dynamic(data, ..) = normalized_ty.kind() else {
739 let def_id = data.principal_def_id()?;
741 return Some((normalized_ty, def_id));
744 /// Searches for unsizing that might apply to `obligation`.
745 fn assemble_candidates_for_unsizing(
747 obligation: &TraitObligation<'tcx>,
748 candidates: &mut SelectionCandidateSet<'tcx>,
750 // We currently never consider higher-ranked obligations e.g.
751 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
752 // because they are a priori invalid, and we could potentially add support
753 // for them later, it's just that there isn't really a strong need for it.
754 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
755 // impl, and those are generally applied to concrete types.
757 // That said, one might try to write a fn with a where clause like
758 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
759 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
760 // Still, you'd be more likely to write that where clause as
762 // so it seems ok if we (conservatively) fail to accept that `Unsize`
763 // obligation above. Should be possible to extend this in the future.
764 let Some(source) = obligation.self_ty().no_bound_vars() else {
765 // Don't add any candidates if there are bound regions.
768 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
770 debug!(?source, ?target, "assemble_candidates_for_unsizing");
772 match (source.kind(), target.kind()) {
773 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
774 (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
775 // Upcast coercions permit several things:
777 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
778 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
779 // 3. Tightening trait to its super traits, eg. `Foo` to `Bar` if `Foo: Bar`
781 // Note that neither of the first two of these changes requires any
782 // change at runtime. The third needs to change pointer metadata at runtime.
784 // We always perform upcasting coercions when we can because of reason
785 // #2 (region bounds).
786 let auto_traits_compatible = data_b
788 // All of a's auto traits need to be in b's auto traits.
789 .all(|b| data_a.auto_traits().any(|a| a == b));
790 if auto_traits_compatible {
791 let principal_def_id_a = data_a.principal_def_id();
792 let principal_def_id_b = data_b.principal_def_id();
793 if principal_def_id_a == principal_def_id_b {
795 candidates.vec.push(BuiltinUnsizeCandidate);
796 } else if principal_def_id_a.is_some() && principal_def_id_b.is_some() {
797 // not casual unsizing, now check whether this is trait upcasting coercion.
798 let principal_a = data_a.principal().unwrap();
799 let target_trait_did = principal_def_id_b.unwrap();
800 let source_trait_ref = principal_a.with_self_ty(self.tcx(), source);
801 if let Some((deref_output_ty, deref_output_trait_did)) = self
802 .need_migrate_deref_output_trait_object(
805 obligation.param_env,
808 if deref_output_trait_did == target_trait_did {
809 self.tcx().struct_span_lint_hir(
810 DEREF_INTO_DYN_SUPERTRAIT,
811 obligation.cause.body_id,
812 obligation.cause.span,
815 "`{}` implements `Deref` with supertrait `{}` as output",
825 for (idx, upcast_trait_ref) in
826 util::supertraits(self.tcx(), source_trait_ref).enumerate()
828 if upcast_trait_ref.def_id() == target_trait_did {
829 candidates.vec.push(TraitUpcastingUnsizeCandidate(idx));
837 (_, &ty::Dynamic(..)) => {
838 candidates.vec.push(BuiltinUnsizeCandidate);
841 // Ambiguous handling is below `T` -> `Trait`, because inference
842 // variables can still implement `Unsize<Trait>` and nested
843 // obligations will have the final say (likely deferred).
844 (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
845 debug!("assemble_candidates_for_unsizing: ambiguous");
846 candidates.ambiguous = true;
850 (&ty::Array(..), &ty::Slice(_)) => {
851 candidates.vec.push(BuiltinUnsizeCandidate);
854 // `Struct<T>` -> `Struct<U>`
855 (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
856 if def_id_a == def_id_b {
857 candidates.vec.push(BuiltinUnsizeCandidate);
861 // `(.., T)` -> `(.., U)`
862 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
863 if tys_a.len() == tys_b.len() {
864 candidates.vec.push(BuiltinUnsizeCandidate);
872 #[tracing::instrument(level = "debug", skip(self, obligation, candidates))]
873 fn assemble_candidates_for_trait_alias(
875 obligation: &TraitObligation<'tcx>,
876 candidates: &mut SelectionCandidateSet<'tcx>,
878 // Okay to skip binder here because the tests we do below do not involve bound regions.
879 let self_ty = obligation.self_ty().skip_binder();
882 let def_id = obligation.predicate.def_id();
884 if self.tcx().is_trait_alias(def_id) {
885 candidates.vec.push(TraitAliasCandidate(def_id));
889 /// Assembles the trait which are built-in to the language itself:
890 /// `Copy`, `Clone` and `Sized`.
891 #[tracing::instrument(level = "debug", skip(self, candidates))]
892 fn assemble_builtin_bound_candidates(
894 conditions: BuiltinImplConditions<'tcx>,
895 candidates: &mut SelectionCandidateSet<'tcx>,
898 BuiltinImplConditions::Where(nested) => {
901 .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
903 BuiltinImplConditions::None => {}
904 BuiltinImplConditions::Ambiguous => {
905 candidates.ambiguous = true;
910 fn assemble_const_destruct_candidates(
912 obligation: &TraitObligation<'tcx>,
913 candidates: &mut SelectionCandidateSet<'tcx>,
915 // If the predicate is `~const Destruct` in a non-const environment, we don't actually need
916 // to check anything. We'll short-circuit checking any obligations in confirmation, too.
917 if !obligation.is_const() {
918 candidates.vec.push(ConstDestructCandidate(None));
922 let self_ty = self.infcx().shallow_resolve(obligation.self_ty());
923 match self_ty.skip_binder().kind() {
930 | ty::Projection(_) => {
931 // We don't know if these are `~const Destruct`, at least
932 // not structurally... so don't push a candidate.
940 | ty::Infer(ty::IntVar(_))
941 | ty::Infer(ty::FloatVar(_))
954 | ty::GeneratorWitness(_) => {
955 // These are built-in, and cannot have a custom `impl const Destruct`.
956 candidates.vec.push(ConstDestructCandidate(None));
960 // Find a custom `impl Drop` impl, if it exists
961 let relevant_impl = self.tcx().find_map_relevant_impl(
962 self.tcx().require_lang_item(LangItem::Drop, None),
963 obligation.predicate.skip_binder().trait_ref.self_ty(),
967 if let Some(impl_def_id) = relevant_impl {
968 // Check that `impl Drop` is actually const, if there is a custom impl
969 if self.tcx().impl_constness(impl_def_id) == hir::Constness::Const {
970 candidates.vec.push(ConstDestructCandidate(Some(impl_def_id)));
973 // Otherwise check the ADT like a built-in type (structurally)
974 candidates.vec.push(ConstDestructCandidate(None));
979 candidates.ambiguous = true;