]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / compiler / rustc_trait_selection / src / traits / select / candidate_assembly.rs
1 //! Candidate assembly.
2 //!
3 //! The selection process begins by examining all in-scope impls,
4 //! caller obligations, and so forth and assembling a list of
5 //! candidates. See the [rustc dev guide] for more details.
6 //!
7 //! [rustc dev guide]:https://rustc-dev-guide.rust-lang.org/traits/resolution.html#candidate-assembly
8 use hir::LangItem;
9 use rustc_hir as hir;
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;
17
18 use crate::traits;
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};
23
24 use super::BuiltinImplConditions;
25 use super::IntercrateAmbiguityCause;
26 use super::OverflowError;
27 use super::SelectionCandidate::{self, *};
28 use super::{EvaluatedCandidate, SelectionCandidateSet, SelectionContext, TraitObligationStack};
29
30 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
31 #[instrument(level = "debug", skip(self))]
32 pub(super) fn candidate_from_obligation<'o>(
33 &mut self,
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)?;
39
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());
47
48 if let Some(c) =
49 self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
50 {
51 debug!(candidate = ?c, "CACHE HIT");
52 return c;
53 }
54
55 // If no match, compute result and insert into cache.
56 //
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));
63
64 debug!(?candidate, "CACHE MISS");
65 self.insert_candidate_cache(
66 stack.obligation.param_env,
67 cache_fresh_trait_pred,
68 dep_node,
69 candidate.clone(),
70 );
71 candidate
72 }
73
74 fn candidate_from_obligation_no_cache<'o>(
75 &mut self,
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;
85
86 for c in candidate_set.vec.iter() {
87 if self.evaluate_candidate(stack, &c)?.may_apply() {
88 no_candidates_apply = false;
89 break;
90 }
91 }
92
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())
100 } else {
101 None
102 };
103 (trait_desc, self_desc)
104 });
105 let cause = if let Conflict::Upstream = conflict {
106 IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
107 } else {
108 IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
109 };
110 debug!(?cause, "evaluate_stack: pushing cause");
111 self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
112 }
113 }
114 }
115 return Ok(None);
116 }
117
118 let candidate_set = self.assemble_candidates(stack)?;
119
120 if candidate_set.ambiguous {
121 debug!("candidate set contains ambig");
122 return Ok(None);
123 }
124
125 let candidates = candidate_set.vec;
126
127 debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
128
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.
137
138 let mut candidates = self.filter_impls(candidates, stack.obligation);
139
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:
146 //
147 // impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
148 //
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);
156 }
157
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
161 .into_iter()
162 .map(|c| match self.evaluate_candidate(stack, &c) {
163 Ok(eval) if eval.may_apply() => {
164 Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
165 }
166 Ok(_) => Ok(None),
167 Err(OverflowError::Canonical) => Err(Overflow(OverflowError::Canonical)),
168 Err(OverflowError::ErrorReporting) => Err(ErrorReporting),
169 Err(OverflowError::Error(e)) => Err(Overflow(OverflowError::Error(e))),
170 })
171 .flat_map(Result::transpose)
172 .collect::<Result<Vec<_>, _>>()?;
173
174 debug!(?stack, ?candidates, "winnowed to {} candidates", candidates.len());
175
176 let needs_infer = stack.obligation.predicate.has_infer_types_or_consts();
177
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 {
182 let mut i = 0;
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(
186 &candidates[i],
187 &candidates[j],
188 needs_infer,
189 )
190 });
191 if is_dup {
192 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
193 candidates.swap_remove(i);
194 } else {
195 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
196 i += 1;
197
198 // If there are *STILL* multiple candidates, give up
199 // and report ambiguity.
200 if i > 1 {
201 debug!("multiple matches, ambig");
202 return Err(Ambiguous(
203 candidates
204 .into_iter()
205 .filter_map(|c| match c.candidate {
206 SelectionCandidate::ImplCandidate(def_id) => Some(def_id),
207 _ => None,
208 })
209 .collect(),
210 ));
211 }
212 }
213 }
214 }
215
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
224 // that function).
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");
232 return Ok(None);
233 }
234 return Err(Unimplemented);
235 }
236
237 // Just one candidate left.
238 self.filter_reservation_impls(candidates.pop().unwrap().candidate, stack.obligation)
239 }
240
241 #[instrument(skip(self, stack), level = "debug")]
242 pub(super) fn assemble_candidates<'o>(
243 &mut self,
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),
252 };
253
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>`).
257 //
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.
261 //
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 });
266 }
267
268 let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
269
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);
275 } else {
276 self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
277
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();
282
283 if lang_items.copy_trait() == Some(def_id) {
284 debug!(obligation_self_ty = ?obligation.predicate.skip_binder().self_ty());
285
286 // User-defined copy impls are permitted, but only for
287 // structs and enums.
288 self.assemble_candidates_from_impls(obligation, &mut candidates);
289
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()
308 {
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
313 #[cfg(bootstrap)]
314 {}
315
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);
319 } else {
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);
326 }
327
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);
333 }
334
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);
341 }
342 }
343 debug!("candidate list size: {}", candidates.vec.len());
344 Ok(candidates)
345 }
346
347 #[tracing::instrument(level = "debug", skip(self, candidates))]
348 fn assemble_candidates_from_projected_tys(
349 &mut self,
350 obligation: &TraitObligation<'tcx>,
351 candidates: &mut SelectionCandidateSet<'tcx>,
352 ) {
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(_)) => {
358 span_bug!(
359 obligation.cause.span,
360 "Self=_ should have been handled by assemble_candidates"
361 );
362 }
363 _ => return,
364 }
365
366 let result = self
367 .infcx
368 .probe(|_| self.match_projection_obligation_against_definition_bounds(obligation));
369
370 candidates.vec.extend(result.into_iter().map(ProjectionCandidate));
371 }
372
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.
375 ///
376 /// Never affects the inference environment.
377 #[tracing::instrument(level = "debug", skip(self, stack, candidates))]
378 fn assemble_candidates_from_caller_bounds<'o>(
379 &mut self,
380 stack: &TraitObligationStack<'o, 'tcx>,
381 candidates: &mut SelectionCandidateSet<'tcx>,
382 ) -> Result<(), SelectionError<'tcx>> {
383 debug!(?stack.obligation);
384
385 let all_bounds = stack
386 .obligation
387 .param_env
388 .caller_bounds()
389 .iter()
390 .filter_map(|o| o.to_opt_poly_trait_pred());
391
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());
395
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
399 // polarity here.
400 let wc = self.where_clause_may_apply(stack, bound.map_bound(|t| t.trait_ref))?;
401 if wc.may_apply() {
402 candidates.vec.push(ParamCandidate(bound));
403 }
404 }
405
406 Ok(())
407 }
408
409 fn assemble_generator_candidates(
410 &mut self,
411 obligation: &TraitObligation<'tcx>,
412 candidates: &mut SelectionCandidateSet<'tcx>,
413 ) {
414 if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
415 return;
416 }
417
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",);
425
426 candidates.vec.push(GeneratorCandidate);
427 }
428 ty::Infer(ty::TyVar(_)) => {
429 debug!("assemble_generator_candidates: ambiguous self-type");
430 candidates.ambiguous = true;
431 }
432 _ => {}
433 }
434 }
435
436 /// Checks for the artificial impl that the compiler will create for an obligation like `X :
437 /// FnMut<..>` where `X` is a closure type.
438 ///
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(
443 &mut self,
444 obligation: &TraitObligation<'tcx>,
445 candidates: &mut SelectionCandidateSet<'tcx>,
446 ) {
447 let Some(kind) = self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) else {
448 return;
449 };
450
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);
462 }
463 }
464 None => {
465 debug!("assemble_unboxed_candidates: closure_kind not yet known");
466 candidates.vec.push(ClosureCandidate);
467 }
468 }
469 }
470 ty::Infer(ty::TyVar(_)) => {
471 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
472 candidates.ambiguous = true;
473 }
474 _ => {}
475 }
476 }
477
478 /// Implements one of the `Fn()` family for a fn pointer.
479 fn assemble_fn_pointer_candidates(
480 &mut self,
481 obligation: &TraitObligation<'tcx>,
482 candidates: &mut SelectionCandidateSet<'tcx>,
483 ) {
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() {
486 return;
487 }
488
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.
495 }
496 // Provide an impl, but only for suitable `fn` pointers.
497 ty::FnPtr(_) => {
498 if let ty::FnSig {
499 unsafety: hir::Unsafety::Normal,
500 abi: Abi::Rust,
501 c_variadic: false,
502 ..
503 } = self_ty.fn_sig(self.tcx()).skip_binder()
504 {
505 candidates.vec.push(FnPointerCandidate { is_const: false });
506 }
507 }
508 // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396).
509 ty::FnDef(def_id, _) => {
510 if let ty::FnSig {
511 unsafety: hir::Unsafety::Normal,
512 abi: Abi::Rust,
513 c_variadic: false,
514 ..
515 } = self_ty.fn_sig(self.tcx()).skip_binder()
516 {
517 if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() {
518 candidates
519 .vec
520 .push(FnPointerCandidate { is_const: self.tcx().is_const_fn(def_id) });
521 }
522 }
523 }
524 _ => {}
525 }
526 }
527
528 /// Searches for impls that might apply to `obligation`.
529 fn assemble_candidates_from_impls(
530 &mut self,
531 obligation: &TraitObligation<'tcx>,
532 candidates: &mut SelectionCandidateSet<'tcx>,
533 ) {
534 debug!(?obligation, "assemble_candidates_from_impls");
535
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() {
546 return;
547 }
548
549 self.tcx().for_each_relevant_impl(
550 obligation.predicate.def_id(),
551 obligation.predicate.skip_binder().trait_ref.self_ty(),
552 |impl_def_id| {
553 self.infcx.probe(|_| {
554 if let Ok(_substs) = self.match_impl(impl_def_id, obligation) {
555 candidates.vec.push(ImplCandidate(impl_def_id));
556 }
557 });
558 },
559 );
560 }
561
562 fn assemble_candidates_from_auto_impls(
563 &mut self,
564 obligation: &TraitObligation<'tcx>,
565 candidates: &mut SelectionCandidateSet<'tcx>,
566 ) {
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");
570
571 let def_id = obligation.predicate.def_id();
572
573 if self.tcx().trait_is_auto(def_id) {
574 match self_ty.kind() {
575 ty::Dynamic(..) => {
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`.
580 }
581 ty::Foreign(..) => {
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.
586 }
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
600 // this path.
601 }
602 ty::Infer(ty::TyVar(_)) => {
603 // The auto impl might apply; we don't know.
604 candidates.ambiguous = true;
605 }
606 ty::Generator(_, _, movability)
607 if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
608 {
609 match movability {
610 hir::Movability::Static => {
611 // Immovable generators are never `Unpin`, so
612 // suppress the normal auto-impl candidate for it.
613 }
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 });
618 }
619 }
620 }
621
622 _ => candidates.vec.push(AutoImplCandidate(def_id)),
623 }
624 }
625 }
626
627 /// Searches for impls that might apply to `obligation`.
628 fn assemble_candidates_from_object_ty(
629 &mut self,
630 obligation: &TraitObligation<'tcx>,
631 candidates: &mut SelectionCandidateSet<'tcx>,
632 ) {
633 debug!(
634 self_ty = ?obligation.self_ty().skip_binder(),
635 "assemble_candidates_from_object_ty",
636 );
637
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
641 // any LBR.
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()) {
646 debug!(
647 "assemble_candidates_from_object_ty: matched builtin bound, \
648 pushing candidate"
649 );
650 candidates.vec.push(BuiltinObjectCandidate);
651 return;
652 }
653
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)
659 } else {
660 return;
661 }
662 } else {
663 // Only auto trait bounds exist.
664 return;
665 }
666 }
667 ty::Infer(ty::TyVar(_)) => {
668 debug!("assemble_candidates_from_object_ty: ambiguous");
669 candidates.ambiguous = true; // could wind up being an object type
670 return;
671 }
672 _ => return,
673 };
674
675 debug!(?poly_trait_ref, "assemble_candidates_from_object_ty");
676
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);
680
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)
687 .enumerate()
688 .filter(|&(_, upcast_trait_ref)| {
689 self.infcx.probe(|_| {
690 self.match_normalize_trait_ref(
691 obligation,
692 upcast_trait_ref,
693 placeholder_trait_predicate.trait_ref,
694 )
695 .is_ok()
696 })
697 })
698 .map(|(idx, _)| ObjectCandidate(idx));
699
700 candidates.vec.extend(candidate_supertraits);
701 })
702 }
703
704 /// Temporary migration for #89190
705 fn need_migrate_deref_output_trait_object(
706 &mut self,
707 ty: Ty<'tcx>,
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 {
713 return None;
714 }
715
716 // <ty as Deref>
717 let trait_ref = ty::TraitRef {
718 def_id: tcx.lang_items().deref_trait()?,
719 substs: tcx.mk_substs_trait(ty, &[]),
720 };
721
722 let obligation = traits::Obligation::new(
723 cause.clone(),
724 param_env,
725 ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
726 );
727 if !self.infcx.predicate_may_hold(&obligation) {
728 return None;
729 }
730
731 let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
732 let normalized_ty = fulfillcx.normalize_projection_type(
733 &self.infcx,
734 param_env,
735 ty::ProjectionTy {
736 item_def_id: tcx.lang_items().deref_target()?,
737 substs: trait_ref.substs,
738 },
739 cause.clone(),
740 );
741
742 let ty::Dynamic(data, ..) = normalized_ty.kind() else {
743 return None;
744 };
745
746 let def_id = data.principal_def_id()?;
747
748 return Some((normalized_ty, def_id));
749 }
750
751 /// Searches for unsizing that might apply to `obligation`.
752 fn assemble_candidates_for_unsizing(
753 &mut self,
754 obligation: &TraitObligation<'tcx>,
755 candidates: &mut SelectionCandidateSet<'tcx>,
756 ) {
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.
763 //
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
768 // T: Trait
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.
773 return;
774 };
775 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
776
777 debug!(?source, ?target, "assemble_candidates_for_unsizing");
778
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:
783 //
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`
787 //
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.
790 //
791 // We always perform upcasting coercions when we can because of reason
792 // #2 (region bounds).
793 let auto_traits_compatible = data_b
794 .auto_traits()
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 {
801 // no cyclic
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(
810 source,
811 &obligation.cause,
812 obligation.param_env,
813 )
814 {
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,
820 |lint| {
821 lint.build(&format!(
822 "`{}` implements `Deref` with supertrait `{}` as output",
823 source,
824 deref_output_ty
825 )).emit();
826 },
827 );
828 return;
829 }
830 }
831
832 for (idx, upcast_trait_ref) in
833 util::supertraits(self.tcx(), source_trait_ref).enumerate()
834 {
835 if upcast_trait_ref.def_id() == target_trait_did {
836 candidates.vec.push(TraitUpcastingUnsizeCandidate(idx));
837 }
838 }
839 }
840 }
841 }
842
843 // `T` -> `Trait`
844 (_, &ty::Dynamic(..)) => {
845 candidates.vec.push(BuiltinUnsizeCandidate);
846 }
847
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;
854 }
855
856 // `[T; n]` -> `[T]`
857 (&ty::Array(..), &ty::Slice(_)) => {
858 candidates.vec.push(BuiltinUnsizeCandidate);
859 }
860
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);
865 }
866 }
867
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);
872 }
873 }
874
875 _ => {}
876 };
877 }
878
879 #[tracing::instrument(level = "debug", skip(self, obligation, candidates))]
880 fn assemble_candidates_for_trait_alias(
881 &mut self,
882 obligation: &TraitObligation<'tcx>,
883 candidates: &mut SelectionCandidateSet<'tcx>,
884 ) {
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();
887 debug!(?self_ty);
888
889 let def_id = obligation.predicate.def_id();
890
891 if self.tcx().is_trait_alias(def_id) {
892 candidates.vec.push(TraitAliasCandidate(def_id));
893 }
894 }
895
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(
900 &mut self,
901 conditions: BuiltinImplConditions<'tcx>,
902 candidates: &mut SelectionCandidateSet<'tcx>,
903 ) {
904 match conditions {
905 BuiltinImplConditions::Where(nested) => {
906 candidates
907 .vec
908 .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
909 }
910 BuiltinImplConditions::None => {}
911 BuiltinImplConditions::Ambiguous => {
912 candidates.ambiguous = true;
913 }
914 }
915 }
916
917 fn assemble_const_destruct_candidates(
918 &mut self,
919 obligation: &TraitObligation<'tcx>,
920 candidates: &mut SelectionCandidateSet<'tcx>,
921 ) {
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));
926 return;
927 }
928
929 let self_ty = self.infcx().shallow_resolve(obligation.self_ty());
930 match self_ty.skip_binder().kind() {
931 ty::Opaque(..)
932 | ty::Dynamic(..)
933 | ty::Error(_)
934 | ty::Bound(..)
935 | ty::Param(_)
936 | ty::Placeholder(_)
937 | ty::Projection(_) => {
938 // We don't know if these are `~const Destruct`, at least
939 // not structurally... so don't push a candidate.
940 }
941
942 ty::Bool
943 | ty::Char
944 | ty::Int(_)
945 | ty::Uint(_)
946 | ty::Float(_)
947 | ty::Infer(ty::IntVar(_))
948 | ty::Infer(ty::FloatVar(_))
949 | ty::Str
950 | ty::RawPtr(_)
951 | ty::Ref(..)
952 | ty::FnDef(..)
953 | ty::FnPtr(_)
954 | ty::Never
955 | ty::Foreign(_)
956 | ty::Array(..)
957 | ty::Slice(_)
958 | ty::Closure(..)
959 | ty::Generator(..)
960 | ty::Tuple(_)
961 | ty::GeneratorWitness(_) => {
962 // These are built-in, and cannot have a custom `impl const Destruct`.
963 candidates.vec.push(ConstDestructCandidate(None));
964 }
965
966 ty::Adt(..) => {
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(),
971 Some,
972 );
973
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)));
978 }
979 } else {
980 // Otherwise check the ADT like a built-in type (structurally)
981 candidates.vec.push(ConstDestructCandidate(None));
982 }
983 }
984
985 ty::Infer(_) => {
986 candidates.ambiguous = true;
987 }
988 }
989 }
990 }