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,
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.
11 use super::elaborate_predicates;
13 use crate::infer::TyCtxtInferExt;
14 use crate::traits::const_evaluatable::{self, AbstractConst};
15 use crate::traits::query::evaluate_obligation::InferCtxtExt;
16 use crate::traits::{self, Obligation, ObligationCause};
17 use rustc_errors::FatalError;
19 use rustc_hir::def_id::DefId;
20 use rustc_middle::ty::subst::{GenericArg, InternalSubsts, Subst};
21 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor};
22 use rustc_middle::ty::{Predicate, ToPredicate};
23 use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
24 use rustc_span::symbol::Symbol;
25 use rustc_span::{MultiSpan, Span};
26 use smallvec::SmallVec;
29 use std::ops::ControlFlow;
31 pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation};
33 /// Returns the object safety violations that affect
34 /// astconv -- currently, `Self` in supertraits. This is needed
35 /// because `object_safety_violations` can't be used during
37 pub fn astconv_object_safety_violations(
40 ) -> Vec<ObjectSafetyViolation> {
41 debug_assert!(tcx.generics_of(trait_def_id).has_self);
42 let violations = traits::supertrait_def_ids(tcx, trait_def_id)
43 .map(|def_id| predicates_reference_self(tcx, def_id, true))
44 .filter(|spans| !spans.is_empty())
45 .map(ObjectSafetyViolation::SupertraitSelf)
48 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
53 fn object_safety_violations(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &'_ [ObjectSafetyViolation] {
54 debug_assert!(tcx.generics_of(trait_def_id).has_self);
55 debug!("object_safety_violations: {:?}", trait_def_id);
57 tcx.arena.alloc_from_iter(
58 traits::supertrait_def_ids(tcx, trait_def_id)
59 .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id)),
63 /// We say a method is *vtable safe* if it can be invoked on a trait
64 /// object. Note that object-safe traits can have some
65 /// non-vtable-safe methods, so long as they require `Self: Sized` or
66 /// otherwise ensure that they cannot be used when `Self = Trait`.
67 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
68 debug_assert!(tcx.generics_of(trait_def_id).has_self);
69 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
70 // Any method that has a `Self: Sized` bound cannot be called.
71 if generics_require_sized_self(tcx, method.def_id) {
75 match virtual_call_violation_for_method(tcx, trait_def_id, method) {
76 None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
81 fn object_safety_violations_for_trait(
84 ) -> Vec<ObjectSafetyViolation> {
85 // Check methods for violations.
86 let mut violations: Vec<_> = tcx
87 .associated_items(trait_def_id)
88 .in_definition_order()
89 .filter(|item| item.kind == ty::AssocKind::Fn)
91 object_safety_violation_for_method(tcx, trait_def_id, &item)
92 .map(|(code, span)| ObjectSafetyViolation::Method(item.name, code, span))
95 if let ObjectSafetyViolation::Method(
97 MethodViolationCode::WhereClauseReferencesSelf,
101 lint_object_unsafe_trait(tcx, *span, trait_def_id, violation);
109 // Check the trait itself.
110 if trait_has_sized_self(tcx, trait_def_id) {
111 // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
112 let spans = get_sized_bounds(tcx, trait_def_id);
113 violations.push(ObjectSafetyViolation::SizedSelf(spans));
115 let spans = predicates_reference_self(tcx, trait_def_id, false);
116 if !spans.is_empty() {
117 violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
119 let spans = bounds_reference_self(tcx, trait_def_id);
120 if !spans.is_empty() {
121 violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
125 tcx.associated_items(trait_def_id)
126 .in_definition_order()
127 .filter(|item| item.kind == ty::AssocKind::Const)
129 let ident = item.ident(tcx);
130 ObjectSafetyViolation::AssocConst(ident.name, ident.span)
135 tcx.associated_items(trait_def_id)
136 .in_definition_order()
137 .filter(|item| item.kind == ty::AssocKind::Type)
138 .filter(|item| !tcx.generics_of(item.def_id).params.is_empty())
140 let ident = item.ident(tcx);
141 ObjectSafetyViolation::GAT(ident.name, ident.span)
146 "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
147 trait_def_id, violations
153 /// Lint object-unsafe trait.
154 fn lint_object_unsafe_trait(
158 violation: &ObjectSafetyViolation,
160 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
161 // It's also hard to get a use site span, so we use the method definition span.
162 tcx.struct_span_lint_hir(WHERE_CLAUSES_OBJECT_SAFETY, hir::CRATE_HIR_ID, span, |lint| {
163 let mut err = lint.build(&format!(
164 "the trait `{}` cannot be made into an object",
165 tcx.def_path_str(trait_def_id)
167 let node = tcx.hir().get_if_local(trait_def_id);
168 let mut spans = MultiSpan::from_span(span);
169 if let Some(hir::Node::Item(item)) = node {
170 spans.push_span_label(
172 "this trait cannot be made into an object...".into(),
174 spans.push_span_label(span, format!("...because {}", violation.error_msg()));
176 spans.push_span_label(
179 "the trait cannot be made into an object because {}",
180 violation.error_msg()
186 "for a trait to be \"object safe\" it needs to allow building a vtable to allow the \
187 call to be resolvable dynamically; for more information visit \
188 <https://doc.rust-lang.org/reference/items/traits.html#object-safety>",
191 // Only provide the help if its a local trait, otherwise it's not
192 violation.solution(&mut err);
198 fn sized_trait_bound_spans<'tcx>(
200 bounds: hir::GenericBounds<'tcx>,
201 ) -> impl 'tcx + Iterator<Item = Span> {
202 bounds.iter().filter_map(move |b| match b {
203 hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
204 if trait_has_sized_self(
206 trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
209 // Fetch spans for supertraits that are `Sized`: `trait T: Super`
216 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
218 .get_if_local(trait_def_id)
219 .and_then(|node| match node {
220 hir::Node::Item(hir::Item {
221 kind: hir::ItemKind::Trait(.., generics, bounds, _),
230 hir::WherePredicate::BoundPredicate(pred)
231 if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
233 // Fetch spans for trait bounds that are Sized:
234 // `trait T where Self: Pred`
235 Some(sized_trait_bound_spans(tcx, pred.bounds))
241 // Fetch spans for supertraits that are `Sized`: `trait T: Super`.
242 .chain(sized_trait_bound_spans(tcx, bounds))
243 .collect::<SmallVec<[Span; 1]>>(),
247 .unwrap_or_else(SmallVec::new)
250 fn predicates_reference_self(
253 supertraits_only: bool,
254 ) -> SmallVec<[Span; 1]> {
255 let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
256 let predicates = if supertraits_only {
257 tcx.super_predicates_of(trait_def_id)
259 tcx.predicates_of(trait_def_id)
264 .map(|&(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
265 .filter_map(|predicate| predicate_references_self(tcx, predicate))
269 fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
270 tcx.associated_items(trait_def_id)
271 .in_definition_order()
272 .filter(|item| item.kind == ty::AssocKind::Type)
273 .flat_map(|item| tcx.explicit_item_bounds(item.def_id))
274 .filter_map(|pred_span| predicate_references_self(tcx, *pred_span))
278 fn predicate_references_self<'tcx>(
280 (predicate, sp): (ty::Predicate<'tcx>, Span),
282 let self_ty = tcx.types.self_param;
283 let has_self_ty = |arg: &GenericArg<'_>| arg.walk().any(|arg| arg == self_ty.into());
284 match predicate.kind().skip_binder() {
285 ty::PredicateKind::Trait(ref data) => {
286 // In the case of a trait predicate, we can skip the "self" type.
287 if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
289 ty::PredicateKind::Projection(ref data) => {
290 // And similarly for projections. This should be redundant with
291 // the previous check because any projection should have a
292 // matching `Trait` predicate with the same inputs, but we do
293 // the check to be safe.
295 // It's also won't be redundant if we allow type-generic associated
296 // types for trait objects.
298 // Note that we *do* allow projection *outputs* to contain
299 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
300 // we just require the user to specify *both* outputs
301 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
303 // This is ALT2 in issue #56288, see that for discussion of the
304 // possible alternatives.
305 if data.projection_ty.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
307 ty::PredicateKind::WellFormed(..)
308 | ty::PredicateKind::ObjectSafe(..)
309 | ty::PredicateKind::TypeOutlives(..)
310 | ty::PredicateKind::RegionOutlives(..)
311 | ty::PredicateKind::ClosureKind(..)
312 | ty::PredicateKind::Subtype(..)
313 | ty::PredicateKind::Coerce(..)
314 | ty::PredicateKind::ConstEvaluatable(..)
315 | ty::PredicateKind::ConstEquate(..)
316 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
320 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
321 generics_require_sized_self(tcx, trait_def_id)
324 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
325 let sized_def_id = match tcx.lang_items().sized_trait() {
326 Some(def_id) => def_id,
328 return false; /* No Sized trait, can't require it! */
332 // Search for a predicate like `Self : Sized` amongst the trait bounds.
333 let predicates = tcx.predicates_of(def_id);
334 let predicates = predicates.instantiate_identity(tcx).predicates;
335 elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| {
336 match obligation.predicate.kind().skip_binder() {
337 ty::PredicateKind::Trait(ref trait_pred) => {
338 trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
340 ty::PredicateKind::Projection(..)
341 | ty::PredicateKind::Subtype(..)
342 | ty::PredicateKind::Coerce(..)
343 | ty::PredicateKind::RegionOutlives(..)
344 | ty::PredicateKind::WellFormed(..)
345 | ty::PredicateKind::ObjectSafe(..)
346 | ty::PredicateKind::ClosureKind(..)
347 | ty::PredicateKind::TypeOutlives(..)
348 | ty::PredicateKind::ConstEvaluatable(..)
349 | ty::PredicateKind::ConstEquate(..)
350 | ty::PredicateKind::TypeWellFormedFromEnv(..) => false,
355 /// Returns `Some(_)` if this method makes the containing trait not object safe.
356 fn object_safety_violation_for_method(
359 method: &ty::AssocItem,
360 ) -> Option<(MethodViolationCode, Span)> {
361 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
362 // Any method that has a `Self : Sized` requisite is otherwise
363 // exempt from the regulations.
364 if generics_require_sized_self(tcx, method.def_id) {
368 let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
369 // Get an accurate span depending on the violation.
371 let node = tcx.hir().get_if_local(method.def_id);
372 let span = match (v, node) {
373 (MethodViolationCode::ReferencesSelfInput(arg), Some(node)) => node
375 .and_then(|decl| decl.inputs.get(arg + 1))
376 .map_or(method.ident(tcx).span, |arg| arg.span),
377 (MethodViolationCode::UndispatchableReceiver, Some(node)) => node
379 .and_then(|decl| decl.inputs.get(0))
380 .map_or(method.ident(tcx).span, |arg| arg.span),
381 (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
382 node.fn_decl().map_or(method.ident(tcx).span, |decl| decl.output.span())
384 _ => method.ident(tcx).span,
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
394 fn virtual_call_violation_for_method<'tcx>(
397 method: &ty::AssocItem,
398 ) -> Option<MethodViolationCode> {
399 let sig = tcx.fn_sig(method.def_id);
401 // The method's first parameter must be named `self`
402 if !method.fn_has_self_parameter {
403 // We'll attempt to provide a structured suggestion for `Self: Sized`.
405 tcx.hir().get_if_local(method.def_id).as_ref().and_then(|node| node.generics()).map(
406 |generics| match generics.where_clause.predicates {
407 [] => (" where Self: Sized", generics.where_clause.span),
408 [.., pred] => (", Self: Sized", pred.span().shrink_to_hi()),
411 // Get the span pointing at where the `self` receiver should be.
412 let sm = tcx.sess.source_map();
413 let self_span = method.ident(tcx).span.to(tcx
415 .span_if_local(method.def_id)
416 .unwrap_or_else(|| sm.next_point(method.ident(tcx).span))
418 let self_span = sm.span_through_char(self_span, '(').shrink_to_hi();
419 return Some(MethodViolationCode::StaticMethod(
422 !sig.inputs().skip_binder().is_empty(),
426 for (i, &input_ty) in sig.skip_binder().inputs()[1..].iter().enumerate() {
427 if contains_illegal_self_type_reference(tcx, trait_def_id, sig.rebind(input_ty)) {
428 return Some(MethodViolationCode::ReferencesSelfInput(i));
431 if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output()) {
432 return Some(MethodViolationCode::ReferencesSelfOutput);
435 // We can't monomorphize things like `fn foo<A>(...)`.
436 let own_counts = tcx.generics_of(method.def_id).own_counts();
437 if own_counts.types + own_counts.consts != 0 {
438 return Some(MethodViolationCode::Generic);
442 .predicates_of(method.def_id)
445 // A trait object can't claim to live more than the concrete type,
446 // so outlives predicates will always hold.
448 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
449 .any(|pred| contains_illegal_self_type_reference(tcx, trait_def_id, pred))
451 return Some(MethodViolationCode::WhereClauseReferencesSelf);
454 let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
456 // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
457 // However, this is already considered object-safe. We allow it as a special case here.
458 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
459 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
460 if receiver_ty != tcx.types.self_param {
461 if !receiver_is_dispatchable(tcx, method, receiver_ty) {
462 return Some(MethodViolationCode::UndispatchableReceiver);
464 // Do sanity check to make sure the receiver actually has the layout of a pointer.
466 use rustc_target::abi::Abi;
468 let param_env = tcx.param_env(method.def_id);
470 let abi_of_ty = |ty: Ty<'tcx>| -> Option<Abi> {
471 match tcx.layout_of(param_env.and(ty)) {
472 Ok(layout) => Some(layout.abi),
475 tcx.sess.delay_span_bug(
476 tcx.def_span(method.def_id),
477 &format!("error: {}\n while computing layout for type {:?}", err, ty),
485 let unit_receiver_ty =
486 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
488 match abi_of_ty(unit_receiver_ty) {
489 Some(Abi::Scalar(..)) => (),
491 tcx.sess.delay_span_bug(
492 tcx.def_span(method.def_id),
494 "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
501 let trait_object_ty =
502 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
504 // e.g., `Rc<dyn Trait>`
505 let trait_object_receiver =
506 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
508 match abi_of_ty(trait_object_receiver) {
509 Some(Abi::ScalarPair(..)) => (),
511 tcx.sess.delay_span_bug(
512 tcx.def_span(method.def_id),
514 "receiver when `Self = {}` should have a ScalarPair ABI; found {:?}",
526 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
527 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
528 fn receiver_for_self_ty<'tcx>(
530 receiver_ty: Ty<'tcx>,
532 method_def_id: DefId,
534 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
535 let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
536 if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
539 let result = receiver_ty.subst(tcx, substs);
541 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
542 receiver_ty, self_ty, method_def_id, result
547 /// Creates the object type for the current trait. For example,
548 /// if the current trait is `Deref`, then this will be
549 /// `dyn Deref<Target = Self::Target> + 'static`.
550 fn object_ty_for_trait<'tcx>(
553 lifetime: ty::Region<'tcx>,
555 debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
557 let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
559 let trait_predicate = trait_ref.map_bound(|trait_ref| {
560 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref))
563 let mut associated_types = traits::supertraits(tcx, trait_ref)
564 .flat_map(|super_trait_ref| {
565 tcx.associated_items(super_trait_ref.def_id())
566 .in_definition_order()
567 .map(move |item| (super_trait_ref, item))
569 .filter(|(_, item)| item.kind == ty::AssocKind::Type)
570 .collect::<Vec<_>>();
572 // existential predicates need to be in a specific order
573 associated_types.sort_by_cached_key(|(_, item)| tcx.def_path_hash(item.def_id));
575 let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
576 // We *can* get bound lifetimes here in cases like
577 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
578 super_trait_ref.map_bound(|super_trait_ref| {
579 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
580 term: tcx.mk_projection(item.def_id, super_trait_ref.substs).into(),
581 item_def_id: item.def_id,
582 substs: super_trait_ref.substs,
587 let existential_predicates = tcx
588 .mk_poly_existential_predicates(iter::once(trait_predicate).chain(projection_predicates));
590 let object_ty = tcx.mk_dynamic(existential_predicates, lifetime);
592 debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
597 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
598 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
599 /// in the following way:
600 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
601 /// - require the following bound:
604 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
607 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
608 /// (substitution notation).
610 /// Some examples of receiver types and their required obligation:
611 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
612 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
613 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
615 /// The only case where the receiver is not dispatchable, but is still a valid receiver
616 /// type (just not object-safe), is when there is more than one level of pointer indirection.
617 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
618 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
619 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
620 /// contained by the trait object, because the object that needs to be coerced is behind
623 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
624 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
625 /// is stabilized, see tracking issue <https://github.com/rust-lang/rust/issues/43561>).
626 /// Instead, we fudge a little by introducing a new type parameter `U` such that
627 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
628 /// Written as a chalk-style query:
630 /// forall (U: Trait + ?Sized) {
631 /// if (Self: Unsize<U>) {
632 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
636 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
637 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
638 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
640 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
641 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
642 // `self: Wrapper<Self>`.
644 fn receiver_is_dispatchable<'tcx>(
646 method: &ty::AssocItem,
647 receiver_ty: Ty<'tcx>,
649 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
651 let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
652 let (Some(unsize_did), Some(dispatch_from_dyn_did)) = traits else {
653 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
657 // the type `U` in the query
658 // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
659 // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
660 // replace this with `dyn Trait`
661 let unsized_self_ty: Ty<'tcx> =
662 tcx.mk_ty_param(u32::MAX, Symbol::intern("RustaceansAreAwesome"));
664 // `Receiver[Self => U]`
665 let unsized_receiver_ty =
666 receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
668 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
669 // `U: ?Sized` is already implied here
671 let param_env = tcx.param_env(method.def_id);
674 let unsize_predicate = ty::Binder::dummy(ty::TraitRef {
676 substs: tcx.mk_substs_trait(tcx.types.self_param, &[unsized_self_ty.into()]),
681 // U: Trait<Arg1, ..., ArgN>
682 let trait_predicate = {
684 InternalSubsts::for_item(tcx, method.container.assert_trait(), |param, _| {
685 if param.index == 0 {
686 unsized_self_ty.into()
688 tcx.mk_param_from_def(param)
692 ty::Binder::dummy(ty::TraitRef { def_id: unsize_did, substs })
697 let caller_bounds: Vec<Predicate<'tcx>> =
698 param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]).collect();
701 tcx.intern_predicates(&caller_bounds),
703 param_env.constness(),
707 // Receiver: DispatchFromDyn<Receiver[Self => U]>
709 let predicate = ty::Binder::dummy(ty::TraitRef {
710 def_id: dispatch_from_dyn_did,
711 substs: tcx.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
716 Obligation::new(ObligationCause::dummy(), param_env, predicate)
719 tcx.infer_ctxt().enter(|ref infcx| {
720 // the receiver is dispatchable iff the obligation holds
721 infcx.predicate_must_hold_modulo_regions(&obligation)
725 fn contains_illegal_self_type_reference<'tcx, T: TypeFoldable<'tcx>>(
730 // This is somewhat subtle. In general, we want to forbid
731 // references to `Self` in the argument and return types,
732 // since the value of `Self` is erased. However, there is one
733 // exception: it is ok to reference `Self` in order to access
734 // an associated type of the current trait, since we retain
735 // the value of those associated types in the object type
739 // trait SuperTrait {
743 // trait Trait : SuperTrait {
745 // fn foo(&self, x: Self) // bad
746 // fn foo(&self) -> Self // bad
747 // fn foo(&self) -> Option<Self> // bad
748 // fn foo(&self) -> Self::Y // OK, desugars to next example
749 // fn foo(&self) -> <Self as Trait>::Y // OK
750 // fn foo(&self) -> Self::X // OK, desugars to next example
751 // fn foo(&self) -> <Self as SuperTrait>::X // OK
755 // However, it is not as simple as allowing `Self` in a projected
756 // type, because there are illegal ways to use `Self` as well:
759 // trait Trait : SuperTrait {
761 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
765 // Here we will not have the type of `X` recorded in the
766 // object type, and we cannot resolve `Self as SomeOtherTrait`
767 // without knowing what `Self` is.
769 struct IllegalSelfTypeVisitor<'tcx> {
772 supertraits: Option<Vec<DefId>>,
775 impl<'tcx> TypeVisitor<'tcx> for IllegalSelfTypeVisitor<'tcx> {
778 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
781 if t == self.tcx.types.self_param {
784 ControlFlow::CONTINUE
787 ty::Projection(ref data) => {
788 // This is a projected type `<Foo as SomeTrait>::X`.
790 // Compute supertraits of current trait lazily.
791 if self.supertraits.is_none() {
792 let trait_ref = ty::TraitRef::identity(self.tcx, self.trait_def_id);
793 self.supertraits = Some(
794 traits::supertraits(self.tcx, trait_ref).map(|t| t.def_id()).collect(),
798 // Determine whether the trait reference `Foo as
799 // SomeTrait` is in fact a supertrait of the
800 // current trait. In that case, this type is
801 // legal, because the type `X` will be specified
802 // in the object type. Note that we can just use
803 // direct equality here because all of these types
804 // are part of the formal parameter listing, and
805 // hence there should be no inference variables.
806 let is_supertrait_of_current_trait = self
810 .contains(&data.trait_ref(self.tcx).def_id);
812 if is_supertrait_of_current_trait {
813 ControlFlow::CONTINUE // do not walk contained types, do not report error, do collect $200
815 t.super_visit_with(self) // DO walk contained types, POSSIBLY reporting an error
818 _ => t.super_visit_with(self), // walk contained types, if any
822 fn visit_unevaluated_const(
824 uv: ty::Unevaluated<'tcx>,
825 ) -> ControlFlow<Self::BreakTy> {
826 // Constants can only influence object safety if they reference `Self`.
827 // This is only possible for unevaluated constants, so we walk these here.
829 // If `AbstractConst::new` returned an error we already failed compilation
830 // so we don't have to emit an additional error here.
832 // We currently recurse into abstract consts here but do not recurse in
833 // `is_const_evaluatable`. This means that the object safety check is more
834 // liberal than the const eval check.
836 // This shouldn't really matter though as we can't really use any
837 // constants which are not considered const evaluatable.
838 use rustc_middle::thir::abstract_const::Node;
839 if let Ok(Some(ct)) = AbstractConst::new(self.tcx, uv.shrink()) {
840 const_evaluatable::walk_abstract_const(self.tcx, ct, |node| {
841 match node.root(self.tcx) {
842 Node::Leaf(leaf) => self.visit_const(leaf),
843 Node::Cast(_, _, ty) => self.visit_ty(ty),
844 Node::Binop(..) | Node::UnaryOp(..) | Node::FunctionCall(_, _) => {
845 ControlFlow::CONTINUE
850 ControlFlow::CONTINUE
856 .visit_with(&mut IllegalSelfTypeVisitor { tcx, trait_def_id, supertraits: None })
860 pub fn provide(providers: &mut ty::query::Providers) {
861 *providers = ty::query::Providers { object_safety_violations, ..*providers };