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, elaborate_trait_ref};
13 use crate::infer::TyCtxtInferExt;
14 use crate::traits::query::evaluate_obligation::InferCtxtExt;
15 use crate::traits::{self, Obligation, ObligationCause};
16 use hir::def::DefKind;
17 use rustc_errors::{DelayDm, FatalError, MultiSpan};
19 use rustc_hir::def_id::DefId;
20 use rustc_middle::ty::abstract_const::{walk_abstract_const, AbstractConst};
21 use rustc_middle::ty::{
22 self, EarlyBinder, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor,
24 use rustc_middle::ty::{GenericArg, InternalSubsts};
25 use rustc_middle::ty::{Predicate, ToPredicate};
26 use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
27 use rustc_span::symbol::Symbol;
29 use smallvec::SmallVec;
32 use std::ops::ControlFlow;
34 pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation};
36 /// Returns the object safety violations that affect
37 /// astconv -- currently, `Self` in supertraits. This is needed
38 /// because `object_safety_violations` can't be used during
40 pub fn astconv_object_safety_violations(
43 ) -> Vec<ObjectSafetyViolation> {
44 debug_assert!(tcx.generics_of(trait_def_id).has_self);
45 let violations = traits::supertrait_def_ids(tcx, trait_def_id)
46 .map(|def_id| predicates_reference_self(tcx, def_id, true))
47 .filter(|spans| !spans.is_empty())
48 .map(ObjectSafetyViolation::SupertraitSelf)
51 debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
56 fn object_safety_violations(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &'_ [ObjectSafetyViolation] {
57 debug_assert!(tcx.generics_of(trait_def_id).has_self);
58 debug!("object_safety_violations: {:?}", trait_def_id);
60 tcx.arena.alloc_from_iter(
61 traits::supertrait_def_ids(tcx, trait_def_id)
62 .flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id)),
66 /// We say a method is *vtable safe* if it can be invoked on a trait
67 /// object. Note that object-safe traits can have some
68 /// non-vtable-safe methods, so long as they require `Self: Sized` or
69 /// otherwise ensure that they cannot be used when `Self = Trait`.
70 pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
71 debug_assert!(tcx.generics_of(trait_def_id).has_self);
72 debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
73 // Any method that has a `Self: Sized` bound cannot be called.
74 if generics_require_sized_self(tcx, method.def_id) {
78 match virtual_call_violation_for_method(tcx, trait_def_id, method) {
79 None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
84 fn object_safety_violations_for_trait(
87 ) -> Vec<ObjectSafetyViolation> {
88 // Check methods for violations.
89 let mut violations: Vec<_> = tcx
90 .associated_items(trait_def_id)
91 .in_definition_order()
92 .filter(|item| item.kind == ty::AssocKind::Fn)
94 object_safety_violation_for_method(tcx, trait_def_id, &item)
95 .map(|(code, span)| ObjectSafetyViolation::Method(item.name, code, span))
98 if let ObjectSafetyViolation::Method(
100 MethodViolationCode::WhereClauseReferencesSelf,
104 lint_object_unsafe_trait(tcx, *span, trait_def_id, &violation);
112 // Check the trait itself.
113 if trait_has_sized_self(tcx, trait_def_id) {
114 // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
115 let spans = get_sized_bounds(tcx, trait_def_id);
116 violations.push(ObjectSafetyViolation::SizedSelf(spans));
118 let spans = predicates_reference_self(tcx, trait_def_id, false);
119 if !spans.is_empty() {
120 violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
122 let spans = bounds_reference_self(tcx, trait_def_id);
123 if !spans.is_empty() {
124 violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
128 tcx.associated_items(trait_def_id)
129 .in_definition_order()
130 .filter(|item| item.kind == ty::AssocKind::Const)
132 let ident = item.ident(tcx);
133 ObjectSafetyViolation::AssocConst(ident.name, ident.span)
137 if !tcx.features().generic_associated_types_extended {
139 tcx.associated_items(trait_def_id)
140 .in_definition_order()
141 .filter(|item| item.kind == ty::AssocKind::Type)
142 .filter(|item| !tcx.generics_of(item.def_id).params.is_empty())
144 let ident = item.ident(tcx);
145 ObjectSafetyViolation::GAT(ident.name, ident.span)
151 "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
152 trait_def_id, violations
158 /// Lint object-unsafe trait.
159 fn lint_object_unsafe_trait(
163 violation: &ObjectSafetyViolation,
165 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
166 // It's also hard to get a use site span, so we use the method definition span.
167 tcx.struct_span_lint_hir(
168 WHERE_CLAUSES_OBJECT_SAFETY,
171 DelayDm(|| format!("the trait `{}` cannot be made into an object", tcx.def_path_str(trait_def_id))),
173 let node = tcx.hir().get_if_local(trait_def_id);
174 let mut spans = MultiSpan::from_span(span);
175 if let Some(hir::Node::Item(item)) = node {
176 spans.push_span_label(
178 "this trait cannot be made into an object...",
180 spans.push_span_label(span, format!("...because {}", violation.error_msg()));
182 spans.push_span_label(
185 "the trait cannot be made into an object because {}",
186 violation.error_msg()
192 "for a trait to be \"object safe\" it needs to allow building a vtable to allow the \
193 call to be resolvable dynamically; for more information visit \
194 <https://doc.rust-lang.org/reference/items/traits.html#object-safety>",
197 // Only provide the help if its a local trait, otherwise it's not
198 violation.solution(err);
205 fn sized_trait_bound_spans<'tcx>(
207 bounds: hir::GenericBounds<'tcx>,
208 ) -> impl 'tcx + Iterator<Item = Span> {
209 bounds.iter().filter_map(move |b| match b {
210 hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
211 if trait_has_sized_self(
213 trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
216 // Fetch spans for supertraits that are `Sized`: `trait T: Super`
223 fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
225 .get_if_local(trait_def_id)
226 .and_then(|node| match node {
227 hir::Node::Item(hir::Item {
228 kind: hir::ItemKind::Trait(.., generics, bounds, _),
236 hir::WherePredicate::BoundPredicate(pred)
237 if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
239 // Fetch spans for trait bounds that are Sized:
240 // `trait T where Self: Pred`
241 Some(sized_trait_bound_spans(tcx, pred.bounds))
247 // Fetch spans for supertraits that are `Sized`: `trait T: Super`.
248 .chain(sized_trait_bound_spans(tcx, bounds))
249 .collect::<SmallVec<[Span; 1]>>(),
253 .unwrap_or_else(SmallVec::new)
256 fn predicates_reference_self(
259 supertraits_only: bool,
260 ) -> SmallVec<[Span; 1]> {
261 let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
262 let predicates = if supertraits_only {
263 tcx.super_predicates_of(trait_def_id)
265 tcx.predicates_of(trait_def_id)
270 .map(|&(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
271 .filter_map(|predicate| predicate_references_self(tcx, predicate))
275 fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
276 tcx.associated_items(trait_def_id)
277 .in_definition_order()
278 .filter(|item| item.kind == ty::AssocKind::Type)
279 .flat_map(|item| tcx.explicit_item_bounds(item.def_id))
280 .filter_map(|pred_span| predicate_references_self(tcx, *pred_span))
284 fn predicate_references_self<'tcx>(
286 (predicate, sp): (ty::Predicate<'tcx>, Span),
288 let self_ty = tcx.types.self_param;
289 let has_self_ty = |arg: &GenericArg<'tcx>| arg.walk().any(|arg| arg == self_ty.into());
290 match predicate.kind().skip_binder() {
291 ty::PredicateKind::Trait(ref data) => {
292 // In the case of a trait predicate, we can skip the "self" type.
293 if data.trait_ref.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
295 ty::PredicateKind::Projection(ref data) => {
296 // And similarly for projections. This should be redundant with
297 // the previous check because any projection should have a
298 // matching `Trait` predicate with the same inputs, but we do
299 // the check to be safe.
301 // It's also won't be redundant if we allow type-generic associated
302 // types for trait objects.
304 // Note that we *do* allow projection *outputs* to contain
305 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
306 // we just require the user to specify *both* outputs
307 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
309 // This is ALT2 in issue #56288, see that for discussion of the
310 // possible alternatives.
311 if data.projection_ty.substs[1..].iter().any(has_self_ty) { Some(sp) } else { None }
313 ty::PredicateKind::WellFormed(..)
314 | ty::PredicateKind::ObjectSafe(..)
315 | ty::PredicateKind::TypeOutlives(..)
316 | ty::PredicateKind::RegionOutlives(..)
317 | ty::PredicateKind::ClosureKind(..)
318 | ty::PredicateKind::Subtype(..)
319 | ty::PredicateKind::Coerce(..)
320 | ty::PredicateKind::ConstEvaluatable(..)
321 | ty::PredicateKind::ConstEquate(..)
322 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
326 fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
327 generics_require_sized_self(tcx, trait_def_id)
330 fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
331 let Some(sized_def_id) = tcx.lang_items().sized_trait() else {
332 return false; /* No Sized trait, can't require it! */
335 // Search for a predicate like `Self : Sized` amongst the trait bounds.
336 let predicates = tcx.predicates_of(def_id);
337 let predicates = predicates.instantiate_identity(tcx).predicates;
338 elaborate_predicates(tcx, predicates.into_iter()).any(|obligation| {
339 match obligation.predicate.kind().skip_binder() {
340 ty::PredicateKind::Trait(ref trait_pred) => {
341 trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
343 ty::PredicateKind::Projection(..)
344 | ty::PredicateKind::Subtype(..)
345 | ty::PredicateKind::Coerce(..)
346 | ty::PredicateKind::RegionOutlives(..)
347 | ty::PredicateKind::WellFormed(..)
348 | ty::PredicateKind::ObjectSafe(..)
349 | ty::PredicateKind::ClosureKind(..)
350 | ty::PredicateKind::TypeOutlives(..)
351 | ty::PredicateKind::ConstEvaluatable(..)
352 | ty::PredicateKind::ConstEquate(..)
353 | ty::PredicateKind::TypeWellFormedFromEnv(..) => false,
358 /// Returns `Some(_)` if this method makes the containing trait not object safe.
359 fn object_safety_violation_for_method(
362 method: &ty::AssocItem,
363 ) -> Option<(MethodViolationCode, Span)> {
364 debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
365 // Any method that has a `Self : Sized` requisite is otherwise
366 // exempt from the regulations.
367 if generics_require_sized_self(tcx, method.def_id) {
371 let violation = virtual_call_violation_for_method(tcx, trait_def_id, method);
372 // Get an accurate span depending on the violation.
374 let node = tcx.hir().get_if_local(method.def_id);
375 let span = match (&v, node) {
376 (MethodViolationCode::ReferencesSelfInput(Some(span)), _) => *span,
377 (MethodViolationCode::UndispatchableReceiver(Some(span)), _) => *span,
378 (MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
379 node.fn_decl().map_or(method.ident(tcx).span, |decl| decl.output.span())
381 _ => method.ident(tcx).span,
387 /// Returns `Some(_)` if this method cannot be called on a trait
388 /// object; this does not necessarily imply that the enclosing trait
389 /// is not object safe, because the method might have a where clause
391 fn virtual_call_violation_for_method<'tcx>(
394 method: &ty::AssocItem,
395 ) -> Option<MethodViolationCode> {
396 let sig = tcx.fn_sig(method.def_id);
398 // The method's first parameter must be named `self`
399 if !method.fn_has_self_parameter {
400 let sugg = if let Some(hir::Node::TraitItem(hir::TraitItem {
402 kind: hir::TraitItemKind::Fn(sig, _),
404 })) = tcx.hir().get_if_local(method.def_id).as_ref()
406 let sm = tcx.sess.source_map();
409 format!("&self{}", if sig.decl.inputs.is_empty() { "" } else { ", " }),
410 sm.span_through_char(sig.span, '(').shrink_to_hi(),
413 format!("{} Self: Sized", generics.add_where_or_trailing_comma()),
414 generics.tail_span_for_predicate_suggestion(),
420 return Some(MethodViolationCode::StaticMethod(sugg));
423 for (i, &input_ty) in sig.skip_binder().inputs().iter().enumerate().skip(1) {
424 if contains_illegal_self_type_reference(tcx, trait_def_id, sig.rebind(input_ty)) {
425 let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
426 kind: hir::TraitItemKind::Fn(sig, _),
428 })) = tcx.hir().get_if_local(method.def_id).as_ref()
430 Some(sig.decl.inputs[i].span)
434 return Some(MethodViolationCode::ReferencesSelfInput(span));
437 if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output()) {
438 return Some(MethodViolationCode::ReferencesSelfOutput);
440 if contains_illegal_impl_trait_in_trait(tcx, sig.output()) {
441 return Some(MethodViolationCode::ReferencesImplTraitInTrait);
444 // We can't monomorphize things like `fn foo<A>(...)`.
445 let own_counts = tcx.generics_of(method.def_id).own_counts();
446 if own_counts.types + own_counts.consts != 0 {
447 return Some(MethodViolationCode::Generic);
450 let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
452 // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
453 // However, this is already considered object-safe. We allow it as a special case here.
454 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
455 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
456 if receiver_ty != tcx.types.self_param {
457 if !receiver_is_dispatchable(tcx, method, receiver_ty) {
458 let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
459 kind: hir::TraitItemKind::Fn(sig, _),
461 })) = tcx.hir().get_if_local(method.def_id).as_ref()
463 Some(sig.decl.inputs[0].span)
467 return Some(MethodViolationCode::UndispatchableReceiver(span));
469 // Do sanity check to make sure the receiver actually has the layout of a pointer.
471 use rustc_target::abi::Abi;
473 let param_env = tcx.param_env(method.def_id);
475 let abi_of_ty = |ty: Ty<'tcx>| -> Option<Abi> {
476 match tcx.layout_of(param_env.and(ty)) {
477 Ok(layout) => Some(layout.abi),
480 tcx.sess.delay_span_bug(
481 tcx.def_span(method.def_id),
482 &format!("error: {}\n while computing layout for type {:?}", err, ty),
490 let unit_receiver_ty =
491 receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
493 match abi_of_ty(unit_receiver_ty) {
494 Some(Abi::Scalar(..)) => (),
496 tcx.sess.delay_span_bug(
497 tcx.def_span(method.def_id),
499 "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
506 let trait_object_ty =
507 object_ty_for_trait(tcx, trait_def_id, tcx.mk_region(ty::ReStatic));
509 // e.g., `Rc<dyn Trait>`
510 let trait_object_receiver =
511 receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
513 match abi_of_ty(trait_object_receiver) {
514 Some(Abi::ScalarPair(..)) => (),
516 tcx.sess.delay_span_bug(
517 tcx.def_span(method.def_id),
519 "receiver when `Self = {}` should have a ScalarPair ABI; found {:?}",
528 // NOTE: This check happens last, because it results in a lint, and not a
531 .predicates_of(method.def_id)
534 // A trait object can't claim to live more than the concrete type,
535 // so outlives predicates will always hold.
537 .filter(|(p, _)| p.to_opt_type_outlives().is_none())
538 .any(|pred| contains_illegal_self_type_reference(tcx, trait_def_id, pred))
540 return Some(MethodViolationCode::WhereClauseReferencesSelf);
546 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
547 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
548 fn receiver_for_self_ty<'tcx>(
550 receiver_ty: Ty<'tcx>,
552 method_def_id: DefId,
554 debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
555 let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
556 if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
559 let result = EarlyBinder(receiver_ty).subst(tcx, substs);
561 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
562 receiver_ty, self_ty, method_def_id, result
567 /// Creates the object type for the current trait. For example,
568 /// if the current trait is `Deref`, then this will be
569 /// `dyn Deref<Target = Self::Target> + 'static`.
570 #[instrument(level = "trace", skip(tcx), ret)]
571 fn object_ty_for_trait<'tcx>(
574 lifetime: ty::Region<'tcx>,
576 let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
579 let trait_predicate = trait_ref.map_bound(|trait_ref| {
580 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref))
582 debug!(?trait_predicate);
584 let mut elaborated_predicates: Vec<_> = elaborate_trait_ref(tcx, trait_ref)
585 .filter_map(|obligation| {
587 let pred = obligation.predicate.to_opt_poly_projection_pred()?;
588 Some(pred.map_bound(|p| {
589 ty::ExistentialPredicate::Projection(ty::ExistentialProjection {
590 item_def_id: p.projection_ty.item_def_id,
591 substs: p.projection_ty.substs,
597 // NOTE: Since #37965, the existential predicates list has depended on the
598 // list of predicates to be sorted. This is mostly to enforce that the primary
599 // predicate comes first.
600 elaborated_predicates.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
601 elaborated_predicates.dedup();
603 let existential_predicates = tcx
604 .mk_poly_existential_predicates(iter::once(trait_predicate).chain(elaborated_predicates));
605 debug!(?existential_predicates);
607 tcx.mk_dynamic(existential_predicates, lifetime, ty::Dyn)
610 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
611 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
612 /// in the following way:
613 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
614 /// - require the following bound:
616 /// ```ignore (not-rust)
617 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
620 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
621 /// (substitution notation).
623 /// Some examples of receiver types and their required obligation:
624 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
625 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
626 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
628 /// The only case where the receiver is not dispatchable, but is still a valid receiver
629 /// type (just not object-safe), is when there is more than one level of pointer indirection.
630 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
631 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
632 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
633 /// contained by the trait object, because the object that needs to be coerced is behind
636 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
637 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
638 /// is stabilized, see tracking issue <https://github.com/rust-lang/rust/issues/43561>).
639 /// Instead, we fudge a little by introducing a new type parameter `U` such that
640 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
641 /// Written as a chalk-style query:
642 /// ```ignore (not-rust)
643 /// forall (U: Trait + ?Sized) {
644 /// if (Self: Unsize<U>) {
645 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
649 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
650 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
651 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
653 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
654 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
655 // `self: Wrapper<Self>`.
657 fn receiver_is_dispatchable<'tcx>(
659 method: &ty::AssocItem,
660 receiver_ty: Ty<'tcx>,
662 debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
664 let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
665 let (Some(unsize_did), Some(dispatch_from_dyn_did)) = traits else {
666 debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
670 // the type `U` in the query
671 // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
672 // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
673 // replace this with `dyn Trait`
674 let unsized_self_ty: Ty<'tcx> =
675 tcx.mk_ty_param(u32::MAX, Symbol::intern("RustaceansAreAwesome"));
677 // `Receiver[Self => U]`
678 let unsized_receiver_ty =
679 receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
681 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
682 // `U: ?Sized` is already implied here
684 let param_env = tcx.param_env(method.def_id);
687 let unsize_predicate = ty::Binder::dummy(ty::TraitRef {
689 substs: tcx.mk_substs_trait(tcx.types.self_param, &[unsized_self_ty.into()]),
694 // U: Trait<Arg1, ..., ArgN>
695 let trait_predicate = {
697 InternalSubsts::for_item(tcx, method.trait_container(tcx).unwrap(), |param, _| {
698 if param.index == 0 {
699 unsized_self_ty.into()
701 tcx.mk_param_from_def(param)
705 ty::Binder::dummy(ty::TraitRef { def_id: unsize_did, substs })
710 let caller_bounds: Vec<Predicate<'tcx>> =
711 param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]).collect();
714 tcx.intern_predicates(&caller_bounds),
716 param_env.constness(),
720 // Receiver: DispatchFromDyn<Receiver[Self => U]>
722 let predicate = ty::Binder::dummy(ty::TraitRef {
723 def_id: dispatch_from_dyn_did,
724 substs: tcx.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
728 Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate)
731 let infcx = tcx.infer_ctxt().build();
732 // the receiver is dispatchable iff the obligation holds
733 infcx.predicate_must_hold_modulo_regions(&obligation)
736 fn contains_illegal_self_type_reference<'tcx, T: TypeVisitable<'tcx>>(
741 // This is somewhat subtle. In general, we want to forbid
742 // references to `Self` in the argument and return types,
743 // since the value of `Self` is erased. However, there is one
744 // exception: it is ok to reference `Self` in order to access
745 // an associated type of the current trait, since we retain
746 // the value of those associated types in the object type
750 // trait SuperTrait {
754 // trait Trait : SuperTrait {
756 // fn foo(&self, x: Self) // bad
757 // fn foo(&self) -> Self // bad
758 // fn foo(&self) -> Option<Self> // bad
759 // fn foo(&self) -> Self::Y // OK, desugars to next example
760 // fn foo(&self) -> <Self as Trait>::Y // OK
761 // fn foo(&self) -> Self::X // OK, desugars to next example
762 // fn foo(&self) -> <Self as SuperTrait>::X // OK
766 // However, it is not as simple as allowing `Self` in a projected
767 // type, because there are illegal ways to use `Self` as well:
770 // trait Trait : SuperTrait {
772 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
776 // Here we will not have the type of `X` recorded in the
777 // object type, and we cannot resolve `Self as SomeOtherTrait`
778 // without knowing what `Self` is.
780 struct IllegalSelfTypeVisitor<'tcx> {
783 supertraits: Option<Vec<DefId>>,
786 impl<'tcx> TypeVisitor<'tcx> for IllegalSelfTypeVisitor<'tcx> {
789 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
792 if t == self.tcx.types.self_param {
795 ControlFlow::CONTINUE
798 ty::Projection(ref data)
799 if self.tcx.def_kind(data.item_def_id) == DefKind::ImplTraitPlaceholder =>
801 // We'll deny these later in their own pass
802 ControlFlow::CONTINUE
804 ty::Projection(ref data) => {
805 // This is a projected type `<Foo as SomeTrait>::X`.
807 // Compute supertraits of current trait lazily.
808 if self.supertraits.is_none() {
809 let trait_ref = ty::TraitRef::identity(self.tcx, self.trait_def_id);
810 self.supertraits = Some(
811 traits::supertraits(self.tcx, trait_ref).map(|t| t.def_id()).collect(),
815 // Determine whether the trait reference `Foo as
816 // SomeTrait` is in fact a supertrait of the
817 // current trait. In that case, this type is
818 // legal, because the type `X` will be specified
819 // in the object type. Note that we can just use
820 // direct equality here because all of these types
821 // are part of the formal parameter listing, and
822 // hence there should be no inference variables.
823 let is_supertrait_of_current_trait = self
827 .contains(&data.trait_ref(self.tcx).def_id);
829 if is_supertrait_of_current_trait {
830 ControlFlow::CONTINUE // do not walk contained types, do not report error, do collect $200
832 t.super_visit_with(self) // DO walk contained types, POSSIBLY reporting an error
835 _ => t.super_visit_with(self), // walk contained types, if any
839 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
840 // Constants can only influence object safety if they reference `Self`.
841 // This is only possible for unevaluated constants, so we walk these here.
843 // If `AbstractConst::from_const` returned an error we already failed compilation
844 // so we don't have to emit an additional error here.
845 use rustc_middle::ty::abstract_const::Node;
846 if let Ok(Some(ct)) = AbstractConst::from_const(self.tcx, ct) {
847 walk_abstract_const(self.tcx, ct, |node| match node.root(self.tcx) {
848 Node::Leaf(leaf) => self.visit_const(leaf),
849 Node::Cast(_, _, ty) => self.visit_ty(ty),
850 Node::Binop(..) | Node::UnaryOp(..) | Node::FunctionCall(_, _) => {
851 ControlFlow::CONTINUE
855 ct.super_visit_with(self)
861 .visit_with(&mut IllegalSelfTypeVisitor { tcx, trait_def_id, supertraits: None })
865 pub fn contains_illegal_impl_trait_in_trait<'tcx>(
867 ty: ty::Binder<'tcx, Ty<'tcx>>,
869 // FIXME(RPITIT): Perhaps we should use a visitor here?
870 ty.skip_binder().walk().any(|arg| {
871 if let ty::GenericArgKind::Type(ty) = arg.unpack()
872 && let ty::Projection(proj) = ty.kind()
874 tcx.def_kind(proj.item_def_id) == DefKind::ImplTraitPlaceholder
881 pub fn provide(providers: &mut ty::query::Providers) {
882 *providers = ty::query::Providers { object_safety_violations, ..*providers };