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