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