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::{self, Obligation, ObligationCause};
15 use rustc::ty::subst::{InternalSubsts, Subst};
16 use rustc::ty::{self, Predicate, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
17 use rustc_errors::Applicability;
19 use rustc_hir::def_id::DefId;
20 use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
21 use rustc_span::symbol::Symbol;
22 use rustc_span::{Span, DUMMY_SP};
23 use smallvec::{smallvec, SmallVec};
27 use std::iter::{self};
29 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
30 pub enum ObjectSafetyViolation {
31 /// `Self: Sized` declared on the trait.
32 SizedSelf(SmallVec<[Span; 1]>),
34 /// Supertrait reference references `Self` an in illegal location
35 /// (e.g., `trait Foo : Bar<Self>`).
36 SupertraitSelf(SmallVec<[Span; 1]>),
38 /// Method has something illegal.
39 Method(ast::Name, MethodViolationCode, Span),
42 AssocConst(ast::Name, Span),
45 impl ObjectSafetyViolation {
46 pub fn error_msg(&self) -> Cow<'static, str> {
48 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
49 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
50 if spans.iter().any(|sp| *sp != DUMMY_SP) {
51 "it uses `Self` as a type parameter in this".into()
53 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
57 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
58 format!("associated function `{}` has no `self` parameter", name).into()
60 ObjectSafetyViolation::Method(
62 MethodViolationCode::ReferencesSelfInput(_),
64 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
65 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
66 format!("method `{}` references the `Self` type in this parameter", name).into()
68 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
69 format!("method `{}` references the `Self` type in its return type", name).into()
71 ObjectSafetyViolation::Method(
73 MethodViolationCode::WhereClauseReferencesSelf,
76 format!("method `{}` references the `Self` type in its `where` clause", name).into()
78 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
79 format!("method `{}` has generic type parameters", name).into()
81 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
82 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
84 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
85 format!("it contains associated `const` `{}`", name).into()
87 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
91 pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
93 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
96 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
98 "consider turning `{}` into a method by giving it a `&self` argument or \
99 constraining it so it does not apply to trait objects",
102 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
104 ObjectSafetyViolation::Method(
106 MethodViolationCode::UndispatchableReceiver,
109 format!("consider changing method `{}`'s `self` parameter to be `&self`", name)
111 Some(("&Self".to_string(), span)),
113 ObjectSafetyViolation::AssocConst(name, _)
114 | ObjectSafetyViolation::Method(name, ..) => {
115 (format!("consider moving `{}` to another trait", name), None)
120 pub fn spans(&self) -> SmallVec<[Span; 1]> {
121 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
122 // diagnostics use a `note` instead of a `span_label`.
124 ObjectSafetyViolation::SupertraitSelf(spans)
125 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
126 ObjectSafetyViolation::AssocConst(_, span)
127 | ObjectSafetyViolation::Method(_, _, span)
128 if *span != DUMMY_SP =>
137 /// Reasons a method might not be object-safe.
138 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
139 pub enum MethodViolationCode {
141 StaticMethod(Option<(&'static str, Span)>),
143 /// e.g., `fn foo(&self, x: Self)`
144 ReferencesSelfInput(usize),
146 /// e.g., `fn foo(&self) -> Self`
147 ReferencesSelfOutput,
149 /// e.g., `fn foo(&self) where Self: Clone`
150 WhereClauseReferencesSelf,
152 /// e.g., `fn foo<A>()`
155 /// the method's receiver (`self` argument) can't be dispatched on
156 UndispatchableReceiver,
159 /// Returns the object safety violations that affect
160 /// astconv -- currently, `Self` in supertraits. This is needed
161 /// because `object_safety_violations` can't be used during
163 pub fn astconv_object_safety_violations(
166 ) -> Vec<ObjectSafetyViolation> {
167 debug_assert!(tcx.generics_of(trait_def_id).has_self);
168 let violations = traits::supertrait_def_ids(tcx, trait_def_id)
169 .map(|def_id| predicates_reference_self(tcx, def_id, true))
170 .filter(|spans| !spans.is_empty())
171 .map(|spans| ObjectSafetyViolation::SupertraitSelf(spans))
174 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
179 pub fn object_safety_violations(
182 ) -> Vec<ObjectSafetyViolation> {
183 debug_assert!(tcx.generics_of(trait_def_id).has_self);
184 debug!("object_safety_violations: {:?}", trait_def_id);
186 traits::supertrait_def_ids(tcx, trait_def_id)
187 .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id))
191 /// We say a method is *vtable safe* if it can be invoked on a trait
192 /// object. Note that object-safe traits can have some
193 /// non-vtable-safe methods, so long as they require `Self: Sized` or
194 /// otherwise ensure that they cannot be used when `Self = Trait`.
195 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
196 debug_assert!(tcx.generics_of(trait_def_id).has_self);
197 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
198 // Any method that has a `Self: Sized` bound cannot be called.
199 if generics_require_sized_self(tcx, method.def_id) {
203 match virtual_call_violation_for_method(tcx, trait_def_id, method) {
204 None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
209 fn object_safety_violations_for_trait(
212 ) -> Vec<ObjectSafetyViolation> {
213 // Check methods for violations.
214 let mut violations: Vec<_> = tcx
215 .associated_items(trait_def_id)
217 .filter(|item| item.kind == ty::AssocKind::Method)
219 object_safety_violation_for_method(tcx, trait_def_id, &item)
220 .map(|(code, span)| ObjectSafetyViolation::Method(item.ident.name, code, span))
222 .filter(|violation| {
223 if let ObjectSafetyViolation::Method(
225 MethodViolationCode::WhereClauseReferencesSelf,
229 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
230 // It's also hard to get a use site span, so we use the method definition span.
231 tcx.struct_span_lint_hir(
232 WHERE_CLAUSES_OBJECT_SAFETY,
236 let mut err = lint.build(&format!(
237 "the trait `{}` cannot be made into an object",
238 tcx.def_path_str(trait_def_id)
240 let node = tcx.hir().get_if_local(trait_def_id);
241 let msg = if let Some(hir::Node::Item(item)) = node {
244 "this trait cannot be made into an object...",
246 format!("...because {}", violation.error_msg())
249 "the trait cannot be made into an object because {}",
250 violation.error_msg()
253 err.span_label(*span, &msg);
254 match (node, violation.solution()) {
255 (Some(_), Some((note, None))) => {
258 (Some(_), Some((note, Some((sugg, span))))) => {
263 Applicability::MachineApplicable,
266 // Only provide the help if its a local trait, otherwise it's not actionable.
279 // Check the trait itself.
280 if trait_has_sized_self(tcx, trait_def_id) {
281 // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
282 let spans = get_sized_bounds(tcx, trait_def_id);
283 violations.push(ObjectSafetyViolation::SizedSelf(spans));
285 let spans = predicates_reference_self(tcx, trait_def_id, false);
286 if !spans.is_empty() {
287 violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
291 tcx.associated_items(trait_def_id)
293 .filter(|item| item.kind == ty::AssocKind::Const)
294 .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)),
298 "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
299 trait_def_id, violations
305 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
307 .get_if_local(trait_def_id)
308 .and_then(|node| match node {
309 hir::Node::Item(hir::Item {
310 kind: hir::ItemKind::Trait(.., generics, bounds, _),
319 hir::WherePredicate::BoundPredicate(pred)
320 if pred.bounded_ty.hir_id.owner_def_id() == trait_def_id =>
322 // Fetch spans for trait bounds that are Sized:
323 // `trait T where Self: Pred`
324 Some(pred.bounds.iter().filter_map(|b| match b {
325 hir::GenericBound::Trait(
327 hir::TraitBoundModifier::None,
328 ) if trait_has_sized_self(
330 trait_ref.trait_ref.trait_def_id(),
342 .chain(bounds.iter().filter_map(|b| match b {
343 hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
344 if trait_has_sized_self(tcx, trait_ref.trait_ref.trait_def_id()) =>
346 // Fetch spans for supertraits that are `Sized`: `trait T: Super`
351 .collect::<SmallVec<[Span; 1]>>(),
355 .unwrap_or_else(SmallVec::new)
358 fn predicates_reference_self(
361 supertraits_only: bool,
362 ) -> SmallVec<[Span; 1]> {
363 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
364 let predicates = if supertraits_only {
365 tcx.super_predicates_of(trait_def_id)
367 tcx.predicates_of(trait_def_id)
369 let self_ty = tcx.types.self_param;
370 let has_self_ty = |t: Ty<'_>| t.walk().any(|t| t == self_ty);
374 .map(|(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
375 .filter_map(|(predicate, &sp)| {
377 ty::Predicate::Trait(ref data, _) => {
378 // In the case of a trait predicate, we can skip the "self" type.
379 if data.skip_binder().input_types().skip(1).any(has_self_ty) {
385 ty::Predicate::Projection(ref data) => {
386 // And similarly for projections. This should be redundant with
387 // the previous check because any projection should have a
388 // matching `Trait` predicate with the same inputs, but we do
389 // the check to be safe.
391 // Note that we *do* allow projection *outputs* to contain
392 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
393 // we just require the user to specify *both* outputs
394 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
396 // This is ALT2 in issue #56288, see that for discussion of the
397 // possible alternatives.
411 ty::Predicate::WellFormed(..)
412 | ty::Predicate::ObjectSafe(..)
413 | ty::Predicate::TypeOutlives(..)
414 | ty::Predicate::RegionOutlives(..)
415 | ty::Predicate::ClosureKind(..)
416 | ty::Predicate::Subtype(..)
417 | ty::Predicate::ConstEvaluatable(..) => None,
423 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
424 generics_require_sized_self(tcx, trait_def_id)
427 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
428 let sized_def_id = match tcx.lang_items().sized_trait() {
429 Some(def_id) => def_id,
431 return false; /* No Sized trait, can't require it! */
435 // Search for a predicate like `Self : Sized` amongst the trait bounds.
436 let predicates = tcx.predicates_of(def_id);
437 let predicates = predicates.instantiate_identity(tcx).predicates;
438 elaborate_predicates(tcx, predicates).any(|predicate| match predicate {
439 ty::Predicate::Trait(ref trait_pred, _) => {
440 trait_pred.def_id() == sized_def_id && trait_pred.skip_binder().self_ty().is_param(0)
442 ty::Predicate::Projection(..)
443 | ty::Predicate::Subtype(..)
444 | ty::Predicate::RegionOutlives(..)
445 | ty::Predicate::WellFormed(..)
446 | ty::Predicate::ObjectSafe(..)
447 | ty::Predicate::ClosureKind(..)
448 | ty::Predicate::TypeOutlives(..)
449 | ty::Predicate::ConstEvaluatable(..) => false,
453 /// Returns `Some(_)` if this method makes the containing trait not object safe.
454 fn object_safety_violation_for_method(
457 method: &ty::AssocItem,
458 ) -> Option<(MethodViolationCode, Span)> {
459 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
460 // Any method that has a `Self : Sized` requisite is otherwise
461 // exempt from the regulations.
462 if generics_require_sized_self(tcx, method.def_id) {
466 let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
467 // Get an accurate span depending on the violation.
469 let node = tcx.hir().get_if_local(method.def_id);
470 let span = match (v, node) {
471 (MethodViolationCode::ReferencesSelfInput(arg), Some(node)) => node
473 .and_then(|decl| decl.inputs.get(arg + 1))
474 .map_or(method.ident.span, |arg| arg.span),
475 (MethodViolationCode::UndispatchableReceiver, Some(node)) => node
477 .and_then(|decl| decl.inputs.get(0))
478 .map_or(method.ident.span, |arg| arg.span),
479 (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
480 node.fn_decl().map_or(method.ident.span, |decl| decl.output.span())
482 _ => method.ident.span,
488 /// Returns `Some(_)` if this method cannot be called on a trait
489 /// object; this does not necessarily imply that the enclosing trait
490 /// is not object safe, because the method might have a where clause
492 fn virtual_call_violation_for_method<'tcx>(
495 method: &ty::AssocItem,
496 ) -> Option<MethodViolationCode> {
497 // The method's first parameter must be named `self`
498 if !method.method_has_self_argument {
499 // We'll attempt to provide a structured suggestion for `Self: Sized`.
501 tcx.hir().get_if_local(method.def_id).as_ref().and_then(|node| node.generics()).map(
502 |generics| match generics.where_clause.predicates {
503 [] => (" where Self: Sized", generics.where_clause.span),
504 [.., pred] => (", Self: Sized", pred.span().shrink_to_hi()),
507 return Some(MethodViolationCode::StaticMethod(sugg));
510 let sig = tcx.fn_sig(method.def_id);
512 for (i, input_ty) in sig.skip_binder().inputs()[1..].iter().enumerate() {
513 if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) {
514 return Some(MethodViolationCode::ReferencesSelfInput(i));
517 if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output().skip_binder()) {
518 return Some(MethodViolationCode::ReferencesSelfOutput);
521 // We can't monomorphize things like `fn foo<A>(...)`.
522 let own_counts = tcx.generics_of(method.def_id).own_counts();
523 if own_counts.types + own_counts.consts != 0 {
524 return Some(MethodViolationCode::Generic);
528 .predicates_of(method.def_id)
531 // A trait object can't claim to live more than the concrete type,
532 // so outlives predicates will always hold.
534 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
536 // Do a shallow visit so that `contains_illegal_self_type_reference`
537 // may apply it's custom visiting.
538 .visit_tys_shallow(|t| contains_illegal_self_type_reference(tcx, trait_def_id, t))
540 return Some(MethodViolationCode::WhereClauseReferencesSelf);
544 tcx.liberate_late_bound_regions(method.def_id, &sig.map_bound(|sig| sig.inputs()[0]));
546 // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
547 // However, this is already considered object-safe. We allow it as a special case here.
548 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
549 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
550 if receiver_ty != tcx.types.self_param {
551 if !receiver_is_dispatchable(tcx, method, receiver_ty) {
552 return Some(MethodViolationCode::UndispatchableReceiver);
554 // Do sanity check to make sure the receiver actually has the layout of a pointer.
556 use rustc::ty::layout::Abi;
558 let param_env = tcx.param_env(method.def_id);
560 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
561 match tcx.layout_of(param_env.and(ty)) {
562 Ok(layout) => &layout.abi,
563 Err(err) => bug!("error: {}\n while computing layout for type {:?}", err, ty),
568 let unit_receiver_ty =
569 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
571 match abi_of_ty(unit_receiver_ty) {
572 &Abi::Scalar(..) => (),
574 tcx.sess.delay_span_bug(
575 tcx.def_span(method.def_id),
577 "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
584 let trait_object_ty =
585 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
587 // e.g., `Rc<dyn Trait>`
588 let trait_object_receiver =
589 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
591 match abi_of_ty(trait_object_receiver) {
592 &Abi::ScalarPair(..) => (),
594 tcx.sess.delay_span_bug(
595 tcx.def_span(method.def_id),
597 "receiver when `Self = {}` should have a ScalarPair ABI; \
610 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
611 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
612 fn receiver_for_self_ty<'tcx>(
614 receiver_ty: Ty<'tcx>,
616 method_def_id: DefId,
618 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
619 let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
620 if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
623 let result = receiver_ty.subst(tcx, substs);
625 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
626 receiver_ty, self_ty, method_def_id, result
631 /// Creates the object type for the current trait. For example,
632 /// if the current trait is `Deref`, then this will be
633 /// `dyn Deref<Target = Self::Target> + 'static`.
634 fn object_ty_for_trait<'tcx>(
637 lifetime: ty::Region<'tcx>,
639 debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
641 let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
643 let trait_predicate =
644 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
646 let mut associated_types = traits::supertraits(tcx, ty::Binder::dummy(trait_ref))
647 .flat_map(|super_trait_ref| {
648 tcx.associated_items(super_trait_ref.def_id())
650 .map(move |item| (super_trait_ref, item))
652 .filter(|(_, item)| item.kind == ty::AssocKind::Type)
653 .collect::<Vec<_>>();
655 // existential predicates need to be in a specific order
656 associated_types.sort_by_cached_key(|(_, item)| tcx.def_path_hash(item.def_id));
658 let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
659 // We *can* get bound lifetimes here in cases like
660 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
662 // binder moved to (*)...
663 let super_trait_ref = super_trait_ref.skip_binder();
664 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
665 ty: tcx.mk_projection(item.def_id, super_trait_ref.substs),
666 item_def_id: item.def_id,
667 substs: super_trait_ref.substs,
671 let existential_predicates =
672 tcx.mk_existential_predicates(iter::once(trait_predicate).chain(projection_predicates));
674 let object_ty = tcx.mk_dynamic(
675 // (*) ... binder re-introduced here
676 ty::Binder::bind(existential_predicates),
680 debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
685 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
686 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
687 /// in the following way:
688 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
689 /// - require the following bound:
692 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
695 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
696 /// (substitution notation).
698 /// Some examples of receiver types and their required obligation:
699 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
700 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
701 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
703 /// The only case where the receiver is not dispatchable, but is still a valid receiver
704 /// type (just not object-safe), is when there is more than one level of pointer indirection.
705 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
706 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
707 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
708 /// contained by the trait object, because the object that needs to be coerced is behind
711 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
712 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
713 /// is stabilized, see tracking issue https://github.com/rust-lang/rust/issues/43561).
714 /// Instead, we fudge a little by introducing a new type parameter `U` such that
715 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
716 /// Written as a chalk-style query:
718 /// forall (U: Trait + ?Sized) {
719 /// if (Self: Unsize<U>) {
720 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
724 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
725 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
726 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
728 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
729 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
730 // `self: Wrapper<Self>`.
732 fn receiver_is_dispatchable<'tcx>(
734 method: &ty::AssocItem,
735 receiver_ty: Ty<'tcx>,
737 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
739 let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
740 let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
743 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
747 // the type `U` in the query
748 // use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
749 // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
750 // replace this with `dyn Trait`
751 let unsized_self_ty: Ty<'tcx> =
752 tcx.mk_ty_param(::std::u32::MAX, Symbol::intern("RustaceansAreAwesome"));
754 // `Receiver[Self => U]`
755 let unsized_receiver_ty =
756 receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
758 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
759 // `U: ?Sized` is already implied here
761 let mut param_env = tcx.param_env(method.def_id);
764 let unsize_predicate = ty::TraitRef {
766 substs: tcx.mk_substs_trait(tcx.types.self_param, &[unsized_self_ty.into()]),
771 // U: Trait<Arg1, ..., ArgN>
772 let trait_predicate = {
774 InternalSubsts::for_item(tcx, method.container.assert_trait(), |param, _| {
775 if param.index == 0 {
776 unsized_self_ty.into()
778 tcx.mk_param_from_def(param)
782 ty::TraitRef { def_id: unsize_did, substs }.without_const().to_predicate()
785 let caller_bounds: Vec<Predicate<'tcx>> = param_env
789 .chain(iter::once(unsize_predicate))
790 .chain(iter::once(trait_predicate))
793 param_env.caller_bounds = tcx.intern_predicates(&caller_bounds);
798 // Receiver: DispatchFromDyn<Receiver[Self => U]>
800 let predicate = ty::TraitRef {
801 def_id: dispatch_from_dyn_did,
802 substs: tcx.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
807 Obligation::new(ObligationCause::dummy(), param_env, predicate)
810 tcx.infer_ctxt().enter(|ref infcx| {
811 // the receiver is dispatchable iff the obligation holds
812 infcx.predicate_must_hold_modulo_regions(&obligation)
816 fn contains_illegal_self_type_reference<'tcx>(
821 // This is somewhat subtle. In general, we want to forbid
822 // references to `Self` in the argument and return types,
823 // since the value of `Self` is erased. However, there is one
824 // exception: it is ok to reference `Self` in order to access
825 // an associated type of the current trait, since we retain
826 // the value of those associated types in the object type
830 // trait SuperTrait {
834 // trait Trait : SuperTrait {
836 // fn foo(&self, x: Self) // bad
837 // fn foo(&self) -> Self // bad
838 // fn foo(&self) -> Option<Self> // bad
839 // fn foo(&self) -> Self::Y // OK, desugars to next example
840 // fn foo(&self) -> <Self as Trait>::Y // OK
841 // fn foo(&self) -> Self::X // OK, desugars to next example
842 // fn foo(&self) -> <Self as SuperTrait>::X // OK
846 // However, it is not as simple as allowing `Self` in a projected
847 // type, because there are illegal ways to use `Self` as well:
850 // trait Trait : SuperTrait {
852 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
856 // Here we will not have the type of `X` recorded in the
857 // object type, and we cannot resolve `Self as SomeOtherTrait`
858 // without knowing what `Self` is.
860 let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
861 let mut error = false;
862 let self_ty = tcx.types.self_param;
870 false // no contained types to walk
873 ty::Projection(ref data) => {
874 // This is a projected type `<Foo as SomeTrait>::X`.
876 // Compute supertraits of current trait lazily.
877 if supertraits.is_none() {
878 let trait_ref = ty::Binder::bind(ty::TraitRef::identity(tcx, trait_def_id));
879 supertraits = Some(traits::supertraits(tcx, trait_ref).collect());
882 // Determine whether the trait reference `Foo as
883 // SomeTrait` is in fact a supertrait of the
884 // current trait. In that case, this type is
885 // legal, because the type `X` will be specified
886 // in the object type. Note that we can just use
887 // direct equality here because all of these types
888 // are part of the formal parameter listing, and
889 // hence there should be no inference variables.
890 let projection_trait_ref = ty::Binder::bind(data.trait_ref(tcx));
891 let is_supertrait_of_current_trait =
892 supertraits.as_ref().unwrap().contains(&projection_trait_ref);
894 if is_supertrait_of_current_trait {
895 false // do not walk contained types, do not report error, do collect $200
897 true // DO walk contained types, POSSIBLY reporting an error
901 _ => true, // walk contained types, if any
908 pub(super) fn is_object_safe_provider(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
909 object_safety_violations(tcx, trait_def_id).is_empty()