]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs
Rollup merge of #93753 - jeremyBanks:main-conflict, r=petrochenkov
[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 rustc_hir as hir;
9 use rustc_hir::def_id::DefId;
10 use rustc_infer::traits::TraitEngine;
11 use rustc_infer::traits::{Obligation, SelectionError, TraitObligation};
12 use rustc_lint_defs::builtin::DEREF_INTO_DYN_SUPERTRAIT;
13 use rustc_middle::ty::print::with_no_trimmed_paths;
14 use rustc_middle::ty::{self, ToPredicate, Ty, TypeFoldable};
15 use rustc_target::spec::abi::Abi;
16
17 use crate::traits;
18 use crate::traits::coherence::Conflict;
19 use crate::traits::query::evaluate_obligation::InferCtxtExt;
20 use crate::traits::{util, SelectionResult};
21 use crate::traits::{Ambiguous, ErrorReporting, Overflow, Unimplemented};
22
23 use super::BuiltinImplConditions;
24 use super::IntercrateAmbiguityCause;
25 use super::OverflowError;
26 use super::SelectionCandidate::{self, *};
27 use super::{EvaluatedCandidate, SelectionCandidateSet, SelectionContext, TraitObligationStack};
28
29 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
30     #[instrument(level = "debug", skip(self))]
31     pub(super) fn candidate_from_obligation<'o>(
32         &mut self,
33         stack: &TraitObligationStack<'o, 'tcx>,
34     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
35         // Watch out for overflow. This intentionally bypasses (and does
36         // not update) the cache.
37         self.check_recursion_limit(&stack.obligation, &stack.obligation)?;
38
39         // Check the cache. Note that we freshen the trait-ref
40         // separately rather than using `stack.fresh_trait_ref` --
41         // this is because we want the unbound variables to be
42         // replaced with fresh types starting from index 0.
43         let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate);
44         debug!(?cache_fresh_trait_pred);
45         debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars());
46
47         if let Some(c) =
48             self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred)
49         {
50             debug!(candidate = ?c, "CACHE HIT");
51             return c;
52         }
53
54         // If no match, compute result and insert into cache.
55         //
56         // FIXME(nikomatsakis) -- this cache is not taking into
57         // account cycles that may have occurred in forming the
58         // candidate. I don't know of any specific problems that
59         // result but it seems awfully suspicious.
60         let (candidate, dep_node) =
61             self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
62
63         debug!(?candidate, "CACHE MISS");
64         self.insert_candidate_cache(
65             stack.obligation.param_env,
66             cache_fresh_trait_pred,
67             dep_node,
68             candidate.clone(),
69         );
70         candidate
71     }
72
73     fn candidate_from_obligation_no_cache<'o>(
74         &mut self,
75         stack: &TraitObligationStack<'o, 'tcx>,
76     ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
77         if let Some(conflict) = self.is_knowable(stack) {
78             debug!("coherence stage: not knowable");
79             if self.intercrate_ambiguity_causes.is_some() {
80                 debug!("evaluate_stack: intercrate_ambiguity_causes is some");
81                 // Heuristics: show the diagnostics when there are no candidates in crate.
82                 if let Ok(candidate_set) = self.assemble_candidates(stack) {
83                     let mut no_candidates_apply = true;
84
85                     for c in candidate_set.vec.iter() {
86                         if self.evaluate_candidate(stack, &c)?.may_apply() {
87                             no_candidates_apply = false;
88                             break;
89                         }
90                     }
91
92                     if !candidate_set.ambiguous && no_candidates_apply {
93                         let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
94                         let self_ty = trait_ref.self_ty();
95                         let (trait_desc, self_desc) = with_no_trimmed_paths(|| {
96                             let trait_desc = trait_ref.print_only_trait_path().to_string();
97                             let self_desc = if self_ty.has_concrete_skeleton() {
98                                 Some(self_ty.to_string())
99                             } else {
100                                 None
101                             };
102                             (trait_desc, self_desc)
103                         });
104                         let cause = if let Conflict::Upstream = conflict {
105                             IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc }
106                         } else {
107                             IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
108                         };
109                         debug!(?cause, "evaluate_stack: pushing cause");
110                         self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
111                     }
112                 }
113             }
114             return Ok(None);
115         }
116
117         let candidate_set = self.assemble_candidates(stack)?;
118
119         if candidate_set.ambiguous {
120             debug!("candidate set contains ambig");
121             return Ok(None);
122         }
123
124         let candidates = candidate_set.vec;
125
126         debug!(?stack, ?candidates, "assembled {} candidates", candidates.len());
127
128         // At this point, we know that each of the entries in the
129         // candidate set is *individually* applicable. Now we have to
130         // figure out if they contain mutual incompatibilities. This
131         // frequently arises if we have an unconstrained input type --
132         // for example, we are looking for `$0: Eq` where `$0` is some
133         // unconstrained type variable. In that case, we'll get a
134         // candidate which assumes $0 == int, one that assumes `$0 ==
135         // usize`, etc. This spells an ambiguity.
136
137         let mut candidates = self.filter_impls(candidates, stack.obligation);
138
139         // If there is more than one candidate, first winnow them down
140         // by considering extra conditions (nested obligations and so
141         // forth). We don't winnow if there is exactly one
142         // candidate. This is a relatively minor distinction but it
143         // can lead to better inference and error-reporting. An
144         // example would be if there was an impl:
145         //
146         //     impl<T:Clone> Vec<T> { fn push_clone(...) { ... } }
147         //
148         // and we were to see some code `foo.push_clone()` where `boo`
149         // is a `Vec<Bar>` and `Bar` does not implement `Clone`.  If
150         // we were to winnow, we'd wind up with zero candidates.
151         // Instead, we select the right impl now but report "`Bar` does
152         // not implement `Clone`".
153         if candidates.len() == 1 {
154             return self.filter_reservation_impls(candidates.pop().unwrap(), stack.obligation);
155         }
156
157         // Winnow, but record the exact outcome of evaluation, which
158         // is needed for specialization. Propagate overflow if it occurs.
159         let mut candidates = candidates
160             .into_iter()
161             .map(|c| match self.evaluate_candidate(stack, &c) {
162                 Ok(eval) if eval.may_apply() => {
163                     Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval }))
164                 }
165                 Ok(_) => Ok(None),
166                 Err(OverflowError::Canonical) => Err(Overflow),
167                 Err(OverflowError::ErrorReporting) => Err(ErrorReporting),
168             })
169             .flat_map(Result::transpose)
170             .collect::<Result<Vec<_>, _>>()?;
171
172         debug!(?stack, ?candidates, "winnowed to {} candidates", candidates.len());
173
174         let needs_infer = stack.obligation.predicate.has_infer_types_or_consts();
175
176         let sized_predicate = self.tcx().lang_items().sized_trait()
177             == Some(stack.obligation.predicate.skip_binder().def_id());
178
179         // If there are STILL multiple candidates, we can further
180         // reduce the list by dropping duplicates -- including
181         // resolving specializations.
182         if candidates.len() > 1 {
183             let mut i = 0;
184             while i < candidates.len() {
185                 let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
186                     self.candidate_should_be_dropped_in_favor_of(
187                         sized_predicate,
188                         &candidates[i],
189                         &candidates[j],
190                         needs_infer,
191                     )
192                 });
193                 if is_dup {
194                     debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
195                     candidates.swap_remove(i);
196                 } else {
197                     debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
198                     i += 1;
199
200                     // If there are *STILL* multiple candidates, give up
201                     // and report ambiguity.
202                     if i > 1 {
203                         debug!("multiple matches, ambig");
204                         return Err(Ambiguous(
205                             candidates
206                                 .into_iter()
207                                 .filter_map(|c| match c.candidate {
208                                     SelectionCandidate::ImplCandidate(def_id) => Some(def_id),
209                                     _ => None,
210                                 })
211                                 .collect(),
212                         ));
213                     }
214                 }
215             }
216         }
217
218         // If there are *NO* candidates, then there are no impls --
219         // that we know of, anyway. Note that in the case where there
220         // are unbound type variables within the obligation, it might
221         // be the case that you could still satisfy the obligation
222         // from another crate by instantiating the type variables with
223         // a type from another crate that does have an impl. This case
224         // is checked for in `evaluate_stack` (and hence users
225         // who might care about this case, like coherence, should use
226         // that function).
227         if candidates.is_empty() {
228             // If there's an error type, 'downgrade' our result from
229             // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid
230             // emitting additional spurious errors, since we're guaranteed
231             // to have emitted at least one.
232             if stack.obligation.references_error() {
233                 debug!("no results for error type, treating as ambiguous");
234                 return Ok(None);
235             }
236             return Err(Unimplemented);
237         }
238
239         // Just one candidate left.
240         self.filter_reservation_impls(candidates.pop().unwrap().candidate, stack.obligation)
241     }
242
243     #[instrument(skip(self, stack), level = "debug")]
244     pub(super) fn assemble_candidates<'o>(
245         &mut self,
246         stack: &TraitObligationStack<'o, 'tcx>,
247     ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
248         let TraitObligationStack { obligation, .. } = *stack;
249         let obligation = &Obligation {
250             param_env: obligation.param_env,
251             cause: obligation.cause.clone(),
252             recursion_depth: obligation.recursion_depth,
253             predicate: self.infcx().resolve_vars_if_possible(obligation.predicate),
254         };
255
256         if obligation.predicate.skip_binder().self_ty().is_ty_var() {
257             debug!(ty = ?obligation.predicate.skip_binder().self_ty(), "ambiguous inference var or opaque type");
258             // Self is a type variable (e.g., `_: AsRef<str>`).
259             //
260             // This is somewhat problematic, as the current scheme can't really
261             // handle it turning to be a projection. This does end up as truly
262             // ambiguous in most cases anyway.
263             //
264             // Take the fast path out - this also improves
265             // performance by preventing assemble_candidates_from_impls from
266             // matching every impl for this trait.
267             return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
268         }
269
270         let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false };
271
272         // The only way to prove a NotImplemented(T: Foo) predicate is via a negative impl.
273         // There are no compiler built-in rules for this.
274         if obligation.polarity() == ty::ImplPolarity::Negative {
275             self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
276             self.assemble_candidates_from_impls(obligation, &mut candidates);
277         } else {
278             self.assemble_candidates_for_trait_alias(obligation, &mut candidates);
279
280             // Other bounds. Consider both in-scope bounds from fn decl
281             // and applicable impls. There is a certain set of precedence rules here.
282             let def_id = obligation.predicate.def_id();
283             let lang_items = self.tcx().lang_items();
284
285             if lang_items.copy_trait() == Some(def_id) {
286                 debug!(obligation_self_ty = ?obligation.predicate.skip_binder().self_ty());
287
288                 // User-defined copy impls are permitted, but only for
289                 // structs and enums.
290                 self.assemble_candidates_from_impls(obligation, &mut candidates);
291
292                 // For other types, we'll use the builtin rules.
293                 let copy_conditions = self.copy_clone_conditions(obligation);
294                 self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates);
295             } else if lang_items.discriminant_kind_trait() == Some(def_id) {
296                 // `DiscriminantKind` is automatically implemented for every type.
297                 candidates.vec.push(DiscriminantKindCandidate);
298             } else if lang_items.pointee_trait() == Some(def_id) {
299                 // `Pointee` is automatically implemented for every type.
300                 candidates.vec.push(PointeeCandidate);
301             } else if lang_items.sized_trait() == Some(def_id) {
302                 // Sized is never implementable by end-users, it is
303                 // always automatically computed.
304                 let sized_conditions = self.sized_conditions(obligation);
305                 self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates);
306             } else if lang_items.unsize_trait() == Some(def_id) {
307                 self.assemble_candidates_for_unsizing(obligation, &mut candidates);
308             } else if lang_items.drop_trait() == Some(def_id)
309                 && obligation.predicate.is_const_if_const()
310             {
311                 self.assemble_const_drop_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.evaluate_where_clause(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 kind = match self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) {
441             Some(k) => k,
442             None => {
443                 return;
444             }
445         };
446
447         // Okay to skip binder because the substs on closure types never
448         // touch bound regions, they just capture the in-scope
449         // type/region parameters
450         match *obligation.self_ty().skip_binder().kind() {
451             ty::Closure(_, closure_substs) => {
452                 debug!(?kind, ?obligation, "assemble_unboxed_candidates");
453                 match self.infcx.closure_kind(closure_substs) {
454                     Some(closure_kind) => {
455                         debug!(?closure_kind, "assemble_unboxed_candidates");
456                         if closure_kind.extends(kind) {
457                             candidates.vec.push(ClosureCandidate);
458                         }
459                     }
460                     None => {
461                         debug!("assemble_unboxed_candidates: closure_kind not yet known");
462                         candidates.vec.push(ClosureCandidate);
463                     }
464                 }
465             }
466             ty::Infer(ty::TyVar(_)) => {
467                 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
468                 candidates.ambiguous = true;
469             }
470             _ => {}
471         }
472     }
473
474     /// Implements one of the `Fn()` family for a fn pointer.
475     fn assemble_fn_pointer_candidates(
476         &mut self,
477         obligation: &TraitObligation<'tcx>,
478         candidates: &mut SelectionCandidateSet<'tcx>,
479     ) {
480         // We provide impl of all fn traits for fn pointers.
481         if self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()).is_none() {
482             return;
483         }
484
485         // Okay to skip binder because what we are inspecting doesn't involve bound regions.
486         let self_ty = obligation.self_ty().skip_binder();
487         match *self_ty.kind() {
488             ty::Infer(ty::TyVar(_)) => {
489                 debug!("assemble_fn_pointer_candidates: ambiguous self-type");
490                 candidates.ambiguous = true; // Could wind up being a fn() type.
491             }
492             // Provide an impl, but only for suitable `fn` pointers.
493             ty::FnPtr(_) => {
494                 if let ty::FnSig {
495                     unsafety: hir::Unsafety::Normal,
496                     abi: Abi::Rust,
497                     c_variadic: false,
498                     ..
499                 } = self_ty.fn_sig(self.tcx()).skip_binder()
500                 {
501                     candidates.vec.push(FnPointerCandidate { is_const: false });
502                 }
503             }
504             // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396).
505             ty::FnDef(def_id, _) => {
506                 if let ty::FnSig {
507                     unsafety: hir::Unsafety::Normal,
508                     abi: Abi::Rust,
509                     c_variadic: false,
510                     ..
511                 } = self_ty.fn_sig(self.tcx()).skip_binder()
512                 {
513                     if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() {
514                         candidates
515                             .vec
516                             .push(FnPointerCandidate { is_const: self.tcx().is_const_fn(def_id) });
517                     }
518                 }
519             }
520             _ => {}
521         }
522     }
523
524     /// Searches for impls that might apply to `obligation`.
525     fn assemble_candidates_from_impls(
526         &mut self,
527         obligation: &TraitObligation<'tcx>,
528         candidates: &mut SelectionCandidateSet<'tcx>,
529     ) {
530         debug!(?obligation, "assemble_candidates_from_impls");
531
532         // Essentially any user-written impl will match with an error type,
533         // so creating `ImplCandidates` isn't useful. However, we might
534         // end up finding a candidate elsewhere (e.g. a `BuiltinCandidate` for `Sized)
535         // This helps us avoid overflow: see issue #72839
536         // Since compilation is already guaranteed to fail, this is just
537         // to try to show the 'nicest' possible errors to the user.
538         // We don't check for errors in the `ParamEnv` - in practice,
539         // it seems to cause us to be overly aggressive in deciding
540         // to give up searching for candidates, leading to spurious errors.
541         if obligation.predicate.references_error() {
542             return;
543         }
544
545         self.tcx().for_each_relevant_impl(
546             obligation.predicate.def_id(),
547             obligation.predicate.skip_binder().trait_ref.self_ty(),
548             |impl_def_id| {
549                 self.infcx.probe(|_| {
550                     if let Ok(_substs) = self.match_impl(impl_def_id, obligation) {
551                         candidates.vec.push(ImplCandidate(impl_def_id));
552                     }
553                 });
554             },
555         );
556     }
557
558     fn assemble_candidates_from_auto_impls(
559         &mut self,
560         obligation: &TraitObligation<'tcx>,
561         candidates: &mut SelectionCandidateSet<'tcx>,
562     ) {
563         // Okay to skip binder here because the tests we do below do not involve bound regions.
564         let self_ty = obligation.self_ty().skip_binder();
565         debug!(?self_ty, "assemble_candidates_from_auto_impls");
566
567         let def_id = obligation.predicate.def_id();
568
569         if self.tcx().trait_is_auto(def_id) {
570             match self_ty.kind() {
571                 ty::Dynamic(..) => {
572                     // For object types, we don't know what the closed
573                     // over types are. This means we conservatively
574                     // say nothing; a candidate may be added by
575                     // `assemble_candidates_from_object_ty`.
576                 }
577                 ty::Foreign(..) => {
578                     // Since the contents of foreign types is unknown,
579                     // we don't add any `..` impl. Default traits could
580                     // still be provided by a manual implementation for
581                     // this trait and type.
582                 }
583                 ty::Param(..) | ty::Projection(..) => {
584                     // In these cases, we don't know what the actual
585                     // type is.  Therefore, we cannot break it down
586                     // into its constituent types. So we don't
587                     // consider the `..` impl but instead just add no
588                     // candidates: this means that typeck will only
589                     // succeed if there is another reason to believe
590                     // that this obligation holds. That could be a
591                     // where-clause or, in the case of an object type,
592                     // it could be that the object type lists the
593                     // trait (e.g., `Foo+Send : Send`). See
594                     // `ui/typeck/typeck-default-trait-impl-send-param.rs`
595                     // for an example of a test case that exercises
596                     // this path.
597                 }
598                 ty::Infer(ty::TyVar(_)) => {
599                     // The auto impl might apply; we don't know.
600                     candidates.ambiguous = true;
601                 }
602                 ty::Generator(_, _, movability)
603                     if self.tcx().lang_items().unpin_trait() == Some(def_id) =>
604                 {
605                     match movability {
606                         hir::Movability::Static => {
607                             // Immovable generators are never `Unpin`, so
608                             // suppress the normal auto-impl candidate for it.
609                         }
610                         hir::Movability::Movable => {
611                             // Movable generators are always `Unpin`, so add an
612                             // unconditional builtin candidate.
613                             candidates.vec.push(BuiltinCandidate { has_nested: false });
614                         }
615                     }
616                 }
617
618                 _ => candidates.vec.push(AutoImplCandidate(def_id)),
619             }
620         }
621     }
622
623     /// Searches for impls that might apply to `obligation`.
624     fn assemble_candidates_from_object_ty(
625         &mut self,
626         obligation: &TraitObligation<'tcx>,
627         candidates: &mut SelectionCandidateSet<'tcx>,
628     ) {
629         debug!(
630             self_ty = ?obligation.self_ty().skip_binder(),
631             "assemble_candidates_from_object_ty",
632         );
633
634         self.infcx.probe(|_snapshot| {
635             // The code below doesn't care about regions, and the
636             // self-ty here doesn't escape this probe, so just erase
637             // any LBR.
638             let self_ty = self.tcx().erase_late_bound_regions(obligation.self_ty());
639             let poly_trait_ref = match self_ty.kind() {
640                 ty::Dynamic(ref data, ..) => {
641                     if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
642                         debug!(
643                             "assemble_candidates_from_object_ty: matched builtin bound, \
644                              pushing candidate"
645                         );
646                         candidates.vec.push(BuiltinObjectCandidate);
647                         return;
648                     }
649
650                     if let Some(principal) = data.principal() {
651                         if !self.infcx.tcx.features().object_safe_for_dispatch {
652                             principal.with_self_ty(self.tcx(), self_ty)
653                         } else if self.tcx().is_object_safe(principal.def_id()) {
654                             principal.with_self_ty(self.tcx(), self_ty)
655                         } else {
656                             return;
657                         }
658                     } else {
659                         // Only auto trait bounds exist.
660                         return;
661                     }
662                 }
663                 ty::Infer(ty::TyVar(_)) => {
664                     debug!("assemble_candidates_from_object_ty: ambiguous");
665                     candidates.ambiguous = true; // could wind up being an object type
666                     return;
667                 }
668                 _ => return,
669             };
670
671             debug!(?poly_trait_ref, "assemble_candidates_from_object_ty");
672
673             let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
674             let placeholder_trait_predicate =
675                 self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
676
677             // Count only those upcast versions that match the trait-ref
678             // we are looking for. Specifically, do not only check for the
679             // correct trait, but also the correct type parameters.
680             // For example, we may be trying to upcast `Foo` to `Bar<i32>`,
681             // but `Foo` is declared as `trait Foo: Bar<u32>`.
682             let candidate_supertraits = util::supertraits(self.tcx(), poly_trait_ref)
683                 .enumerate()
684                 .filter(|&(_, upcast_trait_ref)| {
685                     self.infcx.probe(|_| {
686                         self.match_normalize_trait_ref(
687                             obligation,
688                             upcast_trait_ref,
689                             placeholder_trait_predicate.trait_ref,
690                         )
691                         .is_ok()
692                     })
693                 })
694                 .map(|(idx, _)| ObjectCandidate(idx));
695
696             candidates.vec.extend(candidate_supertraits);
697         })
698     }
699
700     /// Temporary migration for #89190
701     fn need_migrate_deref_output_trait_object(
702         &mut self,
703         ty: Ty<'tcx>,
704         cause: &traits::ObligationCause<'tcx>,
705         param_env: ty::ParamEnv<'tcx>,
706     ) -> Option<(Ty<'tcx>, DefId)> {
707         let tcx = self.tcx();
708         if tcx.features().trait_upcasting {
709             return None;
710         }
711
712         // <ty as Deref>
713         let trait_ref = ty::TraitRef {
714             def_id: tcx.lang_items().deref_trait()?,
715             substs: tcx.mk_substs_trait(ty, &[]),
716         };
717
718         let obligation = traits::Obligation::new(
719             cause.clone(),
720             param_env,
721             ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
722         );
723         if !self.infcx.predicate_may_hold(&obligation) {
724             return None;
725         }
726
727         let mut fulfillcx = traits::FulfillmentContext::new_in_snapshot();
728         let normalized_ty = fulfillcx.normalize_projection_type(
729             &self.infcx,
730             param_env,
731             ty::ProjectionTy {
732                 item_def_id: tcx.lang_items().deref_target()?,
733                 substs: trait_ref.substs,
734             },
735             cause.clone(),
736         );
737
738         let ty::Dynamic(data, ..) = normalized_ty.kind() else {
739             return None;
740         };
741
742         let def_id = data.principal_def_id()?;
743
744         return Some((normalized_ty, def_id));
745     }
746
747     /// Searches for unsizing that might apply to `obligation`.
748     fn assemble_candidates_for_unsizing(
749         &mut self,
750         obligation: &TraitObligation<'tcx>,
751         candidates: &mut SelectionCandidateSet<'tcx>,
752     ) {
753         // We currently never consider higher-ranked obligations e.g.
754         // `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
755         // because they are a priori invalid, and we could potentially add support
756         // for them later, it's just that there isn't really a strong need for it.
757         // A `T: Unsize<U>` obligation is always used as part of a `T: CoerceUnsize<U>`
758         // impl, and those are generally applied to concrete types.
759         //
760         // That said, one might try to write a fn with a where clause like
761         //     for<'a> Foo<'a, T>: Unsize<Foo<'a, Trait>>
762         // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`.
763         // Still, you'd be more likely to write that where clause as
764         //     T: Trait
765         // so it seems ok if we (conservatively) fail to accept that `Unsize`
766         // obligation above. Should be possible to extend this in the future.
767         let source = match obligation.self_ty().no_bound_vars() {
768             Some(t) => t,
769             None => {
770                 // Don't add any candidates if there are bound regions.
771                 return;
772             }
773         };
774         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
775
776         debug!(?source, ?target, "assemble_candidates_for_unsizing");
777
778         match (source.kind(), target.kind()) {
779             // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
780             (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
781                 // Upcast coercions permit several things:
782                 //
783                 // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo`
784                 // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b`
785                 // 3. Tightening trait to its super traits, eg. `Foo` to `Bar` if `Foo: Bar`
786                 //
787                 // Note that neither of the first two of these changes requires any
788                 // change at runtime. The third needs to change pointer metadata at runtime.
789                 //
790                 // We always perform upcasting coercions when we can because of reason
791                 // #2 (region bounds).
792                 let auto_traits_compatible = data_b
793                     .auto_traits()
794                     // All of a's auto traits need to be in b's auto traits.
795                     .all(|b| data_a.auto_traits().any(|a| a == b));
796                 if auto_traits_compatible {
797                     let principal_def_id_a = data_a.principal_def_id();
798                     let principal_def_id_b = data_b.principal_def_id();
799                     if principal_def_id_a == principal_def_id_b {
800                         // no cyclic
801                         candidates.vec.push(BuiltinUnsizeCandidate);
802                     } else if principal_def_id_a.is_some() && principal_def_id_b.is_some() {
803                         // not casual unsizing, now check whether this is trait upcasting coercion.
804                         let principal_a = data_a.principal().unwrap();
805                         let target_trait_did = principal_def_id_b.unwrap();
806                         let source_trait_ref = principal_a.with_self_ty(self.tcx(), source);
807                         if let Some((deref_output_ty, deref_output_trait_did)) = self
808                             .need_migrate_deref_output_trait_object(
809                                 source,
810                                 &obligation.cause,
811                                 obligation.param_env,
812                             )
813                         {
814                             if deref_output_trait_did == target_trait_did {
815                                 self.tcx().struct_span_lint_hir(
816                                     DEREF_INTO_DYN_SUPERTRAIT,
817                                     obligation.cause.body_id,
818                                     obligation.cause.span,
819                                     |lint| {
820                                         lint.build(&format!(
821                                             "`{}` implements `Deref` with supertrait `{}` as output",
822                                             source,
823                                             deref_output_ty
824                                         )).emit();
825                                     },
826                                 );
827                                 return;
828                             }
829                         }
830
831                         for (idx, upcast_trait_ref) in
832                             util::supertraits(self.tcx(), source_trait_ref).enumerate()
833                         {
834                             if upcast_trait_ref.def_id() == target_trait_did {
835                                 candidates.vec.push(TraitUpcastingUnsizeCandidate(idx));
836                             }
837                         }
838                     }
839                 }
840             }
841
842             // `T` -> `Trait`
843             (_, &ty::Dynamic(..)) => {
844                 candidates.vec.push(BuiltinUnsizeCandidate);
845             }
846
847             // Ambiguous handling is below `T` -> `Trait`, because inference
848             // variables can still implement `Unsize<Trait>` and nested
849             // obligations will have the final say (likely deferred).
850             (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
851                 debug!("assemble_candidates_for_unsizing: ambiguous");
852                 candidates.ambiguous = true;
853             }
854
855             // `[T; n]` -> `[T]`
856             (&ty::Array(..), &ty::Slice(_)) => {
857                 candidates.vec.push(BuiltinUnsizeCandidate);
858             }
859
860             // `Struct<T>` -> `Struct<U>`
861             (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => {
862                 if def_id_a == def_id_b {
863                     candidates.vec.push(BuiltinUnsizeCandidate);
864                 }
865             }
866
867             // `(.., T)` -> `(.., U)`
868             (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
869                 if tys_a.len() == tys_b.len() {
870                     candidates.vec.push(BuiltinUnsizeCandidate);
871                 }
872             }
873
874             _ => {}
875         };
876     }
877
878     #[tracing::instrument(level = "debug", skip(self, obligation, candidates))]
879     fn assemble_candidates_for_trait_alias(
880         &mut self,
881         obligation: &TraitObligation<'tcx>,
882         candidates: &mut SelectionCandidateSet<'tcx>,
883     ) {
884         // Okay to skip binder here because the tests we do below do not involve bound regions.
885         let self_ty = obligation.self_ty().skip_binder();
886         debug!(?self_ty);
887
888         let def_id = obligation.predicate.def_id();
889
890         if self.tcx().is_trait_alias(def_id) {
891             candidates.vec.push(TraitAliasCandidate(def_id));
892         }
893     }
894
895     /// Assembles the trait which are built-in to the language itself:
896     /// `Copy`, `Clone` and `Sized`.
897     #[tracing::instrument(level = "debug", skip(self, candidates))]
898     fn assemble_builtin_bound_candidates(
899         &mut self,
900         conditions: BuiltinImplConditions<'tcx>,
901         candidates: &mut SelectionCandidateSet<'tcx>,
902     ) {
903         match conditions {
904             BuiltinImplConditions::Where(nested) => {
905                 candidates
906                     .vec
907                     .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() });
908             }
909             BuiltinImplConditions::None => {}
910             BuiltinImplConditions::Ambiguous => {
911                 candidates.ambiguous = true;
912             }
913         }
914     }
915
916     fn assemble_const_drop_candidates(
917         &mut self,
918         obligation: &TraitObligation<'tcx>,
919         candidates: &mut SelectionCandidateSet<'tcx>,
920     ) {
921         // If the predicate is `~const Drop` in a non-const environment, we don't actually need
922         // to check anything. We'll short-circuit checking any obligations in confirmation, too.
923         if obligation.param_env.constness() == hir::Constness::NotConst {
924             candidates.vec.push(ConstDropCandidate(None));
925             return;
926         }
927
928         let self_ty = self.infcx().shallow_resolve(obligation.self_ty());
929         match self_ty.skip_binder().kind() {
930             ty::Opaque(..)
931             | ty::Dynamic(..)
932             | ty::Error(_)
933             | ty::Bound(..)
934             | ty::Param(_)
935             | ty::Placeholder(_)
936             | ty::Projection(_) => {
937                 // We don't know if these are `~const Drop`, at least
938                 // not structurally... so don't push a candidate.
939             }
940
941             ty::Bool
942             | ty::Char
943             | ty::Int(_)
944             | ty::Uint(_)
945             | ty::Float(_)
946             | ty::Infer(ty::IntVar(_))
947             | ty::Infer(ty::FloatVar(_))
948             | ty::Str
949             | ty::RawPtr(_)
950             | ty::Ref(..)
951             | ty::FnDef(..)
952             | ty::FnPtr(_)
953             | ty::Never
954             | ty::Foreign(_)
955             | ty::Array(..)
956             | ty::Slice(_)
957             | ty::Closure(..)
958             | ty::Generator(..)
959             | ty::Tuple(_)
960             | ty::GeneratorWitness(_) => {
961                 // These are built-in, and cannot have a custom `impl const Drop`.
962                 candidates.vec.push(ConstDropCandidate(None));
963             }
964
965             ty::Adt(..) => {
966                 // Find a custom `impl Drop` impl, if it exists
967                 let relevant_impl = self.tcx().find_map_relevant_impl(
968                     obligation.predicate.def_id(),
969                     obligation.predicate.skip_binder().trait_ref.self_ty(),
970                     Some,
971                 );
972
973                 if let Some(impl_def_id) = relevant_impl {
974                     // Check that `impl Drop` is actually const, if there is a custom impl
975                     if self.tcx().impl_constness(impl_def_id) == hir::Constness::Const {
976                         candidates.vec.push(ConstDropCandidate(Some(impl_def_id)));
977                     }
978                 } else {
979                     // Otherwise check the ADT like a built-in type (structurally)
980                     candidates.vec.push(ConstDropCandidate(None));
981                 }
982             }
983
984             ty::Infer(_) => {
985                 candidates.ambiguous = true;
986             }
987         }
988     }
989 }