]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
Auto merge of #95399 - gilescope:plan_b, r=scottmcm
[rust.git] / compiler / rustc_trait_selection / src / traits / select / candidate_assembly.rs
1 //! Candidate assembly.
2 //!
3 //! The selection process begins by examining all in-scope impls,
4 //! caller obligations, and so forth and assembling a list of
5 //! candidates. See the [rustc dev guide] for more details.
6 //!
7 //! [rustc dev guide]:https://rustc-dev-guide.rust-lang.org/traits/resolution.html#candidate-assembly
8 use 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         let sized_predicate = self.tcx().lang_items().sized_trait()
179             == Some(stack.obligation.predicate.skip_binder().def_id());
180
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 {
185             let mut i = 0;
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(
189                         sized_predicate,
190                         &candidates[i],
191                         &candidates[j],
192                         needs_infer,
193                     )
194                 });
195                 if is_dup {
196                     debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
197                     candidates.swap_remove(i);
198                 } else {
199                     debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
200                     i += 1;
201
202                     // If there are *STILL* multiple candidates, give up
203                     // and report ambiguity.
204                     if i > 1 {
205                         debug!("multiple matches, ambig");
206                         return Err(Ambiguous(
207                             candidates
208                                 .into_iter()
209                                 .filter_map(|c| match c.candidate {
210                                     SelectionCandidate::ImplCandidate(def_id) => Some(def_id),
211                                     _ => None,
212                                 })
213                                 .collect(),
214                         ));
215                     }
216                 }
217             }
218         }
219
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
228         // that function).
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");
236                 return Ok(None);
237             }
238             return Err(Unimplemented);
239         }
240
241         // Just one candidate left.
242         self.filter_reservation_impls(candidates.pop().unwrap().candidate, stack.obligation)
243     }
244
245     #[instrument(skip(self, stack), level = "debug")]
246     pub(super) fn assemble_candidates<'o>(
247         &mut self,
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),
256         };
257
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>`).
261             //
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.
265             //
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 });
270         }
271
272         let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
273
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);
279         } else {
280             self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
281
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();
286
287             if lang_items.copy_trait() == Some(def_id) {
288                 debug!(obligation_self_ty = ?obligation.predicate.skip_binder().self_ty());
289
290                 // User-defined copy impls are permitted, but only for
291                 // structs and enums.
292                 self.assemble_candidates_from_impls(obligation, &mut candidates);
293
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);
312             } else {
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);
319                 }
320
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);
326             }
327
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);
334             }
335         }
336         debug!("candidate list size: {}", candidates.vec.len());
337         Ok(candidates)
338     }
339
340     #[tracing::instrument(level = "debug", skip(self, candidates))]
341     fn assemble_candidates_from_projected_tys(
342         &mut self,
343         obligation: &TraitObligation<'tcx>,
344         candidates: &mut SelectionCandidateSet<'tcx>,
345     ) {
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(_)) => {
351                 span_bug!(
352                     obligation.cause.span,
353                     "Self=_ should have been handled by assemble_candidates"
354                 );
355             }
356             _ => return,
357         }
358
359         let result = self
360             .infcx
361             .probe(|_| self.match_projection_obligation_against_definition_bounds(obligation));
362
363         candidates.vec.extend(result.into_iter().map(ProjectionCandidate));
364     }
365
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.
368     ///
369     /// Never affects the inference environment.
370     #[tracing::instrument(level = "debug", skip(self, stack, candidates))]
371     fn assemble_candidates_from_caller_bounds<'o>(
372         &mut self,
373         stack: &TraitObligationStack<'o, 'tcx>,
374         candidates: &mut SelectionCandidateSet<'tcx>,
375     ) -> Result<(), SelectionError<'tcx>> {
376         debug!(?stack.obligation);
377
378         let all_bounds = stack
379             .obligation
380             .param_env
381             .caller_bounds()
382             .iter()
383             .filter_map(|o| o.to_opt_poly_trait_pred());
384
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());
388
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
392             // polarity here.
393             let wc = self.where_clause_may_apply(stack, bound.map_bound(|t| t.trait_ref))?;
394             if wc.may_apply() {
395                 candidates.vec.push(ParamCandidate(bound));
396             }
397         }
398
399         Ok(())
400     }
401
402     fn assemble_generator_candidates(
403         &mut self,
404         obligation: &TraitObligation<'tcx>,
405         candidates: &mut SelectionCandidateSet<'tcx>,
406     ) {
407         if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
408             return;
409         }
410
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",);
418
419                 candidates.vec.push(GeneratorCandidate);
420             }
421             ty::Infer(ty::TyVar(_)) => {
422                 debug!("assemble_generator_candidates: ambiguous self-type");
423                 candidates.ambiguous = true;
424             }
425             _ => {}
426         }
427     }
428
429     /// Checks for the artificial impl that the compiler will create for an obligation like `X :
430     /// FnMut<..>` where `X` is a closure type.
431     ///
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(
436         &mut self,
437         obligation: &TraitObligation<'tcx>,
438         candidates: &mut SelectionCandidateSet<'tcx>,
439     ) {
440         let Some(kind) = self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) else {
441             return;
442         };
443
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);
455                         }
456                     }
457                     None => {
458                         debug!("assemble_unboxed_candidates: closure_kind not yet known");
459                         candidates.vec.push(ClosureCandidate);
460                     }
461                 }
462             }
463             ty::Infer(ty::TyVar(_)) => {
464                 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
465                 candidates.ambiguous = true;
466             }
467             _ => {}
468         }
469     }
470
471     /// Implements one of the `Fn()` family for a fn pointer.
472     fn assemble_fn_pointer_candidates(
473         &mut self,
474         obligation: &TraitObligation<'tcx>,
475         candidates: &mut SelectionCandidateSet<'tcx>,
476     ) {
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() {
479             return;
480         }
481
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.
488             }
489             // Provide an impl, but only for suitable `fn` pointers.
490             ty::FnPtr(_) => {
491                 if let ty::FnSig {
492                     unsafety: hir::Unsafety::Normal,
493                     abi: Abi::Rust,
494                     c_variadic: false,
495                     ..
496                 } = self_ty.fn_sig(self.tcx()).skip_binder()
497                 {
498                     candidates.vec.push(FnPointerCandidate { is_const: false });
499                 }
500             }
501             // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396).
502             ty::FnDef(def_id, _) => {
503                 if let ty::FnSig {
504                     unsafety: hir::Unsafety::Normal,
505                     abi: Abi::Rust,
506                     c_variadic: false,
507                     ..
508                 } = self_ty.fn_sig(self.tcx()).skip_binder()
509                 {
510                     if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() {
511                         candidates
512                             .vec
513                             .push(FnPointerCandidate { is_const: self.tcx().is_const_fn(def_id) });
514                     }
515                 }
516             }
517             _ => {}
518         }
519     }
520
521     /// Searches for impls that might apply to `obligation`.
522     fn assemble_candidates_from_impls(
523         &mut self,
524         obligation: &TraitObligation<'tcx>,
525         candidates: &mut SelectionCandidateSet<'tcx>,
526     ) {
527         debug!(?obligation, "assemble_candidates_from_impls");
528
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() {
539             return;
540         }
541
542         self.tcx().for_each_relevant_impl(
543             obligation.predicate.def_id(),
544             obligation.predicate.skip_binder().trait_ref.self_ty(),
545             |impl_def_id| {
546                 self.infcx.probe(|_| {
547                     if let Ok(_substs) = self.match_impl(impl_def_id, obligation) {
548                         candidates.vec.push(ImplCandidate(impl_def_id));
549                     }
550                 });
551             },
552         );
553     }
554
555     fn assemble_candidates_from_auto_impls(
556         &mut self,
557         obligation: &TraitObligation<'tcx>,
558         candidates: &mut SelectionCandidateSet<'tcx>,
559     ) {
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");
563
564         let def_id = obligation.predicate.def_id();
565
566         if self.tcx().trait_is_auto(def_id) {
567             match self_ty.kind() {
568                 ty::Dynamic(..) => {
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`.
573                 }
574                 ty::Foreign(..) => {
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.
579                 }
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
593                     // this path.
594                 }
595                 ty::Infer(ty::TyVar(_)) => {
596                     // The auto impl might apply; we don't know.
597                     candidates.ambiguous = true;
598                 }
599                 ty::Generator(_, _, movability)
600                     if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
601                 {
602                     match movability {
603                         hir::Movability::Static => {
604                             // Immovable generators are never `Unpin`, so
605                             // suppress the normal auto-impl candidate for it.
606                         }
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 });
611                         }
612                     }
613                 }
614
615                 _ => candidates.vec.push(AutoImplCandidate(def_id)),
616             }
617         }
618     }
619
620     /// Searches for impls that might apply to `obligation`.
621     fn assemble_candidates_from_object_ty(
622         &mut self,
623         obligation: &TraitObligation<'tcx>,
624         candidates: &mut SelectionCandidateSet<'tcx>,
625     ) {
626         debug!(
627             self_ty = ?obligation.self_ty().skip_binder(),
628             "assemble_candidates_from_object_ty",
629         );
630
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
634             // any LBR.
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()) {
639                         debug!(
640                             "assemble_candidates_from_object_ty: matched builtin bound, \
641                              pushing candidate"
642                         );
643                         candidates.vec.push(BuiltinObjectCandidate);
644                         return;
645                     }
646
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)
652                         } else {
653                             return;
654                         }
655                     } else {
656                         // Only auto trait bounds exist.
657                         return;
658                     }
659                 }
660                 ty::Infer(ty::TyVar(_)) => {
661                     debug!("assemble_candidates_from_object_ty: ambiguous");
662                     candidates.ambiguous = true; // could wind up being an object type
663                     return;
664                 }
665                 _ => return,
666             };
667
668             debug!(?poly_trait_ref, "assemble_candidates_from_object_ty");
669
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);
673
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)
680                 .enumerate()
681                 .filter(|&(_, upcast_trait_ref)| {
682                     self.infcx.probe(|_| {
683                         self.match_normalize_trait_ref(
684                             obligation,
685                             upcast_trait_ref,
686                             placeholder_trait_predicate.trait_ref,
687                         )
688                         .is_ok()
689                     })
690                 })
691                 .map(|(idx, _)| ObjectCandidate(idx));
692
693             candidates.vec.extend(candidate_supertraits);
694         })
695     }
696
697     /// Temporary migration for #89190
698     fn need_migrate_deref_output_trait_object(
699         &mut self,
700         ty: Ty<'tcx>,
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 {
706             return None;
707         }
708
709         // <ty as Deref>
710         let trait_ref = ty::TraitRef {
711             def_id: tcx.lang_items().deref_trait()?,
712             substs: tcx.mk_substs_trait(ty, &[]),
713         };
714
715         let obligation = traits::Obligation::new(
716             cause.clone(),
717             param_env,
718             ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
719         );
720         if !self.infcx.predicate_may_hold(&obligation) {
721             return None;
722         }
723
724         let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
725         let normalized_ty = fulfillcx.normalize_projection_type(
726             &self.infcx,
727             param_env,
728             ty::ProjectionTy {
729                 item_def_id: tcx.lang_items().deref_target()?,
730                 substs: trait_ref.substs,
731             },
732             cause.clone(),
733         );
734
735         let ty::Dynamic(data, ..) = normalized_ty.kind() else {
736             return None;
737         };
738
739         let def_id = data.principal_def_id()?;
740
741         return Some((normalized_ty, def_id));
742     }
743
744     /// Searches for unsizing that might apply to `obligation`.
745     fn assemble_candidates_for_unsizing(
746         &mut self,
747         obligation: &TraitObligation<'tcx>,
748         candidates: &mut SelectionCandidateSet<'tcx>,
749     ) {
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.
756         //
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
761         //     T: Trait
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.
766             return;
767         };
768         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
769
770         debug!(?source, ?target, "assemble_candidates_for_unsizing");
771
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:
776                 //
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`
780                 //
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.
783                 //
784                 // We always perform upcasting coercions when we can because of reason
785                 // #2 (region bounds).
786                 let auto_traits_compatible = data_b
787                     .auto_traits()
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 {
794                         // no cyclic
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(
803                                 source,
804                                 &obligation.cause,
805                                 obligation.param_env,
806                             )
807                         {
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,
813                                     |lint| {
814                                         lint.build(&format!(
815                                             "`{}` implements `Deref` with supertrait `{}` as output",
816                                             source,
817                                             deref_output_ty
818                                         )).emit();
819                                     },
820                                 );
821                                 return;
822                             }
823                         }
824
825                         for (idx, upcast_trait_ref) in
826                             util::supertraits(self.tcx(), source_trait_ref).enumerate()
827                         {
828                             if upcast_trait_ref.def_id() == target_trait_did {
829                                 candidates.vec.push(TraitUpcastingUnsizeCandidate(idx));
830                             }
831                         }
832                     }
833                 }
834             }
835
836             // `T` -> `Trait`
837             (_, &ty::Dynamic(..)) => {
838                 candidates.vec.push(BuiltinUnsizeCandidate);
839             }
840
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;
847             }
848
849             // `[T; n]` -> `[T]`
850             (&ty::Array(..), &ty::Slice(_)) => {
851                 candidates.vec.push(BuiltinUnsizeCandidate);
852             }
853
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);
858                 }
859             }
860
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);
865                 }
866             }
867
868             _ => {}
869         };
870     }
871
872     #[tracing::instrument(level = "debug", skip(self, obligation, candidates))]
873     fn assemble_candidates_for_trait_alias(
874         &mut self,
875         obligation: &TraitObligation<'tcx>,
876         candidates: &mut SelectionCandidateSet<'tcx>,
877     ) {
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();
880         debug!(?self_ty);
881
882         let def_id = obligation.predicate.def_id();
883
884         if self.tcx().is_trait_alias(def_id) {
885             candidates.vec.push(TraitAliasCandidate(def_id));
886         }
887     }
888
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(
893         &mut self,
894         conditions: BuiltinImplConditions<'tcx>,
895         candidates: &mut SelectionCandidateSet<'tcx>,
896     ) {
897         match conditions {
898             BuiltinImplConditions::Where(nested) => {
899                 candidates
900                     .vec
901                     .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
902             }
903             BuiltinImplConditions::None => {}
904             BuiltinImplConditions::Ambiguous => {
905                 candidates.ambiguous = true;
906             }
907         }
908     }
909
910     fn assemble_const_destruct_candidates(
911         &mut self,
912         obligation: &TraitObligation<'tcx>,
913         candidates: &mut SelectionCandidateSet<'tcx>,
914     ) {
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));
919             return;
920         }
921
922         let self_ty = self.infcx().shallow_resolve(obligation.self_ty());
923         match self_ty.skip_binder().kind() {
924             ty::Opaque(..)
925             | ty::Dynamic(..)
926             | ty::Error(_)
927             | ty::Bound(..)
928             | ty::Param(_)
929             | ty::Placeholder(_)
930             | ty::Projection(_) => {
931                 // We don't know if these are `~const Destruct`, at least
932                 // not structurally... so don't push a candidate.
933             }
934
935             ty::Bool
936             | ty::Char
937             | ty::Int(_)
938             | ty::Uint(_)
939             | ty::Float(_)
940             | ty::Infer(ty::IntVar(_))
941             | ty::Infer(ty::FloatVar(_))
942             | ty::Str
943             | ty::RawPtr(_)
944             | ty::Ref(..)
945             | ty::FnDef(..)
946             | ty::FnPtr(_)
947             | ty::Never
948             | ty::Foreign(_)
949             | ty::Array(..)
950             | ty::Slice(_)
951             | ty::Closure(..)
952             | ty::Generator(..)
953             | ty::Tuple(_)
954             | ty::GeneratorWitness(_) => {
955                 // These are built-in, and cannot have a custom `impl const Destruct`.
956                 candidates.vec.push(ConstDestructCandidate(None));
957             }
958
959             ty::Adt(..) => {
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(),
964                     Some,
965                 );
966
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)));
971                     }
972                 } else {
973                     // Otherwise check the ADT like a built-in type (structurally)
974                     candidates.vec.push(ConstDestructCandidate(None));
975                 }
976             }
977
978             ty::Infer(_) => {
979                 candidates.ambiguous = true;
980             }
981         }
982     }
983 }