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::query::evaluate_obligation::InferCtxtExt;
15 use crate::traits::{self, Obligation, ObligationCause};
16 use rustc_errors::{Applicability, FatalError};
18 use rustc_hir::def_id::DefId;
19 use rustc_middle::ty::subst::{GenericArg, InternalSubsts, Subst};
20 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor, WithConstness};
21 use rustc_middle::ty::{Predicate, ToPredicate};
22 use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
23 use rustc_span::symbol::Symbol;
25 use smallvec::SmallVec;
29 pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation};
31 /// Returns the object safety violations that affect
32 /// astconv -- currently, `Self` in supertraits. This is needed
33 /// because `object_safety_violations` can't be used during
35 pub fn astconv_object_safety_violations(
38 ) -> Vec<ObjectSafetyViolation> {
39 debug_assert!(tcx.generics_of(trait_def_id).has_self);
40 let violations = traits::supertrait_def_ids(tcx, trait_def_id)
41 .map(|def_id| predicates_reference_self(tcx, def_id, true))
42 .filter(|spans| !spans.is_empty())
43 .map(ObjectSafetyViolation::SupertraitSelf)
46 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
51 fn object_safety_violations(
54 ) -> &'tcx [ObjectSafetyViolation] {
55 debug_assert!(tcx.generics_of(trait_def_id).has_self);
56 debug!("object_safety_violations: {:?}", trait_def_id);
58 tcx.arena.alloc_from_iter(
59 traits::supertrait_def_ids(tcx, trait_def_id)
60 .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id)),
64 /// We say a method is *vtable safe* if it can be invoked on a trait
65 /// object. Note that object-safe traits can have some
66 /// non-vtable-safe methods, so long as they require `Self: Sized` or
67 /// otherwise ensure that they cannot be used when `Self = Trait`.
68 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
69 debug_assert!(tcx.generics_of(trait_def_id).has_self);
70 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
71 // Any method that has a `Self: Sized` bound cannot be called.
72 if generics_require_sized_self(tcx, method.def_id) {
76 match virtual_call_violation_for_method(tcx, trait_def_id, method) {
77 None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
82 fn object_safety_violations_for_trait(
85 ) -> Vec<ObjectSafetyViolation> {
86 // Check methods for violations.
87 let mut violations: Vec<_> = tcx
88 .associated_items(trait_def_id)
89 .in_definition_order()
90 .filter(|item| item.kind == ty::AssocKind::Fn)
92 object_safety_violation_for_method(tcx, trait_def_id, &item)
93 .map(|(code, span)| ObjectSafetyViolation::Method(item.ident.name, code, span))
96 if let ObjectSafetyViolation::Method(
98 MethodViolationCode::WhereClauseReferencesSelf,
102 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
103 // It's also hard to get a use site span, so we use the method definition span.
104 tcx.struct_span_lint_hir(
105 WHERE_CLAUSES_OBJECT_SAFETY,
109 let mut err = lint.build(&format!(
110 "the trait `{}` cannot be made into an object",
111 tcx.def_path_str(trait_def_id)
113 let node = tcx.hir().get_if_local(trait_def_id);
114 let msg = if let Some(hir::Node::Item(item)) = node {
117 "this trait cannot be made into an object...",
119 format!("...because {}", violation.error_msg())
122 "the trait cannot be made into an object because {}",
123 violation.error_msg()
126 err.span_label(*span, &msg);
127 match (node, violation.solution()) {
128 (Some(_), Some((note, None))) => {
131 (Some(_), Some((note, Some((sugg, span))))) => {
136 Applicability::MachineApplicable,
139 // Only provide the help if its a local trait, otherwise it's not actionable.
152 // Check the trait itself.
153 if trait_has_sized_self(tcx, trait_def_id) {
154 // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
155 let spans = get_sized_bounds(tcx, trait_def_id);
156 violations.push(ObjectSafetyViolation::SizedSelf(spans));
158 let spans = predicates_reference_self(tcx, trait_def_id, false);
159 if !spans.is_empty() {
160 violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
164 tcx.associated_items(trait_def_id)
165 .in_definition_order()
166 .filter(|item| item.kind == ty::AssocKind::Const)
167 .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)),
171 "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
172 trait_def_id, violations
178 fn sized_trait_bound_spans<'tcx>(
180 bounds: hir::GenericBounds<'tcx>,
181 ) -> impl 'tcx + Iterator<Item = Span> {
182 bounds.iter().filter_map(move |b| match b {
183 hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
184 if trait_has_sized_self(
186 trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
189 // Fetch spans for supertraits that are `Sized`: `trait T: Super`
196 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
198 .get_if_local(trait_def_id)
199 .and_then(|node| match node {
200 hir::Node::Item(hir::Item {
201 kind: hir::ItemKind::Trait(.., generics, bounds, _),
210 hir::WherePredicate::BoundPredicate(pred)
211 if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
213 // Fetch spans for trait bounds that are Sized:
214 // `trait T where Self: Pred`
215 Some(sized_trait_bound_spans(tcx, pred.bounds))
221 // Fetch spans for supertraits that are `Sized`: `trait T: Super`.
222 .chain(sized_trait_bound_spans(tcx, bounds))
223 .collect::<SmallVec<[Span; 1]>>(),
227 .unwrap_or_else(SmallVec::new)
230 fn predicates_reference_self(
233 supertraits_only: bool,
234 ) -> SmallVec<[Span; 1]> {
235 let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
236 let predicates = if supertraits_only {
237 tcx.super_predicates_of(trait_def_id)
239 tcx.predicates_of(trait_def_id)
241 let self_ty = tcx.types.self_param;
242 let has_self_ty = |arg: &GenericArg<'_>| arg.walk().any(|arg| arg == self_ty.into());
246 .map(|(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
247 .filter_map(|(predicate, &sp)| {
248 match predicate.kind() {
249 ty::PredicateKind::Trait(ref data, _) => {
250 // In the case of a trait predicate, we can skip the "self" type.
251 if data.skip_binder().trait_ref.substs[1..].iter().any(has_self_ty) {
257 ty::PredicateKind::Projection(ref data) => {
258 // And similarly for projections. This should be redundant with
259 // the previous check because any projection should have a
260 // matching `Trait` predicate with the same inputs, but we do
261 // the check to be safe.
263 // Note that we *do* allow projection *outputs* to contain
264 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
265 // we just require the user to specify *both* outputs
266 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
268 // This is ALT2 in issue #56288, see that for discussion of the
269 // possible alternatives.
270 if data.skip_binder().projection_ty.trait_ref(tcx).substs[1..]
279 ty::PredicateKind::WellFormed(..)
280 | ty::PredicateKind::ObjectSafe(..)
281 | ty::PredicateKind::TypeOutlives(..)
282 | ty::PredicateKind::RegionOutlives(..)
283 | ty::PredicateKind::ClosureKind(..)
284 | ty::PredicateKind::Subtype(..)
285 | ty::PredicateKind::ConstEvaluatable(..)
286 | ty::PredicateKind::ConstEquate(..) => None,
292 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
293 generics_require_sized_self(tcx, trait_def_id)
296 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
297 let sized_def_id = match tcx.lang_items().sized_trait() {
298 Some(def_id) => def_id,
300 return false; /* No Sized trait, can't require it! */
304 // Search for a predicate like `Self : Sized` amongst the trait bounds.
305 let predicates = tcx.predicates_of(def_id);
306 let predicates = predicates.instantiate_identity(tcx).predicates;
307 elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| {
308 match obligation.predicate.kind() {
309 ty::PredicateKind::Trait(ref trait_pred, _) => {
310 trait_pred.def_id() == sized_def_id
311 && trait_pred.skip_binder().self_ty().is_param(0)
313 ty::PredicateKind::Projection(..)
314 | ty::PredicateKind::Subtype(..)
315 | ty::PredicateKind::RegionOutlives(..)
316 | ty::PredicateKind::WellFormed(..)
317 | ty::PredicateKind::ObjectSafe(..)
318 | ty::PredicateKind::ClosureKind(..)
319 | ty::PredicateKind::TypeOutlives(..)
320 | ty::PredicateKind::ConstEvaluatable(..)
321 | ty::PredicateKind::ConstEquate(..) => false,
326 /// Returns `Some(_)` if this method makes the containing trait not object safe.
327 fn object_safety_violation_for_method(
330 method: &ty::AssocItem,
331 ) -> Option<(MethodViolationCode, Span)> {
332 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
333 // Any method that has a `Self : Sized` requisite is otherwise
334 // exempt from the regulations.
335 if generics_require_sized_self(tcx, method.def_id) {
339 let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
340 // Get an accurate span depending on the violation.
342 let node = tcx.hir().get_if_local(method.def_id);
343 let span = match (v, node) {
344 (MethodViolationCode::ReferencesSelfInput(arg), Some(node)) => node
346 .and_then(|decl| decl.inputs.get(arg + 1))
347 .map_or(method.ident.span, |arg| arg.span),
348 (MethodViolationCode::UndispatchableReceiver, Some(node)) => node
350 .and_then(|decl| decl.inputs.get(0))
351 .map_or(method.ident.span, |arg| arg.span),
352 (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
353 node.fn_decl().map_or(method.ident.span, |decl| decl.output.span())
355 _ => method.ident.span,
361 /// Returns `Some(_)` if this method cannot be called on a trait
362 /// object; this does not necessarily imply that the enclosing trait
363 /// is not object safe, because the method might have a where clause
365 fn virtual_call_violation_for_method<'tcx>(
368 method: &ty::AssocItem,
369 ) -> Option<MethodViolationCode> {
370 // The method's first parameter must be named `self`
371 if !method.fn_has_self_parameter {
372 // We'll attempt to provide a structured suggestion for `Self: Sized`.
374 tcx.hir().get_if_local(method.def_id).as_ref().and_then(|node| node.generics()).map(
375 |generics| match generics.where_clause.predicates {
376 [] => (" where Self: Sized", generics.where_clause.span),
377 [.., pred] => (", Self: Sized", pred.span().shrink_to_hi()),
380 return Some(MethodViolationCode::StaticMethod(sugg));
383 let sig = tcx.fn_sig(method.def_id);
385 for (i, input_ty) in sig.skip_binder().inputs()[1..].iter().enumerate() {
386 if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) {
387 return Some(MethodViolationCode::ReferencesSelfInput(i));
390 if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output().skip_binder()) {
391 return Some(MethodViolationCode::ReferencesSelfOutput);
394 // We can't monomorphize things like `fn foo<A>(...)`.
395 let own_counts = tcx.generics_of(method.def_id).own_counts();
396 if own_counts.types + own_counts.consts != 0 {
397 return Some(MethodViolationCode::Generic);
401 .predicates_of(method.def_id)
404 // A trait object can't claim to live more than the concrete type,
405 // so outlives predicates will always hold.
407 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
409 // Do a shallow visit so that `contains_illegal_self_type_reference`
410 // may apply it's custom visiting.
411 .visit_tys_shallow(|t| contains_illegal_self_type_reference(tcx, trait_def_id, t))
413 return Some(MethodViolationCode::WhereClauseReferencesSelf);
417 tcx.liberate_late_bound_regions(method.def_id, &sig.map_bound(|sig| sig.inputs()[0]));
419 // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
420 // However, this is already considered object-safe. We allow it as a special case here.
421 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
422 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
423 if receiver_ty != tcx.types.self_param {
424 if !receiver_is_dispatchable(tcx, method, receiver_ty) {
425 return Some(MethodViolationCode::UndispatchableReceiver);
427 // Do sanity check to make sure the receiver actually has the layout of a pointer.
429 use rustc_target::abi::Abi;
431 let param_env = tcx.param_env(method.def_id);
433 let abi_of_ty = |ty: Ty<'tcx>| -> &Abi {
434 match tcx.layout_of(param_env.and(ty)) {
435 Ok(layout) => &layout.abi,
436 Err(err) => bug!("error: {}\n while computing layout for type {:?}", err, ty),
441 let unit_receiver_ty =
442 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
444 match abi_of_ty(unit_receiver_ty) {
445 &Abi::Scalar(..) => (),
447 tcx.sess.delay_span_bug(
448 tcx.def_span(method.def_id),
450 "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
457 let trait_object_ty =
458 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
460 // e.g., `Rc<dyn Trait>`
461 let trait_object_receiver =
462 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
464 match abi_of_ty(trait_object_receiver) {
465 &Abi::ScalarPair(..) => (),
467 tcx.sess.delay_span_bug(
468 tcx.def_span(method.def_id),
470 "receiver when `Self = {}` should have a ScalarPair ABI; \
483 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
484 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
485 fn receiver_for_self_ty<'tcx>(
487 receiver_ty: Ty<'tcx>,
489 method_def_id: DefId,
491 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
492 let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
493 if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
496 let result = receiver_ty.subst(tcx, substs);
498 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
499 receiver_ty, self_ty, method_def_id, result
504 /// Creates the object type for the current trait. For example,
505 /// if the current trait is `Deref`, then this will be
506 /// `dyn Deref<Target = Self::Target> + 'static`.
507 fn object_ty_for_trait<'tcx>(
510 lifetime: ty::Region<'tcx>,
512 debug!("object_ty_for_trait: trait_def_id={:?}", trait_def_id);
514 let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
516 let trait_predicate =
517 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
519 let mut associated_types = traits::supertraits(tcx, ty::Binder::dummy(trait_ref))
520 .flat_map(|super_trait_ref| {
521 tcx.associated_items(super_trait_ref.def_id())
522 .in_definition_order()
523 .map(move |item| (super_trait_ref, item))
525 .filter(|(_, item)| item.kind == ty::AssocKind::Type)
526 .collect::<Vec<_>>();
528 // existential predicates need to be in a specific order
529 associated_types.sort_by_cached_key(|(_, item)| tcx.def_path_hash(item.def_id));
531 let projection_predicates = associated_types.into_iter().map(|(super_trait_ref, item)| {
532 // We *can* get bound lifetimes here in cases like
533 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
535 // binder moved to (*)...
536 let super_trait_ref = super_trait_ref.skip_binder();
537 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
538 ty: tcx.mk_projection(item.def_id, super_trait_ref.substs),
539 item_def_id: item.def_id,
540 substs: super_trait_ref.substs,
544 let existential_predicates =
545 tcx.mk_existential_predicates(iter::once(trait_predicate).chain(projection_predicates));
547 let object_ty = tcx.mk_dynamic(
548 // (*) ... binder re-introduced here
549 ty::Binder::bind(existential_predicates),
553 debug!("object_ty_for_trait: object_ty=`{}`", object_ty);
558 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
559 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
560 /// in the following way:
561 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
562 /// - require the following bound:
565 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
568 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
569 /// (substitution notation).
571 /// Some examples of receiver types and their required obligation:
572 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
573 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
574 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
576 /// The only case where the receiver is not dispatchable, but is still a valid receiver
577 /// type (just not object-safe), is when there is more than one level of pointer indirection.
578 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
579 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
580 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
581 /// contained by the trait object, because the object that needs to be coerced is behind
584 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
585 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
586 /// is stabilized, see tracking issue https://github.com/rust-lang/rust/issues/43561).
587 /// Instead, we fudge a little by introducing a new type parameter `U` such that
588 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
589 /// Written as a chalk-style query:
591 /// forall (U: Trait + ?Sized) {
592 /// if (Self: Unsize<U>) {
593 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
597 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
598 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
599 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
601 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
602 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
603 // `self: Wrapper<Self>`.
605 fn receiver_is_dispatchable<'tcx>(
607 method: &ty::AssocItem,
608 receiver_ty: Ty<'tcx>,
610 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
612 let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
613 let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
616 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
620 // the type `U` in the query
621 // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
622 // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
623 // replace this with `dyn Trait`
624 let unsized_self_ty: Ty<'tcx> =
625 tcx.mk_ty_param(u32::MAX, Symbol::intern("RustaceansAreAwesome"));
627 // `Receiver[Self => U]`
628 let unsized_receiver_ty =
629 receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
631 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
632 // `U: ?Sized` is already implied here
634 let mut param_env = tcx.param_env(method.def_id);
637 let unsize_predicate = ty::TraitRef {
639 substs: tcx.mk_substs_trait(tcx.types.self_param, &[unsized_self_ty.into()]),
644 // U: Trait<Arg1, ..., ArgN>
645 let trait_predicate = {
647 InternalSubsts::for_item(tcx, method.container.assert_trait(), |param, _| {
648 if param.index == 0 {
649 unsized_self_ty.into()
651 tcx.mk_param_from_def(param)
655 ty::TraitRef { def_id: unsize_did, substs }.without_const().to_predicate(tcx)
658 let caller_bounds: Vec<Predicate<'tcx>> = param_env
661 .chain(iter::once(unsize_predicate))
662 .chain(iter::once(trait_predicate))
665 param_env.caller_bounds = tcx.intern_predicates(&caller_bounds);
670 // Receiver: DispatchFromDyn<Receiver[Self => U]>
672 let predicate = ty::TraitRef {
673 def_id: dispatch_from_dyn_did,
674 substs: tcx.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
679 Obligation::new(ObligationCause::dummy(), param_env, predicate)
682 tcx.infer_ctxt().enter(|ref infcx| {
683 // the receiver is dispatchable iff the obligation holds
684 infcx.predicate_must_hold_modulo_regions(&obligation)
688 fn contains_illegal_self_type_reference<'tcx>(
693 // This is somewhat subtle. In general, we want to forbid
694 // references to `Self` in the argument and return types,
695 // since the value of `Self` is erased. However, there is one
696 // exception: it is ok to reference `Self` in order to access
697 // an associated type of the current trait, since we retain
698 // the value of those associated types in the object type
702 // trait SuperTrait {
706 // trait Trait : SuperTrait {
708 // fn foo(&self, x: Self) // bad
709 // fn foo(&self) -> Self // bad
710 // fn foo(&self) -> Option<Self> // bad
711 // fn foo(&self) -> Self::Y // OK, desugars to next example
712 // fn foo(&self) -> <Self as Trait>::Y // OK
713 // fn foo(&self) -> Self::X // OK, desugars to next example
714 // fn foo(&self) -> <Self as SuperTrait>::X // OK
718 // However, it is not as simple as allowing `Self` in a projected
719 // type, because there are illegal ways to use `Self` as well:
722 // trait Trait : SuperTrait {
724 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
728 // Here we will not have the type of `X` recorded in the
729 // object type, and we cannot resolve `Self as SomeOtherTrait`
730 // without knowing what `Self` is.
732 struct IllegalSelfTypeVisitor<'tcx> {
736 supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>>,
739 impl<'tcx> TypeVisitor<'tcx> for IllegalSelfTypeVisitor<'tcx> {
740 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
742 ty::Param(_) => t == self.self_ty,
743 ty::Projection(ref data) => {
744 // This is a projected type `<Foo as SomeTrait>::X`.
746 // Compute supertraits of current trait lazily.
747 if self.supertraits.is_none() {
749 ty::Binder::bind(ty::TraitRef::identity(self.tcx, self.trait_def_id));
750 self.supertraits = Some(traits::supertraits(self.tcx, trait_ref).collect());
753 // Determine whether the trait reference `Foo as
754 // SomeTrait` is in fact a supertrait of the
755 // current trait. In that case, this type is
756 // legal, because the type `X` will be specified
757 // in the object type. Note that we can just use
758 // direct equality here because all of these types
759 // are part of the formal parameter listing, and
760 // hence there should be no inference variables.
761 let projection_trait_ref = ty::Binder::bind(data.trait_ref(self.tcx));
762 let is_supertrait_of_current_trait =
763 self.supertraits.as_ref().unwrap().contains(&projection_trait_ref);
765 if is_supertrait_of_current_trait {
766 false // do not walk contained types, do not report error, do collect $200
768 t.super_visit_with(self) // DO walk contained types, POSSIBLY reporting an error
771 _ => t.super_visit_with(self), // walk contained types, if any
775 fn visit_const(&mut self, _c: &ty::Const<'tcx>) -> bool {
776 // FIXME(#72219) Look into the unevaluated constants for object safety violations.
777 // Do not walk substitutions of unevaluated consts, as they contain `Self`, even
778 // though the const expression doesn't necessary use it. Currently type variables
779 // inside array length expressions are forbidden, so they can't break the above
785 ty.visit_with(&mut IllegalSelfTypeVisitor {
787 self_ty: tcx.types.self_param,
793 pub fn provide(providers: &mut ty::query::Providers) {
794 *providers = ty::query::Providers { object_safety_violations, ..*providers };