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::traits::{self, Obligation, ObligationCause};
14 use crate::ty::subst::{InternalSubsts, Subst};
15 use crate::ty::{self, Predicate, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
16 use rustc_errors::Applicability;
18 use rustc_hir::def_id::DefId;
19 use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
20 use rustc_span::symbol::Symbol;
21 use rustc_span::{Span, DUMMY_SP};
22 use smallvec::{smallvec, SmallVec};
26 use std::iter::{self};
28 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
29 pub enum ObjectSafetyViolation {
30 /// `Self: Sized` declared on the trait.
31 SizedSelf(SmallVec<[Span; 1]>),
33 /// Supertrait reference references `Self` an in illegal location
34 /// (e.g., `trait Foo : Bar<Self>`).
37 /// Method has something illegal.
38 Method(ast::Name, MethodViolationCode, Span),
41 AssocConst(ast::Name, Span),
44 impl ObjectSafetyViolation {
45 pub fn error_msg(&self) -> Cow<'static, str> {
47 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
48 ObjectSafetyViolation::SupertraitSelf => {
49 "it cannot use `Self` as a type parameter in the supertraits or `where`-clauses"
52 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
53 format!("associated function `{}` has no `self` parameter", name).into()
55 ObjectSafetyViolation::Method(
57 MethodViolationCode::ReferencesSelfInput(_),
59 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
60 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
61 format!("method `{}` references the `Self` type in this parameter", name).into()
63 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
64 format!("method `{}` references the `Self` type in its return type", name).into()
66 ObjectSafetyViolation::Method(
68 MethodViolationCode::WhereClauseReferencesSelf,
71 format!("method `{}` references the `Self` type in its `where` clause", name).into()
73 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
74 format!("method `{}` has generic type parameters", name).into()
76 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
77 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
79 ObjectSafetyViolation::AssocConst(_, DUMMY_SP) => {
80 "it cannot contain associated consts".into()
82 ObjectSafetyViolation::AssocConst(name, _) => {
83 format!("it cannot contain associated consts like `{}`", name).into()
88 pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
90 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf => {
93 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
95 "consider turning `{}` into a method by giving it a `&self` argument or \
96 constraining it so it does not apply to trait objects",
99 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
101 ObjectSafetyViolation::Method(
103 MethodViolationCode::UndispatchableReceiver,
106 format!("consider changing method `{}`'s `self` parameter to be `&self`", name)
108 Some(("&Self".to_string(), span)),
110 ObjectSafetyViolation::AssocConst(name, _)
111 | ObjectSafetyViolation::Method(name, ..) => {
112 (format!("consider moving `{}` to another trait", name), None)
117 pub fn spans(&self) -> SmallVec<[Span; 1]> {
118 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
119 // diagnostics use a `note` instead of a `span_label`.
121 ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
122 ObjectSafetyViolation::AssocConst(_, span)
123 | ObjectSafetyViolation::Method(_, _, span)
124 if *span != DUMMY_SP =>
133 /// Reasons a method might not be object-safe.
134 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
135 pub enum MethodViolationCode {
137 StaticMethod(Option<(&'static str, Span)>),
139 /// e.g., `fn foo(&self, x: Self)`
140 ReferencesSelfInput(usize),
142 /// e.g., `fn foo(&self) -> Self`
143 ReferencesSelfOutput,
145 /// e.g., `fn foo(&self) where Self: Clone`
146 WhereClauseReferencesSelf,
148 /// e.g., `fn foo<A>()`
151 /// the method's receiver (`self` argument) can't be dispatched on
152 UndispatchableReceiver,
155 /// Returns the object safety violations that affect
156 /// astconv -- currently, `Self` in supertraits. This is needed
157 /// because `object_safety_violations` can't be used during
159 pub fn astconv_object_safety_violations(
162 ) -> Vec<ObjectSafetyViolation> {
163 debug_assert!(tcx.generics_of(trait_def_id).has_self);
164 let violations = traits::supertrait_def_ids(tcx, trait_def_id)
165 .filter(|&def_id| predicates_reference_self(tcx, def_id, true))
166 .map(|_| ObjectSafetyViolation::SupertraitSelf)
169 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
174 pub fn object_safety_violations(
177 ) -> Vec<ObjectSafetyViolation> {
178 debug_assert!(tcx.generics_of(trait_def_id).has_self);
179 debug!("object_safety_violations: {:?}", trait_def_id);
181 traits::supertrait_def_ids(tcx, trait_def_id)
182 .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id))
186 /// We say a method is *vtable safe* if it can be invoked on a trait
187 /// object. Note that object-safe traits can have some
188 /// non-vtable-safe methods, so long as they require `Self: Sized` or
189 /// otherwise ensure that they cannot be used when `Self = Trait`.
190 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
191 debug_assert!(tcx.generics_of(trait_def_id).has_self);
192 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
193 // Any method that has a `Self: Sized` bound cannot be called.
194 if generics_require_sized_self(tcx, method.def_id) {
198 match virtual_call_violation_for_method(tcx, trait_def_id, method) {
199 None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
204 fn object_safety_violations_for_trait(
207 ) -> Vec<ObjectSafetyViolation> {
208 // Check methods for violations.
209 let mut violations: Vec<_> = tcx
210 .associated_items(trait_def_id)
211 .filter(|item| item.kind == ty::AssocKind::Method)
213 object_safety_violation_for_method(tcx, trait_def_id, &item)
214 .map(|(code, span)| ObjectSafetyViolation::Method(item.ident.name, code, span))
216 .filter(|violation| {
217 if let ObjectSafetyViolation::Method(
219 MethodViolationCode::WhereClauseReferencesSelf,
223 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
224 // It's also hard to get a use site span, so we use the method definition span.
225 let mut err = tcx.struct_span_lint_hir(
226 WHERE_CLAUSES_OBJECT_SAFETY,
230 "the trait `{}` cannot be made into an object",
231 tcx.def_path_str(trait_def_id)
234 let node = tcx.hir().get_if_local(trait_def_id);
235 let msg = if let Some(hir::Node::Item(item)) = node {
236 err.span_label(item.ident.span, "this trait cannot be made into an object...");
237 format!("...because {}", violation.error_msg())
240 "the trait cannot be made into an object because {}",
241 violation.error_msg()
244 err.span_label(*span, &msg);
245 match (node, violation.solution()) {
246 (Some(_), Some((note, None))) => {
249 (Some(_), Some((note, Some((sugg, span))))) => {
250 err.span_suggestion(span, ¬e, sugg, Applicability::MachineApplicable);
252 // Only provide the help if its a local trait, otherwise it's not actionable.
263 // Check the trait itself.
264 if trait_has_sized_self(tcx, trait_def_id) {
265 // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
266 let spans = get_sized_bounds(tcx, trait_def_id);
267 violations.push(ObjectSafetyViolation::SizedSelf(spans));
269 if predicates_reference_self(tcx, trait_def_id, false) {
270 violations.push(ObjectSafetyViolation::SupertraitSelf);
274 tcx.associated_items(trait_def_id)
275 .filter(|item| item.kind == ty::AssocKind::Const)
276 .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)),
280 "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
281 trait_def_id, violations
287 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
289 .get_if_local(trait_def_id)
290 .and_then(|node| match node {
291 hir::Node::Item(hir::Item {
292 kind: hir::ItemKind::Trait(.., generics, bounds, _),
301 hir::WherePredicate::BoundPredicate(pred)
302 if pred.bounded_ty.hir_id.owner_def_id() == trait_def_id =>
304 // Fetch spans for trait bounds that are Sized:
305 // `trait T where Self: Pred`
306 Some(pred.bounds.iter().filter_map(|b| match b {
307 hir::GenericBound::Trait(
309 hir::TraitBoundModifier::None,
310 ) if trait_has_sized_self(
312 trait_ref.trait_ref.trait_def_id(),
324 .chain(bounds.iter().filter_map(|b| match b {
325 hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
326 if trait_has_sized_self(tcx, trait_ref.trait_ref.trait_def_id()) =>
328 // Fetch spans for supertraits that are `Sized`: `trait T: Super`
333 .collect::<SmallVec<[Span; 1]>>(),
337 .unwrap_or_else(SmallVec::new)
340 fn predicates_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId, supertraits_only: bool) -> bool {
341 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
342 let predicates = if supertraits_only {
343 tcx.super_predicates_of(trait_def_id)
345 tcx.predicates_of(trait_def_id)
347 let self_ty = tcx.types.self_param;
348 let has_self_ty = |t: Ty<'_>| t.walk().any(|t| t == self_ty);
352 .map(|(predicate, _)| predicate.subst_supertrait(tcx, &trait_ref))
355 ty::Predicate::Trait(ref data, _) => {
356 // In the case of a trait predicate, we can skip the "self" type.
357 data.skip_binder().input_types().skip(1).any(has_self_ty)
359 ty::Predicate::Projection(ref data) => {
360 // And similarly for projections. This should be redundant with
361 // the previous check because any projection should have a
362 // matching `Trait` predicate with the same inputs, but we do
363 // the check to be safe.
365 // Note that we *do* allow projection *outputs* to contain
366 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
367 // we just require the user to specify *both* outputs
368 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
370 // This is ALT2 in issue #56288, see that for discussion of the
371 // possible alternatives.
379 ty::Predicate::WellFormed(..)
380 | ty::Predicate::ObjectSafe(..)
381 | ty::Predicate::TypeOutlives(..)
382 | ty::Predicate::RegionOutlives(..)
383 | ty::Predicate::ClosureKind(..)
384 | ty::Predicate::Subtype(..)
385 | ty::Predicate::ConstEvaluatable(..) => false,
390 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
391 generics_require_sized_self(tcx, trait_def_id)
394 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
395 let sized_def_id = match tcx.lang_items().sized_trait() {
396 Some(def_id) => def_id,
398 return false; /* No Sized trait, can't require it! */
402 // Search for a predicate like `Self : Sized` amongst the trait bounds.
403 let predicates = tcx.predicates_of(def_id);
404 let predicates = predicates.instantiate_identity(tcx).predicates;
405 elaborate_predicates(tcx, predicates).any(|predicate| match predicate {
406 ty::Predicate::Trait(ref trait_pred, _) => {
407 trait_pred.def_id() == sized_def_id && trait_pred.skip_binder().self_ty().is_param(0)
409 ty::Predicate::Projection(..)
410 | ty::Predicate::Subtype(..)
411 | ty::Predicate::RegionOutlives(..)
412 | ty::Predicate::WellFormed(..)
413 | ty::Predicate::ObjectSafe(..)
414 | ty::Predicate::ClosureKind(..)
415 | ty::Predicate::TypeOutlives(..)
416 | ty::Predicate::ConstEvaluatable(..) => false,
420 /// Returns `Some(_)` if this method makes the containing trait not object safe.
421 fn object_safety_violation_for_method(
424 method: &ty::AssocItem,
425 ) -> Option<(MethodViolationCode, Span)> {
426 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
427 // Any method that has a `Self : Sized` requisite is otherwise
428 // exempt from the regulations.
429 if generics_require_sized_self(tcx, method.def_id) {
433 let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
434 // Get an accurate span depending on the violation.
436 let node = tcx.hir().get_if_local(method.def_id);
437 let span = match (v, node) {
438 (MethodViolationCode::ReferencesSelfInput(arg), Some(node)) => node
440 .and_then(|decl| decl.inputs.get(arg + 1))
441 .map_or(method.ident.span, |arg| arg.span),
442 (MethodViolationCode::UndispatchableReceiver, Some(node)) => node
444 .and_then(|decl| decl.inputs.get(0))
445 .map_or(method.ident.span, |arg| arg.span),
446 (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
447 node.fn_decl().map_or(method.ident.span, |decl| decl.output.span())
449 _ => method.ident.span,
455 /// Returns `Some(_)` if this method cannot be called on a trait
456 /// object; this does not necessarily imply that the enclosing trait
457 /// is not object safe, because the method might have a where clause
459 fn virtual_call_violation_for_method<'tcx>(
462 method: &ty::AssocItem,
463 ) -> Option<MethodViolationCode> {
464 // The method's first parameter must be named `self`
465 if !method.method_has_self_argument {
466 // We'll attempt to provide a structured suggestion for `Self: Sized`.
468 tcx.hir().get_if_local(method.def_id).as_ref().and_then(|node| node.generics()).map(
469 |generics| match generics.where_clause.predicates {
470 [] => (" where Self: Sized", generics.where_clause.span),
471 [.., pred] => (", Self: Sized", pred.span().shrink_to_hi()),
474 return Some(MethodViolationCode::StaticMethod(sugg));
477 let sig = tcx.fn_sig(method.def_id);
479 for (i, input_ty) in sig.skip_binder().inputs()[1..].iter().enumerate() {
480 if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) {
481 return Some(MethodViolationCode::ReferencesSelfInput(i));
484 if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output().skip_binder()) {
485 return Some(MethodViolationCode::ReferencesSelfOutput);
488 // We can't monomorphize things like `fn foo<A>(...)`.
489 let own_counts = tcx.generics_of(method.def_id).own_counts();
490 if own_counts.types + own_counts.consts != 0 {
491 return Some(MethodViolationCode::Generic);
495 .predicates_of(method.def_id)
498 // A trait object can't claim to live more than the concrete type,
499 // so outlives predicates will always hold.
501 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
503 // Do a shallow visit so that `contains_illegal_self_type_reference`
504 // may apply it's custom visiting.
505 .visit_tys_shallow(|t| contains_illegal_self_type_reference(tcx, trait_def_id, t))
507 return Some(MethodViolationCode::WhereClauseReferencesSelf);
511 tcx.liberate_late_bound_regions(method.def_id, &sig.map_bound(|sig| sig.inputs()[0]));
513 // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
514 // However, this is already considered object-safe. We allow it as a special case here.
515 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
516 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
517 if receiver_ty != tcx.types.self_param {
518 if !receiver_is_dispatchable(tcx, method, receiver_ty) {
519 return Some(MethodViolationCode::UndispatchableReceiver);
521 // Do sanity check to make sure the receiver actually has the layout of a pointer.
523 use crate::ty::layout::Abi;
525 let param_env = tcx.param_env(method.def_id);
527 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
528 match tcx.layout_of(param_env.and(ty)) {
529 Ok(layout) => &layout.abi,
530 Err(err) => bug!("error: {}\n while computing layout for type {:?}", err, ty),
535 let unit_receiver_ty =
536 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
538 match abi_of_ty(unit_receiver_ty) {
539 &Abi::Scalar(..) => (),
541 tcx.sess.delay_span_bug(
542 tcx.def_span(method.def_id),
544 "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
551 let trait_object_ty =
552 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
554 // e.g., `Rc<dyn Trait>`
555 let trait_object_receiver =
556 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
558 match abi_of_ty(trait_object_receiver) {
559 &Abi::ScalarPair(..) => (),
561 tcx.sess.delay_span_bug(
562 tcx.def_span(method.def_id),
564 "receiver when `Self = {}` should have a ScalarPair ABI; \
577 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
578 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
579 fn receiver_for_self_ty<'tcx>(
581 receiver_ty: Ty<'tcx>,
583 method_def_id: DefId,
585 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
586 let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
587 if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
590 let result = receiver_ty.subst(tcx, substs);
592 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
593 receiver_ty, self_ty, method_def_id, result
598 /// Creates the object type for the current trait. For example,
599 /// if the current trait is `Deref`, then this will be
600 /// `dyn Deref<Target = Self::Target> + 'static`.
601 fn object_ty_for_trait<'tcx>(
604 lifetime: ty::Region<'tcx>,
606 debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
608 let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
610 let trait_predicate =
611 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
613 let mut associated_types = traits::supertraits(tcx, ty::Binder::dummy(trait_ref))
614 .flat_map(|super_trait_ref| {
615 tcx.associated_items(super_trait_ref.def_id()).map(move |item| (super_trait_ref, item))
617 .filter(|(_, item)| item.kind == ty::AssocKind::Type)
618 .collect::<Vec<_>>();
620 // existential predicates need to be in a specific order
621 associated_types.sort_by_cached_key(|(_, item)| tcx.def_path_hash(item.def_id));
623 let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
624 // We *can* get bound lifetimes here in cases like
625 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
627 // binder moved to (*)...
628 let super_trait_ref = super_trait_ref.skip_binder();
629 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
630 ty: tcx.mk_projection(item.def_id, super_trait_ref.substs),
631 item_def_id: item.def_id,
632 substs: super_trait_ref.substs,
636 let existential_predicates =
637 tcx.mk_existential_predicates(iter::once(trait_predicate).chain(projection_predicates));
639 let object_ty = tcx.mk_dynamic(
640 // (*) ... binder re-introduced here
641 ty::Binder::bind(existential_predicates),
645 debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
650 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
651 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
652 /// in the following way:
653 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
654 /// - require the following bound:
657 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
660 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
661 /// (substitution notation).
663 /// Some examples of receiver types and their required obligation:
664 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
665 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
666 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
668 /// The only case where the receiver is not dispatchable, but is still a valid receiver
669 /// type (just not object-safe), is when there is more than one level of pointer indirection.
670 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
671 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
672 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
673 /// contained by the trait object, because the object that needs to be coerced is behind
676 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
677 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
678 /// is stabilized, see tracking issue https://github.com/rust-lang/rust/issues/43561).
679 /// Instead, we fudge a little by introducing a new type parameter `U` such that
680 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
681 /// Written as a chalk-style query:
683 /// forall (U: Trait + ?Sized) {
684 /// if (Self: Unsize<U>) {
685 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
689 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
690 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
691 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
693 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
694 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
695 // `self: Wrapper<Self>`.
697 fn receiver_is_dispatchable<'tcx>(
699 method: &ty::AssocItem,
700 receiver_ty: Ty<'tcx>,
702 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
704 let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
705 let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
708 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
712 // the type `U` in the query
713 // use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
714 // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
715 // replace this with `dyn Trait`
716 let unsized_self_ty: Ty<'tcx> =
717 tcx.mk_ty_param(::std::u32::MAX, Symbol::intern("RustaceansAreAwesome"));
719 // `Receiver[Self => U]`
720 let unsized_receiver_ty =
721 receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
723 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
724 // `U: ?Sized` is already implied here
726 let mut param_env = tcx.param_env(method.def_id);
729 let unsize_predicate = ty::TraitRef {
731 substs: tcx.mk_substs_trait(tcx.types.self_param, &[unsized_self_ty.into()]),
736 // U: Trait<Arg1, ..., ArgN>
737 let trait_predicate = {
739 InternalSubsts::for_item(tcx, method.container.assert_trait(), |param, _| {
740 if param.index == 0 {
741 unsized_self_ty.into()
743 tcx.mk_param_from_def(param)
747 ty::TraitRef { def_id: unsize_did, substs }.without_const().to_predicate()
750 let caller_bounds: Vec<Predicate<'tcx>> = param_env
754 .chain(iter::once(unsize_predicate))
755 .chain(iter::once(trait_predicate))
758 param_env.caller_bounds = tcx.intern_predicates(&caller_bounds);
763 // Receiver: DispatchFromDyn<Receiver[Self => U]>
765 let predicate = ty::TraitRef {
766 def_id: dispatch_from_dyn_did,
767 substs: tcx.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
772 Obligation::new(ObligationCause::dummy(), param_env, predicate)
775 tcx.infer_ctxt().enter(|ref infcx| {
776 // the receiver is dispatchable iff the obligation holds
777 infcx.predicate_must_hold_modulo_regions(&obligation)
781 fn contains_illegal_self_type_reference<'tcx>(
786 // This is somewhat subtle. In general, we want to forbid
787 // references to `Self` in the argument and return types,
788 // since the value of `Self` is erased. However, there is one
789 // exception: it is ok to reference `Self` in order to access
790 // an associated type of the current trait, since we retain
791 // the value of those associated types in the object type
795 // trait SuperTrait {
799 // trait Trait : SuperTrait {
801 // fn foo(&self, x: Self) // bad
802 // fn foo(&self) -> Self // bad
803 // fn foo(&self) -> Option<Self> // bad
804 // fn foo(&self) -> Self::Y // OK, desugars to next example
805 // fn foo(&self) -> <Self as Trait>::Y // OK
806 // fn foo(&self) -> Self::X // OK, desugars to next example
807 // fn foo(&self) -> <Self as SuperTrait>::X // OK
811 // However, it is not as simple as allowing `Self` in a projected
812 // type, because there are illegal ways to use `Self` as well:
815 // trait Trait : SuperTrait {
817 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
821 // Here we will not have the type of `X` recorded in the
822 // object type, and we cannot resolve `Self as SomeOtherTrait`
823 // without knowing what `Self` is.
825 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
826 let mut error = false;
827 let self_ty = tcx.types.self_param;
835 false // no contained types to walk
838 ty::Projection(ref data) => {
839 // This is a projected type `<Foo as SomeTrait>::X`.
841 // Compute supertraits of current trait lazily.
842 if supertraits.is_none() {
843 let trait_ref = ty::Binder::bind(ty::TraitRef::identity(tcx, trait_def_id));
844 supertraits = Some(traits::supertraits(tcx, trait_ref).collect());
847 // Determine whether the trait reference `Foo as
848 // SomeTrait` is in fact a supertrait of the
849 // current trait. In that case, this type is
850 // legal, because the type `X` will be specified
851 // in the object type. Note that we can just use
852 // direct equality here because all of these types
853 // are part of the formal parameter listing, and
854 // hence there should be no inference variables.
855 let projection_trait_ref = ty::Binder::bind(data.trait_ref(tcx));
856 let is_supertrait_of_current_trait =
857 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
859 if is_supertrait_of_current_trait {
860 false // do not walk contained types, do not report error, do collect $200
862 true // DO walk contained types, POSSIBLY reporting an error
866 _ => true, // walk contained types, if any
873 pub(super) fn is_object_safe_provider(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
874 object_safety_violations(tcx, trait_def_id).is_empty()