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, GenericArgKind, InternalSubsts, Subst}
;
20 use rustc_middle
::ty
::{self, Predicate, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness}
;
21 use rustc_session
::lint
::builtin
::WHERE_CLAUSES_OBJECT_SAFETY
;
22 use rustc_span
::symbol
::Symbol
;
24 use smallvec
::SmallVec
;
28 pub use crate::traits
::{MethodViolationCode, ObjectSafetyViolation}
;
30 /// Returns the object safety violations that affect
31 /// astconv -- currently, `Self` in supertraits. This is needed
32 /// because `object_safety_violations` can't be used during
34 pub fn astconv_object_safety_violations(
37 ) -> Vec
<ObjectSafetyViolation
> {
38 debug_assert
!(tcx
.generics_of(trait_def_id
).has_self
);
39 let violations
= traits
::supertrait_def_ids(tcx
, trait_def_id
)
40 .map(|def_id
| predicates_reference_self(tcx
, def_id
, true))
41 .filter(|spans
| !spans
.is_empty())
42 .map(ObjectSafetyViolation
::SupertraitSelf
)
45 debug
!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id
, violations
);
50 fn object_safety_violations(
53 ) -> &'tcx
[ObjectSafetyViolation
] {
54 debug_assert
!(tcx
.generics_of(trait_def_id
).has_self
);
55 debug
!("object_safety_violations: {:?}", trait_def_id
);
57 tcx
.arena
.alloc_from_iter(
58 traits
::supertrait_def_ids(tcx
, trait_def_id
)
59 .flat_map(|def_id
| object_safety_violations_for_trait(tcx
, def_id
)),
63 /// We say a method is *vtable safe* if it can be invoked on a trait
64 /// object. Note that object-safe traits can have some
65 /// non-vtable-safe methods, so long as they require `Self: Sized` or
66 /// otherwise ensure that they cannot be used when `Self = Trait`.
67 pub fn is_vtable_safe_method(tcx
: TyCtxt
<'_
>, trait_def_id
: DefId
, method
: &ty
::AssocItem
) -> bool
{
68 debug_assert
!(tcx
.generics_of(trait_def_id
).has_self
);
69 debug
!("is_vtable_safe_method({:?}, {:?})", trait_def_id
, method
);
70 // Any method that has a `Self: Sized` bound cannot be called.
71 if generics_require_sized_self(tcx
, method
.def_id
) {
75 match virtual_call_violation_for_method(tcx
, trait_def_id
, method
) {
76 None
| Some(MethodViolationCode
::WhereClauseReferencesSelf
) => true,
81 fn object_safety_violations_for_trait(
84 ) -> Vec
<ObjectSafetyViolation
> {
85 // Check methods for violations.
86 let mut violations
: Vec
<_
> = tcx
87 .associated_items(trait_def_id
)
88 .in_definition_order()
89 .filter(|item
| item
.kind
== ty
::AssocKind
::Fn
)
91 object_safety_violation_for_method(tcx
, trait_def_id
, &item
)
92 .map(|(code
, span
)| ObjectSafetyViolation
::Method(item
.ident
.name
, code
, span
))
95 if let ObjectSafetyViolation
::Method(
97 MethodViolationCode
::WhereClauseReferencesSelf
,
101 // Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
102 // It's also hard to get a use site span, so we use the method definition span.
103 tcx
.struct_span_lint_hir(
104 WHERE_CLAUSES_OBJECT_SAFETY
,
108 let mut err
= lint
.build(&format
!(
109 "the trait `{}` cannot be made into an object",
110 tcx
.def_path_str(trait_def_id
)
112 let node
= tcx
.hir().get_if_local(trait_def_id
);
113 let msg
= if let Some(hir
::Node
::Item(item
)) = node
{
116 "this trait cannot be made into an object...",
118 format
!("...because {}", violation
.error_msg())
121 "the trait cannot be made into an object because {}",
122 violation
.error_msg()
125 err
.span_label(*span
, &msg
);
126 match (node
, violation
.solution()) {
127 (Some(_
), Some((note
, None
))) => {
130 (Some(_
), Some((note
, Some((sugg
, span
))))) => {
135 Applicability
::MachineApplicable
,
138 // Only provide the help if its a local trait, otherwise it's not actionable.
151 // Check the trait itself.
152 if trait_has_sized_self(tcx
, trait_def_id
) {
153 // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
154 let spans
= get_sized_bounds(tcx
, trait_def_id
);
155 violations
.push(ObjectSafetyViolation
::SizedSelf(spans
));
157 let spans
= predicates_reference_self(tcx
, trait_def_id
, false);
158 if !spans
.is_empty() {
159 violations
.push(ObjectSafetyViolation
::SupertraitSelf(spans
));
163 tcx
.associated_items(trait_def_id
)
164 .in_definition_order()
165 .filter(|item
| item
.kind
== ty
::AssocKind
::Const
)
166 .map(|item
| ObjectSafetyViolation
::AssocConst(item
.ident
.name
, item
.ident
.span
)),
170 "object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
171 trait_def_id
, violations
177 fn sized_trait_bound_spans
<'tcx
>(
179 bounds
: hir
::GenericBounds
<'tcx
>,
180 ) -> impl 'tcx
+ Iterator
<Item
= Span
> {
181 bounds
.iter().filter_map(move |b
| match b
{
182 hir
::GenericBound
::Trait(trait_ref
, hir
::TraitBoundModifier
::None
)
183 if trait_has_sized_self(
185 trait_ref
.trait_ref
.trait_def_id().unwrap_or_else(|| FatalError
.raise()),
188 // Fetch spans for supertraits that are `Sized`: `trait T: Super`
195 fn get_sized_bounds(tcx
: TyCtxt
<'_
>, trait_def_id
: DefId
) -> SmallVec
<[Span
; 1]> {
197 .get_if_local(trait_def_id
)
198 .and_then(|node
| match node
{
199 hir
::Node
::Item(hir
::Item
{
200 kind
: hir
::ItemKind
::Trait(.., generics
, bounds
, _
),
209 hir
::WherePredicate
::BoundPredicate(pred
)
210 if pred
.bounded_ty
.hir_id
.owner
.to_def_id() == trait_def_id
=>
212 // Fetch spans for trait bounds that are Sized:
213 // `trait T where Self: Pred`
214 Some(sized_trait_bound_spans(tcx
, pred
.bounds
))
220 // Fetch spans for supertraits that are `Sized`: `trait T: Super`.
221 .chain(sized_trait_bound_spans(tcx
, bounds
))
222 .collect
::<SmallVec
<[Span
; 1]>>(),
226 .unwrap_or_else(SmallVec
::new
)
229 fn predicates_reference_self(
232 supertraits_only
: bool
,
233 ) -> SmallVec
<[Span
; 1]> {
234 let trait_ref
= ty
::Binder
::dummy(ty
::TraitRef
::identity(tcx
, trait_def_id
));
235 let predicates
= if supertraits_only
{
236 tcx
.super_predicates_of(trait_def_id
)
238 tcx
.predicates_of(trait_def_id
)
240 let self_ty
= tcx
.types
.self_param
;
241 let has_self_ty
= |arg
: &GenericArg
<'_
>| arg
.walk().any(|arg
| arg
== self_ty
.into());
245 .map(|(predicate
, sp
)| (predicate
.subst_supertrait(tcx
, &trait_ref
), sp
))
246 .filter_map(|(predicate
, &sp
)| {
248 ty
::Predicate
::Trait(ref data
, _
) => {
249 // In the case of a trait predicate, we can skip the "self" type.
250 if data
.skip_binder().trait_ref
.substs
[1..].iter().any(has_self_ty
) {
256 ty
::Predicate
::Projection(ref data
) => {
257 // And similarly for projections. This should be redundant with
258 // the previous check because any projection should have a
259 // matching `Trait` predicate with the same inputs, but we do
260 // the check to be safe.
262 // Note that we *do* allow projection *outputs* to contain
263 // `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
264 // we just require the user to specify *both* outputs
265 // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
267 // This is ALT2 in issue #56288, see that for discussion of the
268 // possible alternatives.
269 if data
.skip_binder().projection_ty
.trait_ref(tcx
).substs
[1..]
278 ty
::Predicate
::WellFormed(..)
279 | ty
::Predicate
::ObjectSafe(..)
280 | ty
::Predicate
::TypeOutlives(..)
281 | ty
::Predicate
::RegionOutlives(..)
282 | ty
::Predicate
::ClosureKind(..)
283 | ty
::Predicate
::Subtype(..)
284 | ty
::Predicate
::ConstEvaluatable(..) => None
,
290 fn trait_has_sized_self(tcx
: TyCtxt
<'_
>, trait_def_id
: DefId
) -> bool
{
291 generics_require_sized_self(tcx
, trait_def_id
)
294 fn generics_require_sized_self(tcx
: TyCtxt
<'_
>, def_id
: DefId
) -> bool
{
295 let sized_def_id
= match tcx
.lang_items().sized_trait() {
296 Some(def_id
) => def_id
,
298 return false; /* No Sized trait, can't require it! */
302 // Search for a predicate like `Self : Sized` amongst the trait bounds.
303 let predicates
= tcx
.predicates_of(def_id
);
304 let predicates
= predicates
.instantiate_identity(tcx
).predicates
;
305 elaborate_predicates(tcx
, predicates
.into_iter()).any(|obligation
| match obligation
.predicate
{
306 ty
::Predicate
::Trait(ref trait_pred
, _
) => {
307 trait_pred
.def_id() == sized_def_id
&& trait_pred
.skip_binder().self_ty().is_param(0)
309 ty
::Predicate
::Projection(..)
310 | ty
::Predicate
::Subtype(..)
311 | ty
::Predicate
::RegionOutlives(..)
312 | ty
::Predicate
::WellFormed(..)
313 | ty
::Predicate
::ObjectSafe(..)
314 | ty
::Predicate
::ClosureKind(..)
315 | ty
::Predicate
::TypeOutlives(..)
316 | ty
::Predicate
::ConstEvaluatable(..) => false,
320 /// Returns `Some(_)` if this method makes the containing trait not object safe.
321 fn object_safety_violation_for_method(
324 method
: &ty
::AssocItem
,
325 ) -> Option
<(MethodViolationCode
, Span
)> {
326 debug
!("object_safety_violation_for_method({:?}, {:?})", trait_def_id
, method
);
327 // Any method that has a `Self : Sized` requisite is otherwise
328 // exempt from the regulations.
329 if generics_require_sized_self(tcx
, method
.def_id
) {
333 let violation
= virtual_call_violation_for_method(tcx
, trait_def_id
, method
);
334 // Get an accurate span depending on the violation.
336 let node
= tcx
.hir().get_if_local(method
.def_id
);
337 let span
= match (v
, node
) {
338 (MethodViolationCode
::ReferencesSelfInput(arg
), Some(node
)) => node
340 .and_then(|decl
| decl
.inputs
.get(arg
+ 1))
341 .map_or(method
.ident
.span
, |arg
| arg
.span
),
342 (MethodViolationCode
::UndispatchableReceiver
, Some(node
)) => node
344 .and_then(|decl
| decl
.inputs
.get(0))
345 .map_or(method
.ident
.span
, |arg
| arg
.span
),
346 (MethodViolationCode
::ReferencesSelfOutput
, Some(node
)) => {
347 node
.fn_decl().map_or(method
.ident
.span
, |decl
| decl
.output
.span())
349 _
=> method
.ident
.span
,
355 /// Returns `Some(_)` if this method cannot be called on a trait
356 /// object; this does not necessarily imply that the enclosing trait
357 /// is not object safe, because the method might have a where clause
359 fn virtual_call_violation_for_method
<'tcx
>(
362 method
: &ty
::AssocItem
,
363 ) -> Option
<MethodViolationCode
> {
364 // The method's first parameter must be named `self`
365 if !method
.fn_has_self_parameter
{
366 // We'll attempt to provide a structured suggestion for `Self: Sized`.
368 tcx
.hir().get_if_local(method
.def_id
).as_ref().and_then(|node
| node
.generics()).map(
369 |generics
| match generics
.where_clause
.predicates
{
370 [] => (" where Self: Sized", generics
.where_clause
.span
),
371 [.., pred
] => (", Self: Sized", pred
.span().shrink_to_hi()),
374 return Some(MethodViolationCode
::StaticMethod(sugg
));
377 let sig
= tcx
.fn_sig(method
.def_id
);
379 for (i
, input_ty
) in sig
.skip_binder().inputs()[1..].iter().enumerate() {
380 if contains_illegal_self_type_reference(tcx
, trait_def_id
, input_ty
) {
381 return Some(MethodViolationCode
::ReferencesSelfInput(i
));
384 if contains_illegal_self_type_reference(tcx
, trait_def_id
, sig
.output().skip_binder()) {
385 return Some(MethodViolationCode
::ReferencesSelfOutput
);
388 // We can't monomorphize things like `fn foo<A>(...)`.
389 let own_counts
= tcx
.generics_of(method
.def_id
).own_counts();
390 if own_counts
.types
+ own_counts
.consts
!= 0 {
391 return Some(MethodViolationCode
::Generic
);
395 .predicates_of(method
.def_id
)
398 // A trait object can't claim to live more than the concrete type,
399 // so outlives predicates will always hold.
401 .filter(|(p
, _
)| p
.to_opt_type_outlives().is_none())
403 // Do a shallow visit so that `contains_illegal_self_type_reference`
404 // may apply it's custom visiting.
405 .visit_tys_shallow(|t
| contains_illegal_self_type_reference(tcx
, trait_def_id
, t
))
407 return Some(MethodViolationCode
::WhereClauseReferencesSelf
);
411 tcx
.liberate_late_bound_regions(method
.def_id
, &sig
.map_bound(|sig
| sig
.inputs()[0]));
413 // Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
414 // However, this is already considered object-safe. We allow it as a special case here.
415 // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
416 // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
417 if receiver_ty
!= tcx
.types
.self_param
{
418 if !receiver_is_dispatchable(tcx
, method
, receiver_ty
) {
419 return Some(MethodViolationCode
::UndispatchableReceiver
);
421 // Do sanity check to make sure the receiver actually has the layout of a pointer.
423 use rustc_target
::abi
::Abi
;
425 let param_env
= tcx
.param_env(method
.def_id
);
427 let abi_of_ty
= |ty
: Ty
<'tcx
>| -> &Abi
{
428 match tcx
.layout_of(param_env
.and(ty
)) {
429 Ok(layout
) => &layout
.abi
,
430 Err(err
) => bug
!("error: {}\n while computing layout for type {:?}", err
, ty
),
435 let unit_receiver_ty
=
436 receiver_for_self_ty(tcx
, receiver_ty
, tcx
.mk_unit(), method
.def_id
);
438 match abi_of_ty(unit_receiver_ty
) {
439 &Abi
::Scalar(..) => (),
441 tcx
.sess
.delay_span_bug(
442 tcx
.def_span(method
.def_id
),
444 "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
451 let trait_object_ty
=
452 object_ty_for_trait(tcx
, trait_def_id
, tcx
.mk_region(ty
::ReStatic
));
454 // e.g., `Rc<dyn Trait>`
455 let trait_object_receiver
=
456 receiver_for_self_ty(tcx
, receiver_ty
, trait_object_ty
, method
.def_id
);
458 match abi_of_ty(trait_object_receiver
) {
459 &Abi
::ScalarPair(..) => (),
461 tcx
.sess
.delay_span_bug(
462 tcx
.def_span(method
.def_id
),
464 "receiver when `Self = {}` should have a ScalarPair ABI; \
477 /// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
478 /// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
479 fn receiver_for_self_ty
<'tcx
>(
481 receiver_ty
: Ty
<'tcx
>,
483 method_def_id
: DefId
,
485 debug
!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty
, self_ty
, method_def_id
);
486 let substs
= InternalSubsts
::for_item(tcx
, method_def_id
, |param
, _
| {
487 if param
.index
== 0 { self_ty.into() }
else { tcx.mk_param_from_def(param) }
490 let result
= receiver_ty
.subst(tcx
, substs
);
492 "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
493 receiver_ty
, self_ty
, method_def_id
, result
498 /// Creates the object type for the current trait. For example,
499 /// if the current trait is `Deref`, then this will be
500 /// `dyn Deref<Target = Self::Target> + 'static`.
501 fn object_ty_for_trait
<'tcx
>(
504 lifetime
: ty
::Region
<'tcx
>,
506 debug
!("object_ty_for_trait: trait_def_id={:?}", trait_def_id
);
508 let trait_ref
= ty
::TraitRef
::identity(tcx
, trait_def_id
);
510 let trait_predicate
=
511 ty
::ExistentialPredicate
::Trait(ty
::ExistentialTraitRef
::erase_self_ty(tcx
, trait_ref
));
513 let mut associated_types
= traits
::supertraits(tcx
, ty
::Binder
::dummy(trait_ref
))
514 .flat_map(|super_trait_ref
| {
515 tcx
.associated_items(super_trait_ref
.def_id())
516 .in_definition_order()
517 .map(move |item
| (super_trait_ref
, item
))
519 .filter(|(_
, item
)| item
.kind
== ty
::AssocKind
::Type
)
520 .collect
::<Vec
<_
>>();
522 // existential predicates need to be in a specific order
523 associated_types
.sort_by_cached_key(|(_
, item
)| tcx
.def_path_hash(item
.def_id
));
525 let projection_predicates
= associated_types
.into_iter().map(|(super_trait_ref
, item
)| {
526 // We *can* get bound lifetimes here in cases like
527 // `trait MyTrait: for<'s> OtherTrait<&'s T, Output=bool>`.
529 // binder moved to (*)...
530 let super_trait_ref
= super_trait_ref
.skip_binder();
531 ty
::ExistentialPredicate
::Projection(ty
::ExistentialProjection
{
532 ty
: tcx
.mk_projection(item
.def_id
, super_trait_ref
.substs
),
533 item_def_id
: item
.def_id
,
534 substs
: super_trait_ref
.substs
,
538 let existential_predicates
=
539 tcx
.mk_existential_predicates(iter
::once(trait_predicate
).chain(projection_predicates
));
541 let object_ty
= tcx
.mk_dynamic(
542 // (*) ... binder re-introduced here
543 ty
::Binder
::bind(existential_predicates
),
547 debug
!("object_ty_for_trait: object_ty=`{}`", object_ty
);
552 /// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
553 /// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
554 /// in the following way:
555 /// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
556 /// - require the following bound:
559 /// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
562 /// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
563 /// (substitution notation).
565 /// Some examples of receiver types and their required obligation:
566 /// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
567 /// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
568 /// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
570 /// The only case where the receiver is not dispatchable, but is still a valid receiver
571 /// type (just not object-safe), is when there is more than one level of pointer indirection.
572 /// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
573 /// is no way, or at least no inexpensive way, to coerce the receiver from the version where
574 /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
575 /// contained by the trait object, because the object that needs to be coerced is behind
578 /// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
579 /// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
580 /// is stabilized, see tracking issue https://github.com/rust-lang/rust/issues/43561).
581 /// Instead, we fudge a little by introducing a new type parameter `U` such that
582 /// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
583 /// Written as a chalk-style query:
585 /// forall (U: Trait + ?Sized) {
586 /// if (Self: Unsize<U>) {
587 /// Receiver: DispatchFromDyn<Receiver[Self => U]>
591 /// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
592 /// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
593 /// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
595 // FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
596 // fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
597 // `self: Wrapper<Self>`.
599 fn receiver_is_dispatchable
<'tcx
>(
601 method
: &ty
::AssocItem
,
602 receiver_ty
: Ty
<'tcx
>,
604 debug
!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method
, receiver_ty
);
606 let traits
= (tcx
.lang_items().unsize_trait(), tcx
.lang_items().dispatch_from_dyn_trait());
607 let (unsize_did
, dispatch_from_dyn_did
) = if let (Some(u
), Some(cu
)) = traits
{
610 debug
!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
614 // the type `U` in the query
615 // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
616 // FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
617 // replace this with `dyn Trait`
618 let unsized_self_ty
: Ty
<'tcx
> =
619 tcx
.mk_ty_param(u32::MAX
, Symbol
::intern("RustaceansAreAwesome"));
621 // `Receiver[Self => U]`
622 let unsized_receiver_ty
=
623 receiver_for_self_ty(tcx
, receiver_ty
, unsized_self_ty
, method
.def_id
);
625 // create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
626 // `U: ?Sized` is already implied here
628 let mut param_env
= tcx
.param_env(method
.def_id
);
631 let unsize_predicate
= ty
::TraitRef
{
633 substs
: tcx
.mk_substs_trait(tcx
.types
.self_param
, &[unsized_self_ty
.into()]),
638 // U: Trait<Arg1, ..., ArgN>
639 let trait_predicate
= {
641 InternalSubsts
::for_item(tcx
, method
.container
.assert_trait(), |param
, _
| {
642 if param
.index
== 0 {
643 unsized_self_ty
.into()
645 tcx
.mk_param_from_def(param
)
649 ty
::TraitRef { def_id: unsize_did, substs }
.without_const().to_predicate()
652 let caller_bounds
: Vec
<Predicate
<'tcx
>> = param_env
656 .chain(iter
::once(unsize_predicate
))
657 .chain(iter
::once(trait_predicate
))
660 param_env
.caller_bounds
= tcx
.intern_predicates(&caller_bounds
);
665 // Receiver: DispatchFromDyn<Receiver[Self => U]>
667 let predicate
= ty
::TraitRef
{
668 def_id
: dispatch_from_dyn_did
,
669 substs
: tcx
.mk_substs_trait(receiver_ty
, &[unsized_receiver_ty
.into()]),
674 Obligation
::new(ObligationCause
::dummy(), param_env
, predicate
)
677 tcx
.infer_ctxt().enter(|ref infcx
| {
678 // the receiver is dispatchable iff the obligation holds
679 infcx
.predicate_must_hold_modulo_regions(&obligation
)
683 fn contains_illegal_self_type_reference
<'tcx
>(
688 // This is somewhat subtle. In general, we want to forbid
689 // references to `Self` in the argument and return types,
690 // since the value of `Self` is erased. However, there is one
691 // exception: it is ok to reference `Self` in order to access
692 // an associated type of the current trait, since we retain
693 // the value of those associated types in the object type
697 // trait SuperTrait {
701 // trait Trait : SuperTrait {
703 // fn foo(&self, x: Self) // bad
704 // fn foo(&self) -> Self // bad
705 // fn foo(&self) -> Option<Self> // bad
706 // fn foo(&self) -> Self::Y // OK, desugars to next example
707 // fn foo(&self) -> <Self as Trait>::Y // OK
708 // fn foo(&self) -> Self::X // OK, desugars to next example
709 // fn foo(&self) -> <Self as SuperTrait>::X // OK
713 // However, it is not as simple as allowing `Self` in a projected
714 // type, because there are illegal ways to use `Self` as well:
717 // trait Trait : SuperTrait {
719 // fn foo(&self) -> <Self as SomeOtherTrait>::X;
723 // Here we will not have the type of `X` recorded in the
724 // object type, and we cannot resolve `Self as SomeOtherTrait`
725 // without knowing what `Self` is.
727 let mut supertraits
: Option
<Vec
<ty
::PolyTraitRef
<'tcx
>>> = None
;
728 let self_ty
= tcx
.types
.self_param
;
730 let mut walker
= ty
.walk();
731 while let Some(arg
) = walker
.next() {
732 if arg
== self_ty
.into() {
736 // Special-case projections (everything else is walked normally).
737 if let GenericArgKind
::Type(ty
) = arg
.unpack() {
738 if let ty
::Projection(ref data
) = ty
.kind
{
739 // This is a projected type `<Foo as SomeTrait>::X`.
741 // Compute supertraits of current trait lazily.
742 if supertraits
.is_none() {
743 let trait_ref
= ty
::Binder
::bind(ty
::TraitRef
::identity(tcx
, trait_def_id
));
744 supertraits
= Some(traits
::supertraits(tcx
, trait_ref
).collect());
747 // Determine whether the trait reference `Foo as
748 // SomeTrait` is in fact a supertrait of the
749 // current trait. In that case, this type is
750 // legal, because the type `X` will be specified
751 // in the object type. Note that we can just use
752 // direct equality here because all of these types
753 // are part of the formal parameter listing, and
754 // hence there should be no inference variables.
755 let projection_trait_ref
= ty
::Binder
::bind(data
.trait_ref(tcx
));
756 let is_supertrait_of_current_trait
=
757 supertraits
.as_ref().unwrap().contains(&projection_trait_ref
);
759 if is_supertrait_of_current_trait
{
760 // Do not walk contained types, do not report error, do collect $200.
761 walker
.skip_current_subtree();
764 // DO walk contained types, POSSIBLY reporting an error.
768 // Walk contained types, if any.
774 pub fn provide(providers
: &mut ty
::query
::Providers
<'_
>) {
775 *providers
= ty
::query
::Providers { object_safety_violations, ..*providers }
;