]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/object_safety.rs
Rollup merge of #104286 - ozkanonur:fix-doc-bootstrap-recompilation, r=jyn514
[rust.git] / compiler / rustc_trait_selection / src / traits / object_safety.rs
1 //! "Object safety" refers to the ability for a trait to be converted
2 //! to an object. In general, traits may only be converted to an
3 //! object if all of their methods meet certain criteria. In particular,
4 //! they must:
5 //!
6 //!   - have a suitable receiver from which we can extract a vtable and coerce to a "thin" version
7 //!     that doesn't contain the vtable;
8 //!   - not reference the erased type `Self` except for in this receiver;
9 //!   - not have generic type parameters.
10
11 use super::{elaborate_predicates, elaborate_trait_ref};
12
13 use crate::infer::TyCtxtInferExt;
14 use crate::traits::query::evaluate_obligation::InferCtxtExt;
15 use crate::traits::{self, Obligation, ObligationCause};
16 use hir::def::DefKind;
17 use rustc_errors::{DelayDm, FatalError, MultiSpan};
18 use rustc_hir as hir;
19 use rustc_hir::def_id::DefId;
20 use rustc_middle::ty::abstract_const::{walk_abstract_const, AbstractConst};
21 use rustc_middle::ty::{
22     self, EarlyBinder, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor,
23 };
24 use rustc_middle::ty::{GenericArg, InternalSubsts};
25 use rustc_middle::ty::{Predicate, ToPredicate};
26 use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
27 use rustc_span::symbol::Symbol;
28 use rustc_span::Span;
29 use smallvec::SmallVec;
30
31 use std::iter;
32 use std::ops::ControlFlow;
33
34 pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation};
35
36 /// Returns the object safety violations that affect
37 /// astconv -- currently, `Self` in supertraits. This is needed
38 /// because `object_safety_violations` can't be used during
39 /// type collection.
40 pub fn astconv_object_safety_violations(
41     tcx: TyCtxt<'_>,
42     trait_def_id: DefId,
43 ) -> Vec<ObjectSafetyViolation> {
44     debug_assert!(tcx.generics_of(trait_def_id).has_self);
45     let violations = traits::supertrait_def_ids(tcx, trait_def_id)
46         .map(|def_id| predicates_reference_self(tcx, def_id, true))
47         .filter(|spans| !spans.is_empty())
48         .map(ObjectSafetyViolation::SupertraitSelf)
49         .collect();
50
51     debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
52
53     violations
54 }
55
56 fn object_safety_violations(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &'_ [ObjectSafetyViolation] {
57     debug_assert!(tcx.generics_of(trait_def_id).has_self);
58     debug!("object_safety_violations: {:?}", trait_def_id);
59
60     tcx.arena.alloc_from_iter(
61         traits::supertrait_def_ids(tcx, trait_def_id)
62             .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id)),
63     )
64 }
65
66 /// We say a method is *vtable safe* if it can be invoked on a trait
67 /// object. Note that object-safe traits can have some
68 /// non-vtable-safe methods, so long as they require `Self: Sized` or
69 /// otherwise ensure that they cannot be used when `Self = Trait`.
70 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
71     debug_assert!(tcx.generics_of(trait_def_id).has_self);
72     debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
73     // Any method that has a `Self: Sized` bound cannot be called.
74     if generics_require_sized_self(tcx, method.def_id) {
75         return false;
76     }
77
78     match virtual_call_violation_for_method(tcx, trait_def_id, method) {
79         None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
80         Some(_) => false,
81     }
82 }
83
84 fn object_safety_violations_for_trait(
85     tcx: TyCtxt<'_>,
86     trait_def_id: DefId,
87 ) -> Vec<ObjectSafetyViolation> {
88     // Check methods for violations.
89     let mut violations: Vec<_> = tcx
90         .associated_items(trait_def_id)
91         .in_definition_order()
92         .filter(|item| item.kind == ty::AssocKind::Fn)
93         .filter_map(|item| {
94             object_safety_violation_for_method(tcx, trait_def_id, &item)
95                 .map(|(code, span)| ObjectSafetyViolation::Method(item.name, code, span))
96         })
97         .filter(|violation| {
98             if let ObjectSafetyViolation::Method(
99                 _,
100                 MethodViolationCode::WhereClauseReferencesSelf,
101                 span,
102             ) = violation
103             {
104                 lint_object_unsafe_trait(tcx, *span, trait_def_id, &violation);
105                 false
106             } else {
107                 true
108             }
109         })
110         .collect();
111
112     // Check the trait itself.
113     if trait_has_sized_self(tcx, trait_def_id) {
114         // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
115         let spans = get_sized_bounds(tcx, trait_def_id);
116         violations.push(ObjectSafetyViolation::SizedSelf(spans));
117     }
118     let spans = predicates_reference_self(tcx, trait_def_id, false);
119     if !spans.is_empty() {
120         violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
121     }
122     let spans = bounds_reference_self(tcx, trait_def_id);
123     if !spans.is_empty() {
124         violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
125     }
126
127     violations.extend(
128         tcx.associated_items(trait_def_id)
129             .in_definition_order()
130             .filter(|item| item.kind == ty::AssocKind::Const)
131             .map(|item| {
132                 let ident = item.ident(tcx);
133                 ObjectSafetyViolation::AssocConst(ident.name, ident.span)
134             }),
135     );
136
137     if !tcx.features().generic_associated_types_extended {
138         violations.extend(
139             tcx.associated_items(trait_def_id)
140                 .in_definition_order()
141                 .filter(|item| item.kind == ty::AssocKind::Type)
142                 .filter(|item| !tcx.generics_of(item.def_id).params.is_empty())
143                 .map(|item| {
144                     let ident = item.ident(tcx);
145                     ObjectSafetyViolation::GAT(ident.name, ident.span)
146                 }),
147         );
148     }
149
150     debug!(
151         "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
152         trait_def_id, violations
153     );
154
155     violations
156 }
157
158 /// Lint object-unsafe trait.
159 fn lint_object_unsafe_trait(
160     tcx: TyCtxt<'_>,
161     span: Span,
162     trait_def_id: DefId,
163     violation: &ObjectSafetyViolation,
164 ) {
165     // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
166     // It's also hard to get a use site span, so we use the method definition span.
167     tcx.struct_span_lint_hir(
168         WHERE_CLAUSES_OBJECT_SAFETY,
169         hir::CRATE_HIR_ID,
170         span,
171         DelayDm(|| format!("the trait `{}` cannot be made into an object", tcx.def_path_str(trait_def_id))),
172         |err| {
173             let node = tcx.hir().get_if_local(trait_def_id);
174             let mut spans = MultiSpan::from_span(span);
175             if let Some(hir::Node::Item(item)) = node {
176                 spans.push_span_label(
177                     item.ident.span,
178                     "this trait cannot be made into an object...",
179                 );
180                 spans.push_span_label(span, format!("...because {}", violation.error_msg()));
181             } else {
182                 spans.push_span_label(
183                     span,
184                     format!(
185                         "the trait cannot be made into an object because {}",
186                         violation.error_msg()
187                     ),
188                 );
189             };
190             err.span_note(
191                 spans,
192                 "for a trait to be \"object safe\" it needs to allow building a vtable to allow the \
193                 call to be resolvable dynamically; for more information visit \
194                 <https://doc.rust-lang.org/reference/items/traits.html#object-safety>",
195             );
196             if node.is_some() {
197                 // Only provide the help if its a local trait, otherwise it's not
198                 violation.solution(err);
199             }
200             err
201         },
202     );
203 }
204
205 fn sized_trait_bound_spans<'tcx>(
206     tcx: TyCtxt<'tcx>,
207     bounds: hir::GenericBounds<'tcx>,
208 ) -> impl 'tcx + Iterator<Item = Span> {
209     bounds.iter().filter_map(move |b| match b {
210         hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
211             if trait_has_sized_self(
212                 tcx,
213                 trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
214             ) =>
215         {
216             // Fetch spans for supertraits that are `Sized`: `trait T: Super`
217             Some(trait_ref.span)
218         }
219         _ => None,
220     })
221 }
222
223 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
224     tcx.hir()
225         .get_if_local(trait_def_id)
226         .and_then(|node| match node {
227             hir::Node::Item(hir::Item {
228                 kind: hir::ItemKind::Trait(.., generics, bounds, _),
229                 ..
230             }) => Some(
231                 generics
232                     .predicates
233                     .iter()
234                     .filter_map(|pred| {
235                         match pred {
236                             hir::WherePredicate::BoundPredicate(pred)
237                                 if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
238                             {
239                                 // Fetch spans for trait bounds that are Sized:
240                                 // `trait T where Self: Pred`
241                                 Some(sized_trait_bound_spans(tcx, pred.bounds))
242                             }
243                             _ => None,
244                         }
245                     })
246                     .flatten()
247                     // Fetch spans for supertraits that are `Sized`: `trait T: Super`.
248                     .chain(sized_trait_bound_spans(tcx, bounds))
249                     .collect::<SmallVec<[Span; 1]>>(),
250             ),
251             _ => None,
252         })
253         .unwrap_or_else(SmallVec::new)
254 }
255
256 fn predicates_reference_self(
257     tcx: TyCtxt<'_>,
258     trait_def_id: DefId,
259     supertraits_only: bool,
260 ) -> SmallVec<[Span; 1]> {
261     let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
262     let predicates = if supertraits_only {
263         tcx.super_predicates_of(trait_def_id)
264     } else {
265         tcx.predicates_of(trait_def_id)
266     };
267     predicates
268         .predicates
269         .iter()
270         .map(|&(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
271         .filter_map(|predicate| predicate_references_self(tcx, predicate))
272         .collect()
273 }
274
275 fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
276     tcx.associated_items(trait_def_id)
277         .in_definition_order()
278         .filter(|item| item.kind == ty::AssocKind::Type)
279         .flat_map(|item| tcx.explicit_item_bounds(item.def_id))
280         .filter_map(|pred_span| predicate_references_self(tcx, *pred_span))
281         .collect()
282 }
283
284 fn predicate_references_self<'tcx>(
285     tcx: TyCtxt<'tcx>,
286     (predicate, sp): (ty::Predicate<'tcx>, Span),
287 ) -> Option<Span> {
288     let self_ty = tcx.types.self_param;
289     let has_self_ty = |arg: &GenericArg<'tcx>| arg.walk().any(|arg| arg == self_ty.into());
290     match predicate.kind().skip_binder() {
291         ty::PredicateKind::Trait(ref data) => {
292             // In the case of a trait predicate, we can skip the "self" type.
293             if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
294         }
295         ty::PredicateKind::Projection(ref data) => {
296             // And similarly for projections. This should be redundant with
297             // the previous check because any projection should have a
298             // matching `Trait` predicate with the same inputs, but we do
299             // the check to be safe.
300             //
301             // It's also won't be redundant if we allow type-generic associated
302             // types for trait objects.
303             //
304             // Note that we *do* allow projection *outputs* to contain
305             // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
306             // we just require the user to specify *both* outputs
307             // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
308             //
309             // This is ALT2 in issue #56288, see that for discussion of the
310             // possible alternatives.
311             if data.projection_ty.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
312         }
313         ty::PredicateKind::WellFormed(..)
314         | ty::PredicateKind::ObjectSafe(..)
315         | ty::PredicateKind::TypeOutlives(..)
316         | ty::PredicateKind::RegionOutlives(..)
317         | ty::PredicateKind::ClosureKind(..)
318         | ty::PredicateKind::Subtype(..)
319         | ty::PredicateKind::Coerce(..)
320         | ty::PredicateKind::ConstEvaluatable(..)
321         | ty::PredicateKind::ConstEquate(..)
322         | ty::PredicateKind::Ambiguous
323         | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
324     }
325 }
326
327 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
328     generics_require_sized_self(tcx, trait_def_id)
329 }
330
331 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
332     let Some(sized_def_id) = tcx.lang_items().sized_trait() else {
333         return false; /* No Sized trait, can't require it! */
334     };
335
336     // Search for a predicate like `Self : Sized` amongst the trait bounds.
337     let predicates = tcx.predicates_of(def_id);
338     let predicates = predicates.instantiate_identity(tcx).predicates;
339     elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| {
340         match obligation.predicate.kind().skip_binder() {
341             ty::PredicateKind::Trait(ref trait_pred) => {
342                 trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
343             }
344             ty::PredicateKind::Projection(..)
345             | ty::PredicateKind::Subtype(..)
346             | ty::PredicateKind::Coerce(..)
347             | ty::PredicateKind::RegionOutlives(..)
348             | ty::PredicateKind::WellFormed(..)
349             | ty::PredicateKind::ObjectSafe(..)
350             | ty::PredicateKind::ClosureKind(..)
351             | ty::PredicateKind::TypeOutlives(..)
352             | ty::PredicateKind::ConstEvaluatable(..)
353             | ty::PredicateKind::ConstEquate(..)
354             | ty::PredicateKind::Ambiguous
355             | ty::PredicateKind::TypeWellFormedFromEnv(..) => false,
356         }
357     })
358 }
359
360 /// Returns `Some(_)` if this method makes the containing trait not object safe.
361 fn object_safety_violation_for_method(
362     tcx: TyCtxt<'_>,
363     trait_def_id: DefId,
364     method: &ty::AssocItem,
365 ) -> Option<(MethodViolationCode, Span)> {
366     debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
367     // Any method that has a `Self : Sized` requisite is otherwise
368     // exempt from the regulations.
369     if generics_require_sized_self(tcx, method.def_id) {
370         return None;
371     }
372
373     let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
374     // Get an accurate span depending on the violation.
375     violation.map(|v| {
376         let node = tcx.hir().get_if_local(method.def_id);
377         let span = match (&v, node) {
378             (MethodViolationCode::ReferencesSelfInput(Some(span)), _) => *span,
379             (MethodViolationCode::UndispatchableReceiver(Some(span)), _) => *span,
380             (MethodViolationCode::ReferencesImplTraitInTrait(span), _) => *span,
381             (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
382                 node.fn_decl().map_or(method.ident(tcx).span, |decl| decl.output.span())
383             }
384             _ => method.ident(tcx).span,
385         };
386         (v, span)
387     })
388 }
389
390 /// Returns `Some(_)` if this method cannot be called on a trait
391 /// object; this does not necessarily imply that the enclosing trait
392 /// is not object safe, because the method might have a where clause
393 /// `Self:Sized`.
394 fn virtual_call_violation_for_method<'tcx>(
395     tcx: TyCtxt<'tcx>,
396     trait_def_id: DefId,
397     method: &ty::AssocItem,
398 ) -> Option<MethodViolationCode> {
399     let sig = tcx.fn_sig(method.def_id);
400
401     // The method's first parameter must be named `self`
402     if !method.fn_has_self_parameter {
403         let sugg = if let Some(hir::Node::TraitItem(hir::TraitItem {
404             generics,
405             kind: hir::TraitItemKind::Fn(sig, _),
406             ..
407         })) = tcx.hir().get_if_local(method.def_id).as_ref()
408         {
409             let sm = tcx.sess.source_map();
410             Some((
411                 (
412                     format!("&self{}", if sig.decl.inputs.is_empty() { "" } else { ", " }),
413                     sm.span_through_char(sig.span, '(').shrink_to_hi(),
414                 ),
415                 (
416                     format!("{} Self: Sized", generics.add_where_or_trailing_comma()),
417                     generics.tail_span_for_predicate_suggestion(),
418                 ),
419             ))
420         } else {
421             None
422         };
423         return Some(MethodViolationCode::StaticMethod(sugg));
424     }
425
426     for (i, &input_ty) in sig.skip_binder().inputs().iter().enumerate().skip(1) {
427         if contains_illegal_self_type_reference(tcx, trait_def_id, sig.rebind(input_ty)) {
428             let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
429                 kind: hir::TraitItemKind::Fn(sig, _),
430                 ..
431             })) = tcx.hir().get_if_local(method.def_id).as_ref()
432             {
433                 Some(sig.decl.inputs[i].span)
434             } else {
435                 None
436             };
437             return Some(MethodViolationCode::ReferencesSelfInput(span));
438         }
439     }
440     if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output()) {
441         return Some(MethodViolationCode::ReferencesSelfOutput);
442     }
443     if let Some(code) = contains_illegal_impl_trait_in_trait(tcx, method.def_id, sig.output()) {
444         return Some(code);
445     }
446
447     // We can't monomorphize things like `fn foo<A>(...)`.
448     let own_counts = tcx.generics_of(method.def_id).own_counts();
449     if own_counts.types + own_counts.consts != 0 {
450         return Some(MethodViolationCode::Generic);
451     }
452
453     let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
454
455     // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
456     // However, this is already considered object-safe. We allow it as a special case here.
457     // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
458     // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
459     if receiver_ty != tcx.types.self_param {
460         if !receiver_is_dispatchable(tcx, method, receiver_ty) {
461             let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
462                 kind: hir::TraitItemKind::Fn(sig, _),
463                 ..
464             })) = tcx.hir().get_if_local(method.def_id).as_ref()
465             {
466                 Some(sig.decl.inputs[0].span)
467             } else {
468                 None
469             };
470             return Some(MethodViolationCode::UndispatchableReceiver(span));
471         } else {
472             // Do sanity check to make sure the receiver actually has the layout of a pointer.
473
474             use rustc_target::abi::Abi;
475
476             let param_env = tcx.param_env(method.def_id);
477
478             let abi_of_ty = |ty: Ty<'tcx>| -> Option<Abi> {
479                 match tcx.layout_of(param_env.and(ty)) {
480                     Ok(layout) => Some(layout.abi),
481                     Err(err) => {
482                         // #78372
483                         tcx.sess.delay_span_bug(
484                             tcx.def_span(method.def_id),
485                             &format!("error: {}\n while computing layout for type {:?}", err, ty),
486                         );
487                         None
488                     }
489                 }
490             };
491
492             // e.g., `Rc<()>`
493             let unit_receiver_ty =
494                 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
495
496             match abi_of_ty(unit_receiver_ty) {
497                 Some(Abi::Scalar(..)) => (),
498                 abi => {
499                     tcx.sess.delay_span_bug(
500                         tcx.def_span(method.def_id),
501                         &format!(
502                             "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
503                             abi
504                         ),
505                     );
506                 }
507             }
508
509             let trait_object_ty =
510                 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
511
512             // e.g., `Rc<dyn Trait>`
513             let trait_object_receiver =
514                 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
515
516             match abi_of_ty(trait_object_receiver) {
517                 Some(Abi::ScalarPair(..)) => (),
518                 abi => {
519                     tcx.sess.delay_span_bug(
520                         tcx.def_span(method.def_id),
521                         &format!(
522                             "receiver when `Self = {}` should have a ScalarPair ABI; found {:?}",
523                             trait_object_ty, abi
524                         ),
525                     );
526                 }
527             }
528         }
529     }
530
531     // NOTE: This check happens last, because it results in a lint, and not a
532     // hard error.
533     if tcx
534         .predicates_of(method.def_id)
535         .predicates
536         .iter()
537         // A trait object can't claim to live more than the concrete type,
538         // so outlives predicates will always hold.
539         .cloned()
540         .filter(|(p, _)| p.to_opt_type_outlives().is_none())
541         .any(|pred| contains_illegal_self_type_reference(tcx, trait_def_id, pred))
542     {
543         return Some(MethodViolationCode::WhereClauseReferencesSelf);
544     }
545
546     None
547 }
548
549 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
550 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
551 fn receiver_for_self_ty<'tcx>(
552     tcx: TyCtxt<'tcx>,
553     receiver_ty: Ty<'tcx>,
554     self_ty: Ty<'tcx>,
555     method_def_id: DefId,
556 ) -> Ty<'tcx> {
557     debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
558     let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
559         if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
560     });
561
562     let result = EarlyBinder(receiver_ty).subst(tcx, substs);
563     debug!(
564         "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
565         receiver_ty, self_ty, method_def_id, result
566     );
567     result
568 }
569
570 /// Creates the object type for the current trait. For example,
571 /// if the current trait is `Deref`, then this will be
572 /// `dyn Deref<Target = Self::Target> + 'static`.
573 #[instrument(level = "trace", skip(tcx), ret)]
574 fn object_ty_for_trait<'tcx>(
575     tcx: TyCtxt<'tcx>,
576     trait_def_id: DefId,
577     lifetime: ty::Region<'tcx>,
578 ) -> Ty<'tcx> {
579     let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
580     debug!(?trait_ref);
581
582     let trait_predicate = trait_ref.map_bound(|trait_ref| {
583         ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref))
584     });
585     debug!(?trait_predicate);
586
587     let mut elaborated_predicates: Vec<_> = elaborate_trait_ref(tcx, trait_ref)
588         .filter_map(|obligation| {
589             debug!(?obligation);
590             let pred = obligation.predicate.to_opt_poly_projection_pred()?;
591             Some(pred.map_bound(|p| {
592                 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
593                     item_def_id: p.projection_ty.item_def_id,
594                     substs: p.projection_ty.substs,
595                     term: p.term,
596                 })
597             }))
598         })
599         .collect();
600     // NOTE: Since #37965, the existential predicates list has depended on the
601     // list of predicates to be sorted. This is mostly to enforce that the primary
602     // predicate comes first.
603     elaborated_predicates.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
604     elaborated_predicates.dedup();
605
606     let existential_predicates = tcx
607         .mk_poly_existential_predicates(iter::once(trait_predicate).chain(elaborated_predicates));
608     debug!(?existential_predicates);
609
610     tcx.mk_dynamic(existential_predicates, lifetime, ty::Dyn)
611 }
612
613 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
614 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
615 /// in the following way:
616 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
617 /// - require the following bound:
618 ///
619 ///   ```ignore (not-rust)
620 ///   Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
621 ///   ```
622 ///
623 ///   where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
624 ///   (substitution notation).
625 ///
626 /// Some examples of receiver types and their required obligation:
627 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
628 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
629 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
630 ///
631 /// The only case where the receiver is not dispatchable, but is still a valid receiver
632 /// type (just not object-safe), is when there is more than one level of pointer indirection.
633 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
634 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
635 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
636 /// contained by the trait object, because the object that needs to be coerced is behind
637 /// a pointer.
638 ///
639 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
640 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
641 /// is stabilized, see tracking issue <https://github.com/rust-lang/rust/issues/43561>).
642 /// Instead, we fudge a little by introducing a new type parameter `U` such that
643 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
644 /// Written as a chalk-style query:
645 /// ```ignore (not-rust)
646 /// forall (U: Trait + ?Sized) {
647 ///     if (Self: Unsize<U>) {
648 ///         Receiver: DispatchFromDyn<Receiver[Self => U]>
649 ///     }
650 /// }
651 /// ```
652 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
653 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
654 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
655 //
656 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
657 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
658 // `self: Wrapper<Self>`.
659 #[allow(dead_code)]
660 fn receiver_is_dispatchable<'tcx>(
661     tcx: TyCtxt<'tcx>,
662     method: &ty::AssocItem,
663     receiver_ty: Ty<'tcx>,
664 ) -> bool {
665     debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
666
667     let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
668     let (Some(unsize_did), Some(dispatch_from_dyn_did)) = traits else {
669         debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
670         return false;
671     };
672
673     // the type `U` in the query
674     // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
675     // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
676     // replace this with `dyn Trait`
677     let unsized_self_ty: Ty<'tcx> =
678         tcx.mk_ty_param(u32::MAX, Symbol::intern("RustaceansAreAwesome"));
679
680     // `Receiver[Self => U]`
681     let unsized_receiver_ty =
682         receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
683
684     // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
685     // `U: ?Sized` is already implied here
686     let param_env = {
687         let param_env = tcx.param_env(method.def_id);
688
689         // Self: Unsize<U>
690         let unsize_predicate = ty::Binder::dummy(
691             tcx.mk_trait_ref(unsize_did, [tcx.types.self_param, unsized_self_ty]),
692         )
693         .without_const()
694         .to_predicate(tcx);
695
696         // U: Trait<Arg1, ..., ArgN>
697         let trait_predicate = {
698             let substs =
699                 InternalSubsts::for_item(tcx, method.trait_container(tcx).unwrap(), |param, _| {
700                     if param.index == 0 {
701                         unsized_self_ty.into()
702                     } else {
703                         tcx.mk_param_from_def(param)
704                     }
705                 });
706
707             ty::Binder::dummy(ty::TraitRef { def_id: unsize_did, substs })
708                 .without_const()
709                 .to_predicate(tcx)
710         };
711
712         let caller_bounds: Vec<Predicate<'tcx>> =
713             param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]).collect();
714
715         ty::ParamEnv::new(
716             tcx.intern_predicates(&caller_bounds),
717             param_env.reveal(),
718             param_env.constness(),
719         )
720     };
721
722     // Receiver: DispatchFromDyn<Receiver[Self => U]>
723     let obligation = {
724         let predicate = ty::Binder::dummy(
725             tcx.mk_trait_ref(dispatch_from_dyn_did, [receiver_ty, unsized_receiver_ty]),
726         )
727         .without_const();
728
729         Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate)
730     };
731
732     let infcx = tcx.infer_ctxt().build();
733     // the receiver is dispatchable iff the obligation holds
734     infcx.predicate_must_hold_modulo_regions(&obligation)
735 }
736
737 fn contains_illegal_self_type_reference<'tcx, T: TypeVisitable<'tcx>>(
738     tcx: TyCtxt<'tcx>,
739     trait_def_id: DefId,
740     value: T,
741 ) -> bool {
742     // This is somewhat subtle. In general, we want to forbid
743     // references to `Self` in the argument and return types,
744     // since the value of `Self` is erased. However, there is one
745     // exception: it is ok to reference `Self` in order to access
746     // an associated type of the current trait, since we retain
747     // the value of those associated types in the object type
748     // itself.
749     //
750     // ```rust
751     // trait SuperTrait {
752     //     type X;
753     // }
754     //
755     // trait Trait : SuperTrait {
756     //     type Y;
757     //     fn foo(&self, x: Self) // bad
758     //     fn foo(&self) -> Self // bad
759     //     fn foo(&self) -> Option<Self> // bad
760     //     fn foo(&self) -> Self::Y // OK, desugars to next example
761     //     fn foo(&self) -> <Self as Trait>::Y // OK
762     //     fn foo(&self) -> Self::X // OK, desugars to next example
763     //     fn foo(&self) -> <Self as SuperTrait>::X // OK
764     // }
765     // ```
766     //
767     // However, it is not as simple as allowing `Self` in a projected
768     // type, because there are illegal ways to use `Self` as well:
769     //
770     // ```rust
771     // trait Trait : SuperTrait {
772     //     ...
773     //     fn foo(&self) -> <Self as SomeOtherTrait>::X;
774     // }
775     // ```
776     //
777     // Here we will not have the type of `X` recorded in the
778     // object type, and we cannot resolve `Self as SomeOtherTrait`
779     // without knowing what `Self` is.
780
781     struct IllegalSelfTypeVisitor<'tcx> {
782         tcx: TyCtxt<'tcx>,
783         trait_def_id: DefId,
784         supertraits: Option<Vec<DefId>>,
785     }
786
787     impl<'tcx> TypeVisitor<'tcx> for IllegalSelfTypeVisitor<'tcx> {
788         type BreakTy = ();
789
790         fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
791             match t.kind() {
792                 ty::Param(_) => {
793                     if t == self.tcx.types.self_param {
794                         ControlFlow::BREAK
795                     } else {
796                         ControlFlow::CONTINUE
797                     }
798                 }
799                 ty::Projection(ref data)
800                     if self.tcx.def_kind(data.item_def_id) == DefKind::ImplTraitPlaceholder =>
801                 {
802                     // We'll deny these later in their own pass
803                     ControlFlow::CONTINUE
804                 }
805                 ty::Projection(ref data) => {
806                     // This is a projected type `<Foo as SomeTrait>::X`.
807
808                     // Compute supertraits of current trait lazily.
809                     if self.supertraits.is_none() {
810                         let trait_ref = ty::TraitRef::identity(self.tcx, self.trait_def_id);
811                         self.supertraits = Some(
812                             traits::supertraits(self.tcx, trait_ref).map(|t| t.def_id()).collect(),
813                         );
814                     }
815
816                     // Determine whether the trait reference `Foo as
817                     // SomeTrait` is in fact a supertrait of the
818                     // current trait. In that case, this type is
819                     // legal, because the type `X` will be specified
820                     // in the object type.  Note that we can just use
821                     // direct equality here because all of these types
822                     // are part of the formal parameter listing, and
823                     // hence there should be no inference variables.
824                     let is_supertrait_of_current_trait = self
825                         .supertraits
826                         .as_ref()
827                         .unwrap()
828                         .contains(&data.trait_ref(self.tcx).def_id);
829
830                     if is_supertrait_of_current_trait {
831                         ControlFlow::CONTINUE // do not walk contained types, do not report error, do collect $200
832                     } else {
833                         t.super_visit_with(self) // DO walk contained types, POSSIBLY reporting an error
834                     }
835                 }
836                 _ => t.super_visit_with(self), // walk contained types, if any
837             }
838         }
839
840         fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
841             // Constants can only influence object safety if they reference `Self`.
842             // This is only possible for unevaluated constants, so we walk these here.
843             //
844             // If `AbstractConst::from_const` returned an error we already failed compilation
845             // so we don't have to emit an additional error here.
846             use rustc_middle::ty::abstract_const::Node;
847             if let Ok(Some(ct)) = AbstractConst::from_const(self.tcx, ct) {
848                 walk_abstract_const(self.tcx, ct, |node| match node.root(self.tcx) {
849                     Node::Leaf(leaf) => self.visit_const(leaf),
850                     Node::Cast(_, _, ty) => self.visit_ty(ty),
851                     Node::Binop(..) | Node::UnaryOp(..) | Node::FunctionCall(_, _) => {
852                         ControlFlow::CONTINUE
853                     }
854                 })
855             } else {
856                 ct.super_visit_with(self)
857             }
858         }
859     }
860
861     value
862         .visit_with(&mut IllegalSelfTypeVisitor { tcx, trait_def_id, supertraits: None })
863         .is_break()
864 }
865
866 pub fn contains_illegal_impl_trait_in_trait<'tcx>(
867     tcx: TyCtxt<'tcx>,
868     fn_def_id: DefId,
869     ty: ty::Binder<'tcx, Ty<'tcx>>,
870 ) -> Option<MethodViolationCode> {
871     // This would be caught below, but rendering the error as a separate
872     // `async-specific` message is better.
873     if tcx.asyncness(fn_def_id).is_async() {
874         return Some(MethodViolationCode::AsyncFn);
875     }
876
877     // FIXME(RPITIT): Perhaps we should use a visitor here?
878     ty.skip_binder().walk().find_map(|arg| {
879         if let ty::GenericArgKind::Type(ty) = arg.unpack()
880             && let ty::Projection(proj) = ty.kind()
881             && tcx.def_kind(proj.item_def_id) == DefKind::ImplTraitPlaceholder
882         {
883             Some(MethodViolationCode::ReferencesImplTraitInTrait(tcx.def_span(proj.item_def_id)))
884         } else {
885             None
886         }
887     })
888 }
889
890 pub fn provide(providers: &mut ty::query::Providers) {
891     *providers = ty::query::Providers { object_safety_violations, ..*providers };
892 }