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 // If there are STILL multiple candidates, we can further
179 // reduce the list by dropping duplicates -- including
180 // resolving specializations.
181 if candidates
.len() > 1 {
183 while i
< candidates
.len() {
184 let is_dup
= (0..candidates
.len()).filter(|&j
| i
!= j
).any(|j
| {
185 self.candidate_should_be_dropped_in_favor_of(
192 debug
!(candidate
= ?candidates
[i
], "Dropping candidate #{}/{}", i
, candidates
.len());
193 candidates
.swap_remove(i
);
195 debug
!(candidate
= ?candidates
[i
], "Retaining candidate #{}/{}", i
, candidates
.len());
198 // If there are *STILL* multiple candidates, give up
199 // and report ambiguity.
201 debug
!("multiple matches, ambig");
202 return Err(Ambiguous(
205 .filter_map(|c
| match c
.candidate
{
206 SelectionCandidate
::ImplCandidate(def_id
) => Some(def_id
),
216 // If there are *NO* candidates, then there are no impls --
217 // that we know of, anyway. Note that in the case where there
218 // are unbound type variables within the obligation, it might
219 // be the case that you could still satisfy the obligation
220 // from another crate by instantiating the type variables with
221 // a type from another crate that does have an impl. This case
222 // is checked for in `evaluate_stack` (and hence users
223 // who might care about this case, like coherence, should use
225 if candidates
.is_empty() {
226 // If there's an error type, 'downgrade' our result from
227 // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
228 // emitting additional spurious errors, since we're guaranteed
229 // to have emitted at least one.
230 if stack
.obligation
.references_error() {
231 debug
!("no results for error type, treating as ambiguous");
234 return Err(Unimplemented
);
237 // Just one candidate left.
238 self.filter_reservation_impls(candidates
.pop().unwrap().candidate
, stack
.obligation
)
241 #[instrument(skip(self, stack), level = "debug")]
242 pub(super) fn assemble_candidates
<'o
>(
244 stack
: &TraitObligationStack
<'o
, 'tcx
>,
245 ) -> Result
<SelectionCandidateSet
<'tcx
>, SelectionError
<'tcx
>> {
246 let TraitObligationStack { obligation, .. }
= *stack
;
247 let obligation
= &Obligation
{
248 param_env
: obligation
.param_env
,
249 cause
: obligation
.cause
.clone(),
250 recursion_depth
: obligation
.recursion_depth
,
251 predicate
: self.infcx().resolve_vars_if_possible(obligation
.predicate
),
254 if obligation
.predicate
.skip_binder().self_ty().is_ty_var() {
255 debug
!(ty
= ?obligation
.predicate
.skip_binder().self_ty(), "ambiguous inference var or opaque type");
256 // Self is a type variable (e.g., `_: AsRef<str>`).
258 // This is somewhat problematic, as the current scheme can't really
259 // handle it turning to be a projection. This does end up as truly
260 // ambiguous in most cases anyway.
262 // Take the fast path out - this also improves
263 // performance by preventing assemble_candidates_from_impls from
264 // matching every impl for this trait.
265 return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true }
);
268 let mut candidates
= SelectionCandidateSet { vec: Vec::new(), ambiguous: false }
;
270 // The only way to prove a NotImplemented(T: Foo) predicate is via a negative impl.
271 // There are no compiler built-in rules for this.
272 if obligation
.polarity() == ty
::ImplPolarity
::Negative
{
273 self.assemble_candidates_for_trait_alias(obligation
, &mut candidates
);
274 self.assemble_candidates_from_impls(obligation
, &mut candidates
);
276 self.assemble_candidates_for_trait_alias(obligation
, &mut candidates
);
278 // Other bounds. Consider both in-scope bounds from fn decl
279 // and applicable impls. There is a certain set of precedence rules here.
280 let def_id
= obligation
.predicate
.def_id();
281 let lang_items
= self.tcx().lang_items();
283 if lang_items
.copy_trait() == Some(def_id
) {
284 debug
!(obligation_self_ty
= ?obligation
.predicate
.skip_binder().self_ty());
286 // User-defined copy impls are permitted, but only for
287 // structs and enums.
288 self.assemble_candidates_from_impls(obligation
, &mut candidates
);
290 // For other types, we'll use the builtin rules.
291 let copy_conditions
= self.copy_clone_conditions(obligation
);
292 self.assemble_builtin_bound_candidates(copy_conditions
, &mut candidates
);
293 } else if lang_items
.discriminant_kind_trait() == Some(def_id
) {
294 // `DiscriminantKind` is automatically implemented for every type.
295 candidates
.vec
.push(DiscriminantKindCandidate
);
296 } else if lang_items
.pointee_trait() == Some(def_id
) {
297 // `Pointee` is automatically implemented for every type.
298 candidates
.vec
.push(PointeeCandidate
);
299 } else if lang_items
.sized_trait() == Some(def_id
) {
300 // Sized is never implementable by end-users, it is
301 // always automatically computed.
302 let sized_conditions
= self.sized_conditions(obligation
);
303 self.assemble_builtin_bound_candidates(sized_conditions
, &mut candidates
);
304 } else if lang_items
.unsize_trait() == Some(def_id
) {
305 self.assemble_candidates_for_unsizing(obligation
, &mut candidates
);
306 } else if lang_items
.drop_trait() == Some(def_id
)
307 && obligation
.predicate
.is_const_if_const()
309 // holds to make it easier to transition
310 // FIXME(fee1-dead): add a note for selection error of `~const Drop`
311 // when beta is bumped
312 // FIXME: remove this when beta is bumped
316 candidates
.vec
.push(SelectionCandidate
::ConstDestructCandidate(None
))
317 } else if lang_items
.destruct_trait() == Some(def_id
) {
318 self.assemble_const_destruct_candidates(obligation
, &mut candidates
);
320 if lang_items
.clone_trait() == Some(def_id
) {
321 // Same builtin conditions as `Copy`, i.e., every type which has builtin support
322 // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone`
323 // types have builtin support for `Clone`.
324 let clone_conditions
= self.copy_clone_conditions(obligation
);
325 self.assemble_builtin_bound_candidates(clone_conditions
, &mut candidates
);
328 self.assemble_generator_candidates(obligation
, &mut candidates
);
329 self.assemble_closure_candidates(obligation
, &mut candidates
);
330 self.assemble_fn_pointer_candidates(obligation
, &mut candidates
);
331 self.assemble_candidates_from_impls(obligation
, &mut candidates
);
332 self.assemble_candidates_from_object_ty(obligation
, &mut candidates
);
335 self.assemble_candidates_from_projected_tys(obligation
, &mut candidates
);
336 self.assemble_candidates_from_caller_bounds(stack
, &mut candidates
)?
;
337 // Auto implementations have lower priority, so we only
338 // consider triggering a default if there is no other impl that can apply.
339 if candidates
.vec
.is_empty() {
340 self.assemble_candidates_from_auto_impls(obligation
, &mut candidates
);
343 debug
!("candidate list size: {}", candidates
.vec
.len());
347 #[tracing::instrument(level = "debug", skip(self, candidates))]
348 fn assemble_candidates_from_projected_tys(
350 obligation
: &TraitObligation
<'tcx
>,
351 candidates
: &mut SelectionCandidateSet
<'tcx
>,
353 // Before we go into the whole placeholder thing, just
354 // quickly check if the self-type is a projection at all.
355 match obligation
.predicate
.skip_binder().trait_ref
.self_ty().kind() {
356 ty
::Projection(_
) | ty
::Opaque(..) => {}
357 ty
::Infer(ty
::TyVar(_
)) => {
359 obligation
.cause
.span
,
360 "Self=_ should have been handled by assemble_candidates"
368 .probe(|_
| self.match_projection_obligation_against_definition_bounds(obligation
));
370 candidates
.vec
.extend(result
.into_iter().map(ProjectionCandidate
));
373 /// Given an obligation like `<SomeTrait for T>`, searches the obligations that the caller
374 /// supplied to find out whether it is listed among them.
376 /// Never affects the inference environment.
377 #[tracing::instrument(level = "debug", skip(self, stack, candidates))]
378 fn assemble_candidates_from_caller_bounds
<'o
>(
380 stack
: &TraitObligationStack
<'o
, 'tcx
>,
381 candidates
: &mut SelectionCandidateSet
<'tcx
>,
382 ) -> Result
<(), SelectionError
<'tcx
>> {
383 debug
!(?stack
.obligation
);
385 let all_bounds
= stack
390 .filter_map(|o
| o
.to_opt_poly_trait_pred());
392 // Micro-optimization: filter out predicates relating to different traits.
393 let matching_bounds
=
394 all_bounds
.filter(|p
| p
.def_id() == stack
.obligation
.predicate
.def_id());
396 // Keep only those bounds which may apply, and propagate overflow if it occurs.
397 for bound
in matching_bounds
{
398 // FIXME(oli-obk): it is suspicious that we are dropping the constness and
400 let wc
= self.where_clause_may_apply(stack
, bound
.map_bound(|t
| t
.trait_ref
))?
;
402 candidates
.vec
.push(ParamCandidate(bound
));
409 fn assemble_generator_candidates(
411 obligation
: &TraitObligation
<'tcx
>,
412 candidates
: &mut SelectionCandidateSet
<'tcx
>,
414 if self.tcx().lang_items().gen_trait() != Some(obligation
.predicate
.def_id()) {
418 // Okay to skip binder because the substs on generator types never
419 // touch bound regions, they just capture the in-scope
420 // type/region parameters.
421 let self_ty
= obligation
.self_ty().skip_binder();
422 match self_ty
.kind() {
423 ty
::Generator(..) => {
424 debug
!(?self_ty
, ?obligation
, "assemble_generator_candidates",);
426 candidates
.vec
.push(GeneratorCandidate
);
428 ty
::Infer(ty
::TyVar(_
)) => {
429 debug
!("assemble_generator_candidates: ambiguous self-type");
430 candidates
.ambiguous
= true;
436 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
437 /// FnMut<..>` where `X` is a closure type.
439 /// Note: the type parameters on a closure candidate are modeled as *output* type
440 /// parameters and hence do not affect whether this trait is a match or not. They will be
441 /// unified during the confirmation step.
442 fn assemble_closure_candidates(
444 obligation
: &TraitObligation
<'tcx
>,
445 candidates
: &mut SelectionCandidateSet
<'tcx
>,
447 let Some(kind
) = self.tcx().fn_trait_kind_from_lang_item(obligation
.predicate
.def_id()) else {
451 // Okay to skip binder because the substs on closure types never
452 // touch bound regions, they just capture the in-scope
453 // type/region parameters
454 match *obligation
.self_ty().skip_binder().kind() {
455 ty
::Closure(_
, closure_substs
) => {
456 debug
!(?kind
, ?obligation
, "assemble_unboxed_candidates");
457 match self.infcx
.closure_kind(closure_substs
) {
458 Some(closure_kind
) => {
459 debug
!(?closure_kind
, "assemble_unboxed_candidates");
460 if closure_kind
.extends(kind
) {
461 candidates
.vec
.push(ClosureCandidate
);
465 debug
!("assemble_unboxed_candidates: closure_kind not yet known");
466 candidates
.vec
.push(ClosureCandidate
);
470 ty
::Infer(ty
::TyVar(_
)) => {
471 debug
!("assemble_unboxed_closure_candidates: ambiguous self-type");
472 candidates
.ambiguous
= true;
478 /// Implements one of the `Fn()` family for a fn pointer.
479 fn assemble_fn_pointer_candidates(
481 obligation
: &TraitObligation
<'tcx
>,
482 candidates
: &mut SelectionCandidateSet
<'tcx
>,
484 // We provide impl of all fn traits for fn pointers.
485 if self.tcx().fn_trait_kind_from_lang_item(obligation
.predicate
.def_id()).is_none() {
489 // Okay to skip binder because what we are inspecting doesn't involve bound regions.
490 let self_ty
= obligation
.self_ty().skip_binder();
491 match *self_ty
.kind() {
492 ty
::Infer(ty
::TyVar(_
)) => {
493 debug
!("assemble_fn_pointer_candidates: ambiguous self-type");
494 candidates
.ambiguous
= true; // Could wind up being a fn() type.
496 // Provide an impl, but only for suitable `fn` pointers.
499 unsafety
: hir
::Unsafety
::Normal
,
503 } = self_ty
.fn_sig(self.tcx()).skip_binder()
505 candidates
.vec
.push(FnPointerCandidate { is_const: false }
);
508 // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396).
509 ty
::FnDef(def_id
, _
) => {
511 unsafety
: hir
::Unsafety
::Normal
,
515 } = self_ty
.fn_sig(self.tcx()).skip_binder()
517 if self.tcx().codegen_fn_attrs(def_id
).target_features
.is_empty() {
520 .push(FnPointerCandidate { is_const: self.tcx().is_const_fn(def_id) }
);
528 /// Searches for impls that might apply to `obligation`.
529 fn assemble_candidates_from_impls(
531 obligation
: &TraitObligation
<'tcx
>,
532 candidates
: &mut SelectionCandidateSet
<'tcx
>,
534 debug
!(?obligation
, "assemble_candidates_from_impls");
536 // Essentially any user-written impl will match with an error type,
537 // so creating `ImplCandidates` isn't useful. However, we might
538 // end up finding a candidate elsewhere (e.g. a `BuiltinCandidate` for `Sized)
539 // This helps us avoid overflow: see issue #72839
540 // Since compilation is already guaranteed to fail, this is just
541 // to try to show the 'nicest' possible errors to the user.
542 // We don't check for errors in the `ParamEnv` - in practice,
543 // it seems to cause us to be overly aggressive in deciding
544 // to give up searching for candidates, leading to spurious errors.
545 if obligation
.predicate
.references_error() {
549 self.tcx().for_each_relevant_impl(
550 obligation
.predicate
.def_id(),
551 obligation
.predicate
.skip_binder().trait_ref
.self_ty(),
553 self.infcx
.probe(|_
| {
554 if let Ok(_substs
) = self.match_impl(impl_def_id
, obligation
) {
555 candidates
.vec
.push(ImplCandidate(impl_def_id
));
562 fn assemble_candidates_from_auto_impls(
564 obligation
: &TraitObligation
<'tcx
>,
565 candidates
: &mut SelectionCandidateSet
<'tcx
>,
567 // Okay to skip binder here because the tests we do below do not involve bound regions.
568 let self_ty
= obligation
.self_ty().skip_binder();
569 debug
!(?self_ty
, "assemble_candidates_from_auto_impls");
571 let def_id
= obligation
.predicate
.def_id();
573 if self.tcx().trait_is_auto(def_id
) {
574 match self_ty
.kind() {
576 // For object types, we don't know what the closed
577 // over types are. This means we conservatively
578 // say nothing; a candidate may be added by
579 // `assemble_candidates_from_object_ty`.
582 // Since the contents of foreign types is unknown,
583 // we don't add any `..` impl. Default traits could
584 // still be provided by a manual implementation for
585 // this trait and type.
587 ty
::Param(..) | ty
::Projection(..) => {
588 // In these cases, we don't know what the actual
589 // type is. Therefore, we cannot break it down
590 // into its constituent types. So we don't
591 // consider the `..` impl but instead just add no
592 // candidates: this means that typeck will only
593 // succeed if there is another reason to believe
594 // that this obligation holds. That could be a
595 // where-clause or, in the case of an object type,
596 // it could be that the object type lists the
597 // trait (e.g., `Foo+Send : Send`). See
598 // `ui/typeck/typeck-default-trait-impl-send-param.rs`
599 // for an example of a test case that exercises
602 ty
::Infer(ty
::TyVar(_
)) => {
603 // The auto impl might apply; we don't know.
604 candidates
.ambiguous
= true;
606 ty
::Generator(_
, _
, movability
)
607 if self.tcx().lang_items().unpin_trait() == Some(def_id
) =>
610 hir
::Movability
::Static
=> {
611 // Immovable generators are never `Unpin`, so
612 // suppress the normal auto-impl candidate for it.
614 hir
::Movability
::Movable
=> {
615 // Movable generators are always `Unpin`, so add an
616 // unconditional builtin candidate.
617 candidates
.vec
.push(BuiltinCandidate { has_nested: false }
);
622 _
=> candidates
.vec
.push(AutoImplCandidate(def_id
)),
627 /// Searches for impls that might apply to `obligation`.
628 fn assemble_candidates_from_object_ty(
630 obligation
: &TraitObligation
<'tcx
>,
631 candidates
: &mut SelectionCandidateSet
<'tcx
>,
634 self_ty
= ?obligation
.self_ty().skip_binder(),
635 "assemble_candidates_from_object_ty",
638 self.infcx
.probe(|_snapshot
| {
639 // The code below doesn't care about regions, and the
640 // self-ty here doesn't escape this probe, so just erase
642 let self_ty
= self.tcx().erase_late_bound_regions(obligation
.self_ty());
643 let poly_trait_ref
= match self_ty
.kind() {
644 ty
::Dynamic(ref data
, ..) => {
645 if data
.auto_traits().any(|did
| did
== obligation
.predicate
.def_id()) {
647 "assemble_candidates_from_object_ty: matched builtin bound, \
650 candidates
.vec
.push(BuiltinObjectCandidate
);
654 if let Some(principal
) = data
.principal() {
655 if !self.infcx
.tcx
.features().object_safe_for_dispatch
{
656 principal
.with_self_ty(self.tcx(), self_ty
)
657 } else if self.tcx().is_object_safe(principal
.def_id()) {
658 principal
.with_self_ty(self.tcx(), self_ty
)
663 // Only auto trait bounds exist.
667 ty
::Infer(ty
::TyVar(_
)) => {
668 debug
!("assemble_candidates_from_object_ty: ambiguous");
669 candidates
.ambiguous
= true; // could wind up being an object type
675 debug
!(?poly_trait_ref
, "assemble_candidates_from_object_ty");
677 let poly_trait_predicate
= self.infcx().resolve_vars_if_possible(obligation
.predicate
);
678 let placeholder_trait_predicate
=
679 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate
);
681 // Count only those upcast versions that match the trait-ref
682 // we are looking for. Specifically, do not only check for the
683 // correct trait, but also the correct type parameters.
684 // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
685 // but `Foo` is declared as `trait Foo: Bar<u32>`.
686 let candidate_supertraits
= util
::supertraits(self.tcx(), poly_trait_ref
)
688 .filter(|&(_
, upcast_trait_ref
)| {
689 self.infcx
.probe(|_
| {
690 self.match_normalize_trait_ref(
693 placeholder_trait_predicate
.trait_ref
,
698 .map(|(idx
, _
)| ObjectCandidate(idx
));
700 candidates
.vec
.extend(candidate_supertraits
);
704 /// Temporary migration for #89190
705 fn need_migrate_deref_output_trait_object(
708 cause
: &traits
::ObligationCause
<'tcx
>,
709 param_env
: ty
::ParamEnv
<'tcx
>,
710 ) -> Option
<(Ty
<'tcx
>, DefId
)> {
711 let tcx
= self.tcx();
712 if tcx
.features().trait_upcasting
{
717 let trait_ref
= ty
::TraitRef
{
718 def_id
: tcx
.lang_items().deref_trait()?
,
719 substs
: tcx
.mk_substs_trait(ty
, &[]),
722 let obligation
= traits
::Obligation
::new(
725 ty
::Binder
::dummy(trait_ref
).without_const().to_predicate(tcx
),
727 if !self.infcx
.predicate_may_hold(&obligation
) {
731 let mut fulfillcx
= traits
::FulfillmentContext
::new_in_snapshot();
732 let normalized_ty
= fulfillcx
.normalize_projection_type(
736 item_def_id
: tcx
.lang_items().deref_target()?
,
737 substs
: trait_ref
.substs
,
742 let ty
::Dynamic(data
, ..) = normalized_ty
.kind() else {
746 let def_id
= data
.principal_def_id()?
;
748 return Some((normalized_ty
, def_id
));
751 /// Searches for unsizing that might apply to `obligation`.
752 fn assemble_candidates_for_unsizing(
754 obligation
: &TraitObligation
<'tcx
>,
755 candidates
: &mut SelectionCandidateSet
<'tcx
>,
757 // We currently never consider higher-ranked obligations e.g.
758 // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
759 // because they are a priori invalid, and we could potentially add support
760 // for them later, it's just that there isn't really a strong need for it.
761 // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
762 // impl, and those are generally applied to concrete types.
764 // That said, one might try to write a fn with a where clause like
765 // for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
766 // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
767 // Still, you'd be more likely to write that where clause as
769 // so it seems ok if we (conservatively) fail to accept that `Unsize`
770 // obligation above. Should be possible to extend this in the future.
771 let Some(source
) = obligation
.self_ty().no_bound_vars() else {
772 // Don't add any candidates if there are bound regions.
775 let target
= obligation
.predicate
.skip_binder().trait_ref
.substs
.type_at(1);
777 debug
!(?source
, ?target
, "assemble_candidates_for_unsizing");
779 match (source
.kind(), target
.kind()) {
780 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
781 (&ty
::Dynamic(ref data_a
, ..), &ty
::Dynamic(ref data_b
, ..)) => {
782 // Upcast coercions permit several things:
784 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
785 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
786 // 3. Tightening trait to its super traits, eg. `Foo` to `Bar` if `Foo: Bar`
788 // Note that neither of the first two of these changes requires any
789 // change at runtime. The third needs to change pointer metadata at runtime.
791 // We always perform upcasting coercions when we can because of reason
792 // #2 (region bounds).
793 let auto_traits_compatible
= data_b
795 // All of a's auto traits need to be in b's auto traits.
796 .all(|b
| data_a
.auto_traits().any(|a
| a
== b
));
797 if auto_traits_compatible
{
798 let principal_def_id_a
= data_a
.principal_def_id();
799 let principal_def_id_b
= data_b
.principal_def_id();
800 if principal_def_id_a
== principal_def_id_b
{
802 candidates
.vec
.push(BuiltinUnsizeCandidate
);
803 } else if principal_def_id_a
.is_some() && principal_def_id_b
.is_some() {
804 // not casual unsizing, now check whether this is trait upcasting coercion.
805 let principal_a
= data_a
.principal().unwrap();
806 let target_trait_did
= principal_def_id_b
.unwrap();
807 let source_trait_ref
= principal_a
.with_self_ty(self.tcx(), source
);
808 if let Some((deref_output_ty
, deref_output_trait_did
)) = self
809 .need_migrate_deref_output_trait_object(
812 obligation
.param_env
,
815 if deref_output_trait_did
== target_trait_did
{
816 self.tcx().struct_span_lint_hir(
817 DEREF_INTO_DYN_SUPERTRAIT
,
818 obligation
.cause
.body_id
,
819 obligation
.cause
.span
,
822 "`{}` implements `Deref` with supertrait `{}` as output",
832 for (idx
, upcast_trait_ref
) in
833 util
::supertraits(self.tcx(), source_trait_ref
).enumerate()
835 if upcast_trait_ref
.def_id() == target_trait_did
{
836 candidates
.vec
.push(TraitUpcastingUnsizeCandidate(idx
));
844 (_
, &ty
::Dynamic(..)) => {
845 candidates
.vec
.push(BuiltinUnsizeCandidate
);
848 // Ambiguous handling is below `T` -> `Trait`, because inference
849 // variables can still implement `Unsize<Trait>` and nested
850 // obligations will have the final say (likely deferred).
851 (&ty
::Infer(ty
::TyVar(_
)), _
) | (_
, &ty
::Infer(ty
::TyVar(_
))) => {
852 debug
!("assemble_candidates_for_unsizing: ambiguous");
853 candidates
.ambiguous
= true;
857 (&ty
::Array(..), &ty
::Slice(_
)) => {
858 candidates
.vec
.push(BuiltinUnsizeCandidate
);
861 // `Struct<T>` -> `Struct<U>`
862 (&ty
::Adt(def_id_a
, _
), &ty
::Adt(def_id_b
, _
)) if def_id_a
.is_struct() => {
863 if def_id_a
== def_id_b
{
864 candidates
.vec
.push(BuiltinUnsizeCandidate
);
868 // `(.., T)` -> `(.., U)`
869 (&ty
::Tuple(tys_a
), &ty
::Tuple(tys_b
)) => {
870 if tys_a
.len() == tys_b
.len() {
871 candidates
.vec
.push(BuiltinUnsizeCandidate
);
879 #[tracing::instrument(level = "debug", skip(self, obligation, candidates))]
880 fn assemble_candidates_for_trait_alias(
882 obligation
: &TraitObligation
<'tcx
>,
883 candidates
: &mut SelectionCandidateSet
<'tcx
>,
885 // Okay to skip binder here because the tests we do below do not involve bound regions.
886 let self_ty
= obligation
.self_ty().skip_binder();
889 let def_id
= obligation
.predicate
.def_id();
891 if self.tcx().is_trait_alias(def_id
) {
892 candidates
.vec
.push(TraitAliasCandidate(def_id
));
896 /// Assembles the trait which are built-in to the language itself:
897 /// `Copy`, `Clone` and `Sized`.
898 #[tracing::instrument(level = "debug", skip(self, candidates))]
899 fn assemble_builtin_bound_candidates(
901 conditions
: BuiltinImplConditions
<'tcx
>,
902 candidates
: &mut SelectionCandidateSet
<'tcx
>,
905 BuiltinImplConditions
::Where(nested
) => {
908 .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() }
);
910 BuiltinImplConditions
::None
=> {}
911 BuiltinImplConditions
::Ambiguous
=> {
912 candidates
.ambiguous
= true;
917 fn assemble_const_destruct_candidates(
919 obligation
: &TraitObligation
<'tcx
>,
920 candidates
: &mut SelectionCandidateSet
<'tcx
>,
922 // If the predicate is `~const Destruct` in a non-const environment, we don't actually need
923 // to check anything. We'll short-circuit checking any obligations in confirmation, too.
924 if !obligation
.is_const() {
925 candidates
.vec
.push(ConstDestructCandidate(None
));
929 let self_ty
= self.infcx().shallow_resolve(obligation
.self_ty());
930 match self_ty
.skip_binder().kind() {
937 | ty
::Projection(_
) => {
938 // We don't know if these are `~const Destruct`, at least
939 // not structurally... so don't push a candidate.
947 | ty
::Infer(ty
::IntVar(_
))
948 | ty
::Infer(ty
::FloatVar(_
))
961 | ty
::GeneratorWitness(_
) => {
962 // These are built-in, and cannot have a custom `impl const Destruct`.
963 candidates
.vec
.push(ConstDestructCandidate(None
));
967 // Find a custom `impl Drop` impl, if it exists
968 let relevant_impl
= self.tcx().find_map_relevant_impl(
969 self.tcx().require_lang_item(LangItem
::Drop
, None
),
970 obligation
.predicate
.skip_binder().trait_ref
.self_ty(),
974 if let Some(impl_def_id
) = relevant_impl
{
975 // Check that `impl Drop` is actually const, if there is a custom impl
976 if self.tcx().impl_constness(impl_def_id
) == hir
::Constness
::Const
{
977 candidates
.vec
.push(ConstDestructCandidate(Some(impl_def_id
)));
980 // Otherwise check the ADT like a built-in type (structurally)
981 candidates
.vec
.push(ConstDestructCandidate(None
));
986 candidates
.ambiguous
= true;