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