2014-12-15 21:11:09 -05:00
|
|
|
//! "Object safety" refers to the ability for a trait to be converted
|
|
|
|
//! to an object. In general, traits may only be converted to an
|
|
|
|
//! object if all of their methods meet certain criteria. In particular,
|
|
|
|
//! they must:
|
|
|
|
//!
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
//! - have a suitable receiver from which we can extract a vtable and coerce to a "thin" version
|
|
|
|
//! that doesn't contain the vtable;
|
2014-12-15 21:11:09 -05:00
|
|
|
//! - not reference the erased type `Self` except for in this receiver;
|
2019-02-08 14:53:55 +01:00
|
|
|
//! - not have generic type parameters.
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2023-04-06 23:24:03 +00:00
|
|
|
use super::elaborate;
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2020-01-06 20:13:24 +01:00
|
|
|
use crate::infer::TyCtxtInferExt;
|
2020-02-22 11:44:18 +01:00
|
|
|
use crate::traits::query::evaluate_obligation::InferCtxtExt;
|
2019-02-05 11:20:45 -06:00
|
|
|
use crate::traits::{self, Obligation, ObligationCause};
|
2022-09-16 11:01:02 +04:00
|
|
|
use rustc_errors::{DelayDm, FatalError, MultiSpan};
|
2020-01-05 02:37:57 +01:00
|
|
|
use rustc_hir as hir;
|
|
|
|
use rustc_hir::def_id::DefId;
|
2023-05-15 06:24:45 +02:00
|
|
|
use rustc_middle::query::Providers;
|
2022-07-27 07:27:52 +00:00
|
|
|
use rustc_middle::ty::subst::{GenericArg, InternalSubsts};
|
Folding revamp.
This commit makes type folding more like the way chalk does it.
Currently, `TypeFoldable` has `fold_with` and `super_fold_with` methods.
- `fold_with` is the standard entry point, and defaults to calling
`super_fold_with`.
- `super_fold_with` does the actual work of traversing a type.
- For a few types of interest (`Ty`, `Region`, etc.) `fold_with` instead
calls into a `TypeFolder`, which can then call back into
`super_fold_with`.
With the new approach, `TypeFoldable` has `fold_with` and
`TypeSuperFoldable` has `super_fold_with`.
- `fold_with` is still the standard entry point, *and* it does the
actual work of traversing a type, for all types except types of
interest.
- `super_fold_with` is only implemented for the types of interest.
Benefits of the new model.
- I find it easier to understand. The distinction between types of
interest and other types is clearer, and `super_fold_with` doesn't
exist for most types.
- With the current model is easy to get confused and implement a
`super_fold_with` method that should be left defaulted. (Some of the
precursor commits fixed such cases.)
- With the current model it's easy to call `super_fold_with` within
`TypeFolder` impls where `fold_with` should be called. The new
approach makes this mistake impossible, and this commit fixes a number
of such cases.
- It's potentially faster, because it avoids the `fold_with` ->
`super_fold_with` call in all cases except types of interest. A lot of
the time the compile would inline those away, but not necessarily
always.
2022-06-02 11:38:15 +10:00
|
|
|
use rustc_middle::ty::{
|
2023-02-22 02:18:40 +00:00
|
|
|
self, EarlyBinder, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor,
|
Folding revamp.
This commit makes type folding more like the way chalk does it.
Currently, `TypeFoldable` has `fold_with` and `super_fold_with` methods.
- `fold_with` is the standard entry point, and defaults to calling
`super_fold_with`.
- `super_fold_with` does the actual work of traversing a type.
- For a few types of interest (`Ty`, `Region`, etc.) `fold_with` instead
calls into a `TypeFolder`, which can then call back into
`super_fold_with`.
With the new approach, `TypeFoldable` has `fold_with` and
`TypeSuperFoldable` has `super_fold_with`.
- `fold_with` is still the standard entry point, *and* it does the
actual work of traversing a type, for all types except types of
interest.
- `super_fold_with` is only implemented for the types of interest.
Benefits of the new model.
- I find it easier to understand. The distinction between types of
interest and other types is clearer, and `super_fold_with` doesn't
exist for most types.
- With the current model is easy to get confused and implement a
`super_fold_with` method that should be left defaulted. (Some of the
precursor commits fixed such cases.)
- With the current model it's easy to call `super_fold_with` within
`TypeFolder` impls where `fold_with` should be called. The new
approach makes this mistake impossible, and this commit fixes a number
of such cases.
- It's potentially faster, because it avoids the `fold_with` ->
`super_fold_with` call in all cases except types of interest. A lot of
the time the compile would inline those away, but not necessarily
always.
2022-06-02 11:38:15 +10:00
|
|
|
};
|
2023-03-07 05:51:43 +00:00
|
|
|
use rustc_middle::ty::{ToPredicate, TypeVisitableExt};
|
2020-01-05 10:58:44 +01:00
|
|
|
use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY;
|
2020-01-01 19:30:57 +01:00
|
|
|
use rustc_span::symbol::Symbol;
|
2022-03-24 02:03:04 +00:00
|
|
|
use rustc_span::Span;
|
2020-02-10 19:55:49 +01:00
|
|
|
use smallvec::SmallVec;
|
2020-01-05 10:58:44 +01:00
|
|
|
|
2020-02-10 19:55:49 +01:00
|
|
|
use std::iter;
|
2020-10-21 14:24:35 +02:00
|
|
|
use std::ops::ControlFlow;
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2020-02-10 19:55:49 +01:00
|
|
|
pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation};
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2020-01-05 18:07:29 +01:00
|
|
|
/// Returns the object safety violations that affect
|
|
|
|
/// astconv -- currently, `Self` in supertraits. This is needed
|
|
|
|
/// because `object_safety_violations` can't be used during
|
|
|
|
/// type collection.
|
|
|
|
pub fn astconv_object_safety_violations(
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
trait_def_id: DefId,
|
|
|
|
) -> Vec<ObjectSafetyViolation> {
|
|
|
|
debug_assert!(tcx.generics_of(trait_def_id).has_self);
|
|
|
|
let violations = traits::supertrait_def_ids(tcx, trait_def_id)
|
2020-02-02 12:51:30 -08:00
|
|
|
.map(|def_id| predicates_reference_self(tcx, def_id, true))
|
|
|
|
.filter(|spans| !spans.is_empty())
|
2020-03-22 12:43:19 +01:00
|
|
|
.map(ObjectSafetyViolation::SupertraitSelf)
|
2020-01-05 18:07:29 +01:00
|
|
|
.collect();
|
2015-09-24 18:27:29 +03:00
|
|
|
|
2020-01-05 18:07:29 +01:00
|
|
|
debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
|
2015-09-24 18:27:29 +03:00
|
|
|
|
2020-01-05 18:07:29 +01:00
|
|
|
violations
|
|
|
|
}
|
|
|
|
|
2021-12-14 09:44:49 +00:00
|
|
|
fn object_safety_violations(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &'_ [ObjectSafetyViolation] {
|
2020-01-05 18:07:29 +01:00
|
|
|
debug_assert!(tcx.generics_of(trait_def_id).has_self);
|
|
|
|
debug!("object_safety_violations: {:?}", trait_def_id);
|
2016-05-11 08:48:12 +03:00
|
|
|
|
2020-03-14 12:06:06 +01:00
|
|
|
tcx.arena.alloc_from_iter(
|
|
|
|
traits::supertrait_def_ids(tcx, trait_def_id)
|
|
|
|
.flat_map(|def_id| object_safety_violations_for_trait(tcx, def_id)),
|
|
|
|
)
|
2020-01-05 18:07:29 +01:00
|
|
|
}
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
|
2023-01-28 15:07:21 +00:00
|
|
|
fn check_is_object_safe(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
|
2022-12-29 09:53:25 +00:00
|
|
|
let violations = tcx.object_safety_violations(trait_def_id);
|
|
|
|
|
|
|
|
if violations.is_empty() {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the trait contains any other violations, then let the error reporting path
|
|
|
|
// report it instead of emitting a warning here.
|
|
|
|
if violations.iter().all(|violation| {
|
|
|
|
matches!(
|
|
|
|
violation,
|
|
|
|
ObjectSafetyViolation::Method(_, MethodViolationCode::WhereClauseReferencesSelf, _)
|
|
|
|
)
|
|
|
|
}) {
|
|
|
|
for violation in violations {
|
|
|
|
if let ObjectSafetyViolation::Method(
|
|
|
|
_,
|
|
|
|
MethodViolationCode::WhereClauseReferencesSelf,
|
|
|
|
span,
|
|
|
|
) = violation
|
|
|
|
{
|
|
|
|
lint_object_unsafe_trait(tcx, *span, trait_def_id, &violation);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
2020-01-05 18:07:29 +01:00
|
|
|
/// We say a method is *vtable safe* if it can be invoked on a trait
|
|
|
|
/// object. Note that object-safe traits can have some
|
|
|
|
/// non-vtable-safe methods, so long as they require `Self: Sized` or
|
|
|
|
/// otherwise ensure that they cannot be used when `Self = Trait`.
|
2023-02-06 08:57:34 +00:00
|
|
|
pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: ty::AssocItem) -> bool {
|
2020-01-05 18:07:29 +01:00
|
|
|
debug_assert!(tcx.generics_of(trait_def_id).has_self);
|
|
|
|
debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
|
|
|
|
// Any method that has a `Self: Sized` bound cannot be called.
|
2023-06-16 12:38:57 +00:00
|
|
|
if tcx.generics_require_sized_self(method.def_id) {
|
2020-01-05 18:07:29 +01:00
|
|
|
return false;
|
2016-05-11 08:48:12 +03:00
|
|
|
}
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2020-01-05 18:07:29 +01:00
|
|
|
match virtual_call_violation_for_method(tcx, trait_def_id, method) {
|
|
|
|
None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
|
|
|
|
Some(_) => false,
|
2019-07-07 16:34:06 +01:00
|
|
|
}
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
2019-07-07 16:34:06 +01:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
fn object_safety_violations_for_trait(
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
trait_def_id: DefId,
|
|
|
|
) -> Vec<ObjectSafetyViolation> {
|
2023-06-05 15:32:23 +00:00
|
|
|
// Check assoc items for violations.
|
2020-01-05 15:48:46 +01:00
|
|
|
let mut violations: Vec<_> = tcx
|
|
|
|
.associated_items(trait_def_id)
|
2020-02-17 13:09:01 -08:00
|
|
|
.in_definition_order()
|
2023-06-05 15:32:23 +00:00
|
|
|
.filter_map(|&item| object_safety_violation_for_assoc_item(tcx, trait_def_id, item))
|
2020-01-05 15:48:46 +01:00
|
|
|
.collect();
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
// Check the trait itself.
|
|
|
|
if trait_has_sized_self(tcx, trait_def_id) {
|
2020-01-29 12:59:04 -08:00
|
|
|
// We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
|
|
|
|
let spans = get_sized_bounds(tcx, trait_def_id);
|
|
|
|
violations.push(ObjectSafetyViolation::SizedSelf(spans));
|
2016-05-11 08:48:12 +03:00
|
|
|
}
|
2020-02-02 12:51:30 -08:00
|
|
|
let spans = predicates_reference_self(tcx, trait_def_id, false);
|
|
|
|
if !spans.is_empty() {
|
|
|
|
violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
|
2016-05-11 08:48:12 +03:00
|
|
|
}
|
2020-06-28 17:36:41 +01:00
|
|
|
let spans = bounds_reference_self(tcx, trait_def_id);
|
|
|
|
if !spans.is_empty() {
|
|
|
|
violations.push(ObjectSafetyViolation::SupertraitSelf(spans));
|
|
|
|
}
|
2023-03-07 05:51:43 +00:00
|
|
|
let spans = super_predicates_have_non_lifetime_binders(tcx, trait_def_id);
|
|
|
|
if !spans.is_empty() {
|
|
|
|
violations.push(ObjectSafetyViolation::SupertraitNonLifetimeBinder(spans));
|
|
|
|
}
|
2015-02-17 10:57:15 -05:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
debug!(
|
|
|
|
"object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
|
|
|
|
trait_def_id, violations
|
|
|
|
);
|
2016-05-11 08:48:12 +03:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
violations
|
|
|
|
}
|
|
|
|
|
2020-10-19 17:57:18 -07:00
|
|
|
/// Lint object-unsafe trait.
|
|
|
|
fn lint_object_unsafe_trait(
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
span: Span,
|
|
|
|
trait_def_id: DefId,
|
|
|
|
violation: &ObjectSafetyViolation,
|
|
|
|
) {
|
|
|
|
// Using `CRATE_NODE_ID` is wrong, but it's hard to get a more precise id.
|
|
|
|
// It's also hard to get a use site span, so we use the method definition span.
|
2022-09-16 11:01:02 +04:00
|
|
|
tcx.struct_span_lint_hir(
|
|
|
|
WHERE_CLAUSES_OBJECT_SAFETY,
|
|
|
|
hir::CRATE_HIR_ID,
|
|
|
|
span,
|
|
|
|
DelayDm(|| format!("the trait `{}` cannot be made into an object", tcx.def_path_str(trait_def_id))),
|
|
|
|
|err| {
|
|
|
|
let node = tcx.hir().get_if_local(trait_def_id);
|
|
|
|
let mut spans = MultiSpan::from_span(span);
|
|
|
|
if let Some(hir::Node::Item(item)) = node {
|
|
|
|
spans.push_span_label(
|
|
|
|
item.ident.span,
|
|
|
|
"this trait cannot be made into an object...",
|
|
|
|
);
|
|
|
|
spans.push_span_label(span, format!("...because {}", violation.error_msg()));
|
|
|
|
} else {
|
|
|
|
spans.push_span_label(
|
|
|
|
span,
|
|
|
|
format!(
|
|
|
|
"the trait cannot be made into an object because {}",
|
|
|
|
violation.error_msg()
|
|
|
|
),
|
|
|
|
);
|
|
|
|
};
|
|
|
|
err.span_note(
|
|
|
|
spans,
|
|
|
|
"for a trait to be \"object safe\" it needs to allow building a vtable to allow the \
|
|
|
|
call to be resolvable dynamically; for more information visit \
|
|
|
|
<https://doc.rust-lang.org/reference/items/traits.html#object-safety>",
|
2020-10-19 17:57:18 -07:00
|
|
|
);
|
2022-09-16 11:01:02 +04:00
|
|
|
if node.is_some() {
|
|
|
|
// Only provide the help if its a local trait, otherwise it's not
|
|
|
|
violation.solution(err);
|
|
|
|
}
|
|
|
|
err
|
|
|
|
},
|
|
|
|
);
|
2020-10-19 17:57:18 -07:00
|
|
|
}
|
|
|
|
|
2020-03-26 09:59:07 +01:00
|
|
|
fn sized_trait_bound_spans<'tcx>(
|
2020-03-23 20:27:59 +01:00
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
bounds: hir::GenericBounds<'tcx>,
|
|
|
|
) -> impl 'tcx + Iterator<Item = Span> {
|
|
|
|
bounds.iter().filter_map(move |b| match b {
|
|
|
|
hir::GenericBound::Trait(trait_ref, hir::TraitBoundModifier::None)
|
|
|
|
if trait_has_sized_self(
|
|
|
|
tcx,
|
|
|
|
trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
|
|
|
|
) =>
|
|
|
|
{
|
|
|
|
// Fetch spans for supertraits that are `Sized`: `trait T: Super`
|
|
|
|
Some(trait_ref.span)
|
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-01-29 12:59:04 -08:00
|
|
|
fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
|
2020-01-19 14:53:37 -08:00
|
|
|
tcx.hir()
|
|
|
|
.get_if_local(trait_def_id)
|
|
|
|
.and_then(|node| match node {
|
2020-01-29 13:27:53 -08:00
|
|
|
hir::Node::Item(hir::Item {
|
|
|
|
kind: hir::ItemKind::Trait(.., generics, bounds, _),
|
|
|
|
..
|
|
|
|
}) => Some(
|
|
|
|
generics
|
|
|
|
.predicates
|
2020-01-29 12:59:04 -08:00
|
|
|
.iter()
|
2020-01-29 13:27:53 -08:00
|
|
|
.filter_map(|pred| {
|
|
|
|
match pred {
|
|
|
|
hir::WherePredicate::BoundPredicate(pred)
|
2020-03-18 20:27:59 +02:00
|
|
|
if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
|
2020-01-29 13:27:53 -08:00
|
|
|
{
|
|
|
|
// Fetch spans for trait bounds that are Sized:
|
|
|
|
// `trait T where Self: Pred`
|
2020-03-26 09:59:07 +01:00
|
|
|
Some(sized_trait_bound_spans(tcx, pred.bounds))
|
2020-01-29 13:27:53 -08:00
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.flatten()
|
2020-03-23 20:27:59 +01:00
|
|
|
// Fetch spans for supertraits that are `Sized`: `trait T: Super`.
|
2020-03-26 09:59:07 +01:00
|
|
|
.chain(sized_trait_bound_spans(tcx, bounds))
|
2020-01-29 12:59:04 -08:00
|
|
|
.collect::<SmallVec<[Span; 1]>>(),
|
|
|
|
),
|
2020-01-19 14:53:37 -08:00
|
|
|
_ => None,
|
|
|
|
})
|
2020-01-29 12:59:04 -08:00
|
|
|
.unwrap_or_else(SmallVec::new)
|
2020-01-19 14:53:37 -08:00
|
|
|
}
|
|
|
|
|
2020-02-02 12:51:30 -08:00
|
|
|
fn predicates_reference_self(
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
trait_def_id: DefId,
|
|
|
|
supertraits_only: bool,
|
|
|
|
) -> SmallVec<[Span; 1]> {
|
2023-04-26 11:59:51 +00:00
|
|
|
let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
|
2020-01-05 15:48:46 +01:00
|
|
|
let predicates = if supertraits_only {
|
|
|
|
tcx.super_predicates_of(trait_def_id)
|
|
|
|
} else {
|
|
|
|
tcx.predicates_of(trait_def_id)
|
|
|
|
};
|
|
|
|
predicates
|
|
|
|
.predicates
|
|
|
|
.iter()
|
2020-10-25 18:05:37 +01:00
|
|
|
.map(|&(predicate, sp)| (predicate.subst_supertrait(tcx, &trait_ref), sp))
|
2020-06-28 17:36:41 +01:00
|
|
|
.filter_map(|predicate| predicate_references_self(tcx, predicate))
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
|
|
|
|
tcx.associated_items(trait_def_id)
|
|
|
|
.in_definition_order()
|
|
|
|
.filter(|item| item.kind == ty::AssocKind::Type)
|
2023-04-17 17:19:08 -06:00
|
|
|
.flat_map(|item| tcx.explicit_item_bounds(item.def_id).subst_identity_iter_copied())
|
2023-06-22 18:17:13 +00:00
|
|
|
.filter_map(|c| predicate_references_self(tcx, c))
|
2020-02-02 12:51:30 -08:00
|
|
|
.collect()
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
2016-05-11 08:48:12 +03:00
|
|
|
|
2021-12-14 09:44:49 +00:00
|
|
|
fn predicate_references_self<'tcx>(
|
2020-06-28 17:36:41 +01:00
|
|
|
tcx: TyCtxt<'tcx>,
|
2023-06-22 18:17:13 +00:00
|
|
|
(predicate, sp): (ty::Clause<'tcx>, Span),
|
2020-06-28 17:36:41 +01:00
|
|
|
) -> Option<Span> {
|
|
|
|
let self_ty = tcx.types.self_param;
|
2022-05-22 12:48:19 -07:00
|
|
|
let has_self_ty = |arg: &GenericArg<'tcx>| arg.walk().any(|arg| arg == self_ty.into());
|
2021-01-07 11:20:28 -05:00
|
|
|
match predicate.kind().skip_binder() {
|
2023-06-22 18:17:13 +00:00
|
|
|
ty::ClauseKind::Trait(ref data) => {
|
2020-06-28 17:36:41 +01:00
|
|
|
// In the case of a trait predicate, we can skip the "self" type.
|
2023-02-15 17:39:43 +00:00
|
|
|
data.trait_ref.substs[1..].iter().any(has_self_ty).then_some(sp)
|
2020-06-28 17:36:41 +01:00
|
|
|
}
|
2023-06-22 18:17:13 +00:00
|
|
|
ty::ClauseKind::Projection(ref data) => {
|
2020-06-28 17:36:41 +01:00
|
|
|
// And similarly for projections. This should be redundant with
|
|
|
|
// the previous check because any projection should have a
|
|
|
|
// matching `Trait` predicate with the same inputs, but we do
|
|
|
|
// the check to be safe.
|
|
|
|
//
|
|
|
|
// It's also won't be redundant if we allow type-generic associated
|
|
|
|
// types for trait objects.
|
|
|
|
//
|
|
|
|
// Note that we *do* allow projection *outputs* to contain
|
|
|
|
// `self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
|
|
|
|
// we just require the user to specify *both* outputs
|
|
|
|
// in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
|
|
|
|
//
|
|
|
|
// This is ALT2 in issue #56288, see that for discussion of the
|
|
|
|
// possible alternatives.
|
2023-02-15 17:39:43 +00:00
|
|
|
data.projection_ty.substs[1..].iter().any(has_self_ty).then_some(sp)
|
2020-06-28 17:36:41 +01:00
|
|
|
}
|
2023-06-22 18:17:13 +00:00
|
|
|
ty::ClauseKind::ConstArgHasType(_ct, ty) => has_self_ty(&ty.into()).then_some(sp),
|
2023-02-10 13:43:29 +00:00
|
|
|
|
2023-06-22 18:17:13 +00:00
|
|
|
ty::ClauseKind::WellFormed(..)
|
|
|
|
| ty::ClauseKind::TypeOutlives(..)
|
|
|
|
| ty::ClauseKind::RegionOutlives(..)
|
2023-02-10 13:43:29 +00:00
|
|
|
// FIXME(generic_const_exprs): this can mention `Self`
|
2023-06-22 17:43:19 +00:00
|
|
|
| ty::ClauseKind::ConstEvaluatable(..)
|
2023-07-03 15:27:41 +00:00
|
|
|
=> None,
|
2020-06-28 17:36:41 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-07 05:51:43 +00:00
|
|
|
fn super_predicates_have_non_lifetime_binders(
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
trait_def_id: DefId,
|
|
|
|
) -> SmallVec<[Span; 1]> {
|
|
|
|
// If non_lifetime_binders is disabled, then exit early
|
|
|
|
if !tcx.features().non_lifetime_binders {
|
|
|
|
return SmallVec::new();
|
|
|
|
}
|
|
|
|
tcx.super_predicates_of(trait_def_id)
|
|
|
|
.predicates
|
|
|
|
.iter()
|
|
|
|
.filter_map(|(pred, span)| pred.has_non_region_late_bound().then_some(*span))
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
|
2023-06-16 12:38:57 +00:00
|
|
|
tcx.generics_require_sized_self(trait_def_id)
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
|
2022-02-19 00:48:31 +01:00
|
|
|
let Some(sized_def_id) = tcx.lang_items().sized_trait() else {
|
|
|
|
return false; /* No Sized trait, can't require it! */
|
2020-01-05 15:48:46 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// Search for a predicate like `Self : Sized` amongst the trait bounds.
|
|
|
|
let predicates = tcx.predicates_of(def_id);
|
|
|
|
let predicates = predicates.instantiate_identity(tcx).predicates;
|
2023-04-06 23:11:19 +00:00
|
|
|
elaborate(tcx, predicates.into_iter()).any(|pred| match pred.kind().skip_binder() {
|
2023-06-22 18:17:13 +00:00
|
|
|
ty::ClauseKind::Trait(ref trait_pred) => {
|
2023-03-26 20:33:54 +00:00
|
|
|
trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
|
2016-05-11 08:48:12 +03:00
|
|
|
}
|
2023-06-22 18:17:13 +00:00
|
|
|
ty::ClauseKind::RegionOutlives(_)
|
|
|
|
| ty::ClauseKind::TypeOutlives(_)
|
|
|
|
| ty::ClauseKind::Projection(_)
|
|
|
|
| ty::ClauseKind::ConstArgHasType(_, _)
|
|
|
|
| ty::ClauseKind::WellFormed(_)
|
2023-07-03 15:27:41 +00:00
|
|
|
| ty::ClauseKind::ConstEvaluatable(_) => false,
|
2020-01-05 15:48:46 +01:00
|
|
|
})
|
|
|
|
}
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2023-06-05 15:32:23 +00:00
|
|
|
/// Returns `Some(_)` if this item makes the containing trait not object safe.
|
|
|
|
#[instrument(level = "debug", skip(tcx), ret)]
|
|
|
|
fn object_safety_violation_for_assoc_item(
|
2020-01-05 15:48:46 +01:00
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
trait_def_id: DefId,
|
2023-06-05 15:32:23 +00:00
|
|
|
item: ty::AssocItem,
|
|
|
|
) -> Option<ObjectSafetyViolation> {
|
|
|
|
// Any item that has a `Self : Sized` requisite is otherwise
|
2020-01-05 15:48:46 +01:00
|
|
|
// exempt from the regulations.
|
2023-06-16 12:38:57 +00:00
|
|
|
if tcx.generics_require_sized_self(item.def_id) {
|
2020-01-05 15:48:46 +01:00
|
|
|
return None;
|
2016-05-11 08:48:12 +03:00
|
|
|
}
|
2015-03-18 15:26:38 -04:00
|
|
|
|
2023-06-05 15:32:23 +00:00
|
|
|
match item.kind {
|
|
|
|
// Associated consts are never object safe, as they can't have `where` bounds yet at all,
|
|
|
|
// and associated const bounds in trait objects aren't a thing yet either.
|
|
|
|
ty::AssocKind::Const => {
|
|
|
|
Some(ObjectSafetyViolation::AssocConst(item.name, item.ident(tcx).span))
|
|
|
|
}
|
|
|
|
ty::AssocKind::Fn => virtual_call_violation_for_method(tcx, trait_def_id, item).map(|v| {
|
|
|
|
let node = tcx.hir().get_if_local(item.def_id);
|
|
|
|
// Get an accurate span depending on the violation.
|
|
|
|
let span = match (&v, node) {
|
|
|
|
(MethodViolationCode::ReferencesSelfInput(Some(span)), _) => *span,
|
|
|
|
(MethodViolationCode::UndispatchableReceiver(Some(span)), _) => *span,
|
|
|
|
(MethodViolationCode::ReferencesImplTraitInTrait(span), _) => *span,
|
|
|
|
(MethodViolationCode::ReferencesSelfOutput, Some(node)) => {
|
|
|
|
node.fn_decl().map_or(item.ident(tcx).span, |decl| decl.output.span())
|
|
|
|
}
|
|
|
|
_ => item.ident(tcx).span,
|
|
|
|
};
|
|
|
|
|
|
|
|
ObjectSafetyViolation::Method(item.name, v, span)
|
|
|
|
}),
|
|
|
|
// Associated types can only be object safe if they have `Self: Sized` bounds.
|
|
|
|
ty::AssocKind::Type => {
|
|
|
|
if !tcx.features().generic_associated_types_extended
|
|
|
|
&& !tcx.generics_of(item.def_id).params.is_empty()
|
|
|
|
&& item.opt_rpitit_info.is_none()
|
|
|
|
{
|
|
|
|
Some(ObjectSafetyViolation::GAT(item.name, item.ident(tcx).span))
|
|
|
|
} else {
|
|
|
|
// We will permit associated types if they are explicitly mentioned in the trait object.
|
|
|
|
// We can't check this here, as here we only check if it is guaranteed to not be possible.
|
|
|
|
None
|
2020-01-31 18:48:35 -08:00
|
|
|
}
|
2023-06-05 15:32:23 +00:00
|
|
|
}
|
|
|
|
}
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
/// Returns `Some(_)` if this method cannot be called on a trait
|
|
|
|
/// object; this does not necessarily imply that the enclosing trait
|
|
|
|
/// is not object safe, because the method might have a where clause
|
|
|
|
/// `Self:Sized`.
|
|
|
|
fn virtual_call_violation_for_method<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
trait_def_id: DefId,
|
2023-02-06 08:57:34 +00:00
|
|
|
method: ty::AssocItem,
|
2020-01-05 15:48:46 +01:00
|
|
|
) -> Option<MethodViolationCode> {
|
2023-01-18 16:52:47 -07:00
|
|
|
let sig = tcx.fn_sig(method.def_id).subst_identity();
|
2020-10-15 17:23:45 -07:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
// The method's first parameter must be named `self`
|
2020-04-01 10:09:50 +08:00
|
|
|
if !method.fn_has_self_parameter {
|
2022-06-25 14:59:45 -07:00
|
|
|
let sugg = if let Some(hir::Node::TraitItem(hir::TraitItem {
|
|
|
|
generics,
|
|
|
|
kind: hir::TraitItemKind::Fn(sig, _),
|
|
|
|
..
|
|
|
|
})) = tcx.hir().get_if_local(method.def_id).as_ref()
|
|
|
|
{
|
|
|
|
let sm = tcx.sess.source_map();
|
|
|
|
Some((
|
|
|
|
(
|
|
|
|
format!("&self{}", if sig.decl.inputs.is_empty() { "" } else { ", " }),
|
|
|
|
sm.span_through_char(sig.span, '(').shrink_to_hi(),
|
|
|
|
),
|
|
|
|
(
|
|
|
|
format!("{} Self: Sized", generics.add_where_or_trailing_comma()),
|
|
|
|
generics.tail_span_for_predicate_suggestion(),
|
|
|
|
),
|
|
|
|
))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
return Some(MethodViolationCode::StaticMethod(sugg));
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
2017-11-08 05:27:39 -05:00
|
|
|
|
2022-06-25 14:59:45 -07:00
|
|
|
for (i, &input_ty) in sig.skip_binder().inputs().iter().enumerate().skip(1) {
|
2020-12-16 22:36:14 -05:00
|
|
|
if contains_illegal_self_type_reference(tcx, trait_def_id, sig.rebind(input_ty)) {
|
2022-06-25 14:59:45 -07:00
|
|
|
let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
|
|
|
|
kind: hir::TraitItemKind::Fn(sig, _),
|
|
|
|
..
|
|
|
|
})) = tcx.hir().get_if_local(method.def_id).as_ref()
|
|
|
|
{
|
|
|
|
Some(sig.decl.inputs[i].span)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
return Some(MethodViolationCode::ReferencesSelfInput(span));
|
2014-12-15 21:11:09 -05:00
|
|
|
}
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
2020-12-16 22:36:14 -05:00
|
|
|
if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output()) {
|
2020-01-31 18:48:35 -08:00
|
|
|
return Some(MethodViolationCode::ReferencesSelfOutput);
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
2022-11-19 02:32:55 +00:00
|
|
|
if let Some(code) = contains_illegal_impl_trait_in_trait(tcx, method.def_id, sig.output()) {
|
|
|
|
return Some(code);
|
2022-09-11 09:13:55 +00:00
|
|
|
}
|
2016-05-11 08:48:12 +03:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
// We can't monomorphize things like `fn foo<A>(...)`.
|
|
|
|
let own_counts = tcx.generics_of(method.def_id).own_counts();
|
|
|
|
if own_counts.types + own_counts.consts != 0 {
|
|
|
|
return Some(MethodViolationCode::Generic);
|
|
|
|
}
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2021-04-19 15:40:05 -05:00
|
|
|
let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
// Until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
|
|
|
|
// However, this is already considered object-safe. We allow it as a special case here.
|
|
|
|
// FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
|
|
|
|
// `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
|
|
|
|
if receiver_ty != tcx.types.self_param {
|
|
|
|
if !receiver_is_dispatchable(tcx, method, receiver_ty) {
|
2022-06-25 14:59:45 -07:00
|
|
|
let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
|
|
|
|
kind: hir::TraitItemKind::Fn(sig, _),
|
|
|
|
..
|
|
|
|
})) = tcx.hir().get_if_local(method.def_id).as_ref()
|
|
|
|
{
|
|
|
|
Some(sig.decl.inputs[0].span)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
return Some(MethodViolationCode::UndispatchableReceiver(span));
|
2020-01-05 15:48:46 +01:00
|
|
|
} else {
|
|
|
|
// Do sanity check to make sure the receiver actually has the layout of a pointer.
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2020-03-31 18:16:47 +02:00
|
|
|
use rustc_target::abi::Abi;
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
let param_env = tcx.param_env(method.def_id);
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2021-08-29 11:06:55 +02:00
|
|
|
let abi_of_ty = |ty: Ty<'tcx>| -> Option<Abi> {
|
2020-01-05 15:48:46 +01:00
|
|
|
match tcx.layout_of(param_env.and(ty)) {
|
2021-08-29 11:06:55 +02:00
|
|
|
Ok(layout) => Some(layout.abi),
|
2020-10-26 16:56:22 -07:00
|
|
|
Err(err) => {
|
|
|
|
// #78372
|
|
|
|
tcx.sess.delay_span_bug(
|
|
|
|
tcx.def_span(method.def_id),
|
2023-05-17 10:30:14 +00:00
|
|
|
format!("error: {err}\n while computing layout for type {ty:?}"),
|
2020-10-26 16:56:22 -07:00
|
|
|
);
|
|
|
|
None
|
|
|
|
}
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// e.g., `Rc<()>`
|
|
|
|
let unit_receiver_ty =
|
|
|
|
receiver_for_self_ty(tcx, receiver_ty, tcx.mk_unit(), method.def_id);
|
|
|
|
|
|
|
|
match abi_of_ty(unit_receiver_ty) {
|
2020-10-26 16:56:22 -07:00
|
|
|
Some(Abi::Scalar(..)) => (),
|
2020-01-05 15:48:46 +01:00
|
|
|
abi => {
|
|
|
|
tcx.sess.delay_span_bug(
|
|
|
|
tcx.def_span(method.def_id),
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
format!(
|
2020-01-05 15:48:46 +01:00
|
|
|
"receiver when `Self = ()` should have a Scalar ABI; found {:?}",
|
|
|
|
abi
|
|
|
|
),
|
|
|
|
);
|
2018-10-08 20:40:57 -04:00
|
|
|
}
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2023-02-13 13:03:45 +11:00
|
|
|
let trait_object_ty = object_ty_for_trait(tcx, trait_def_id, tcx.lifetimes.re_static);
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
// e.g., `Rc<dyn Trait>`
|
|
|
|
let trait_object_receiver =
|
|
|
|
receiver_for_self_ty(tcx, receiver_ty, trait_object_ty, method.def_id);
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
match abi_of_ty(trait_object_receiver) {
|
2020-10-26 16:56:22 -07:00
|
|
|
Some(Abi::ScalarPair(..)) => (),
|
2020-01-05 15:48:46 +01:00
|
|
|
abi => {
|
|
|
|
tcx.sess.delay_span_bug(
|
|
|
|
tcx.def_span(method.def_id),
|
Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-04-20 13:26:58 +10:00
|
|
|
format!(
|
2020-10-26 16:56:22 -07:00
|
|
|
"receiver when `Self = {}` should have a ScalarPair ABI; found {:?}",
|
2020-01-05 15:48:46 +01:00
|
|
|
trait_object_ty, abi
|
|
|
|
),
|
|
|
|
);
|
2018-10-08 20:40:57 -04:00
|
|
|
}
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
}
|
|
|
|
}
|
2014-12-15 21:11:09 -05:00
|
|
|
}
|
|
|
|
|
2022-10-07 02:29:19 +00:00
|
|
|
// NOTE: This check happens last, because it results in a lint, and not a
|
|
|
|
// hard error.
|
2023-01-19 01:24:45 -08:00
|
|
|
if tcx.predicates_of(method.def_id).predicates.iter().any(|&(pred, span)| {
|
|
|
|
// dyn Trait is okay:
|
|
|
|
//
|
|
|
|
// trait Trait {
|
|
|
|
// fn f(&self) where Self: 'static;
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// because a trait object can't claim to live longer than the concrete
|
|
|
|
// type. If the lifetime bound holds on dyn Trait then it's guaranteed
|
|
|
|
// to hold as well on the concrete type.
|
2023-06-22 18:17:13 +00:00
|
|
|
if pred.as_type_outlives_clause().is_some() {
|
2023-01-19 01:24:45 -08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// dyn Trait is okay:
|
|
|
|
//
|
|
|
|
// auto trait AutoTrait {}
|
|
|
|
//
|
|
|
|
// trait Trait {
|
|
|
|
// fn f(&self) where Self: AutoTrait;
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// because `impl AutoTrait for dyn Trait` is disallowed by coherence.
|
|
|
|
// Traits with a default impl are implemented for a trait object if and
|
|
|
|
// only if the autotrait is one of the trait object's trait bounds, like
|
|
|
|
// in `dyn Trait + AutoTrait`. This guarantees that trait objects only
|
|
|
|
// implement auto traits if the underlying type does as well.
|
2023-06-22 18:17:13 +00:00
|
|
|
if let ty::ClauseKind::Trait(ty::TraitPredicate {
|
2023-01-19 01:24:45 -08:00
|
|
|
trait_ref: pred_trait_ref,
|
|
|
|
constness: ty::BoundConstness::NotConst,
|
|
|
|
polarity: ty::ImplPolarity::Positive,
|
2023-06-22 18:17:13 +00:00
|
|
|
}) = pred.kind().skip_binder()
|
2023-01-19 01:24:45 -08:00
|
|
|
&& pred_trait_ref.self_ty() == tcx.types.self_param
|
|
|
|
&& tcx.trait_is_auto(pred_trait_ref.def_id)
|
|
|
|
{
|
|
|
|
// Consider bounds like `Self: Bound<Self>`. Auto traits are not
|
|
|
|
// allowed to have generic parameters so `auto trait Bound<T> {}`
|
|
|
|
// would already have reported an error at the definition of the
|
|
|
|
// auto trait.
|
|
|
|
if pred_trait_ref.substs.len() != 1 {
|
|
|
|
tcx.sess.diagnostic().delay_span_bug(
|
|
|
|
span,
|
|
|
|
"auto traits cannot have generic parameters",
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2023-02-15 23:18:40 +01:00
|
|
|
contains_illegal_self_type_reference(tcx, trait_def_id, pred)
|
2023-01-19 01:24:45 -08:00
|
|
|
}) {
|
2022-10-07 02:29:19 +00:00
|
|
|
return Some(MethodViolationCode::WhereClauseReferencesSelf);
|
|
|
|
}
|
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
None
|
|
|
|
}
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
/// Performs a type substitution to produce the version of `receiver_ty` when `Self = self_ty`.
|
|
|
|
/// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
|
|
|
|
fn receiver_for_self_ty<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
receiver_ty: Ty<'tcx>,
|
|
|
|
self_ty: Ty<'tcx>,
|
|
|
|
method_def_id: DefId,
|
|
|
|
) -> Ty<'tcx> {
|
|
|
|
debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
|
|
|
|
let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| {
|
|
|
|
if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
|
|
|
|
});
|
|
|
|
|
2023-05-29 13:46:10 +02:00
|
|
|
let result = EarlyBinder::bind(receiver_ty).subst(tcx, substs);
|
2020-01-05 15:48:46 +01:00
|
|
|
debug!(
|
|
|
|
"receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
|
|
|
|
receiver_ty, self_ty, method_def_id, result
|
|
|
|
);
|
|
|
|
result
|
|
|
|
}
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
/// Creates the object type for the current trait. For example,
|
|
|
|
/// if the current trait is `Deref`, then this will be
|
|
|
|
/// `dyn Deref<Target = Self::Target> + 'static`.
|
2022-10-09 13:34:42 +00:00
|
|
|
#[instrument(level = "trace", skip(tcx), ret)]
|
2020-01-05 15:48:46 +01:00
|
|
|
fn object_ty_for_trait<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
trait_def_id: DefId,
|
|
|
|
lifetime: ty::Region<'tcx>,
|
|
|
|
) -> Ty<'tcx> {
|
|
|
|
let trait_ref = ty::TraitRef::identity(tcx, trait_def_id);
|
2022-10-09 13:34:42 +00:00
|
|
|
debug!(?trait_ref);
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2023-04-26 11:59:51 +00:00
|
|
|
let trait_predicate = ty::Binder::dummy(ty::ExistentialPredicate::Trait(
|
|
|
|
ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref),
|
|
|
|
));
|
2022-10-09 13:34:42 +00:00
|
|
|
debug!(?trait_predicate);
|
2018-10-08 20:40:57 -04:00
|
|
|
|
2023-04-06 23:24:03 +00:00
|
|
|
let pred: ty::Predicate<'tcx> = trait_ref.to_predicate(tcx);
|
|
|
|
let mut elaborated_predicates: Vec<_> = elaborate(tcx, [pred])
|
2023-03-26 20:33:54 +00:00
|
|
|
.filter_map(|pred| {
|
|
|
|
debug!(?pred);
|
|
|
|
let pred = pred.to_opt_poly_projection_pred()?;
|
2022-10-12 05:10:29 +00:00
|
|
|
Some(pred.map_bound(|p| {
|
2023-02-08 02:34:23 +00:00
|
|
|
ty::ExistentialPredicate::Projection(ty::ExistentialProjection::erase_self_ty(
|
|
|
|
tcx, p,
|
|
|
|
))
|
2022-10-12 05:10:29 +00:00
|
|
|
}))
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
// NOTE: Since #37965, the existential predicates list has depended on the
|
|
|
|
// list of predicates to be sorted. This is mostly to enforce that the primary
|
|
|
|
// predicate comes first.
|
|
|
|
elaborated_predicates.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
|
|
|
|
elaborated_predicates.dedup();
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
|
2023-02-17 14:33:08 +11:00
|
|
|
let existential_predicates = tcx.mk_poly_existential_predicates_from_iter(
|
|
|
|
iter::once(trait_predicate).chain(elaborated_predicates),
|
|
|
|
);
|
2022-10-09 13:34:42 +00:00
|
|
|
debug!(?existential_predicates);
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
|
2022-10-09 13:34:42 +00:00
|
|
|
tcx.mk_dynamic(existential_predicates, lifetime, ty::Dyn)
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
/// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
|
|
|
|
/// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
|
|
|
|
/// in the following way:
|
|
|
|
/// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
|
|
|
|
/// - require the following bound:
|
|
|
|
///
|
2022-04-15 15:04:34 -07:00
|
|
|
/// ```ignore (not-rust)
|
2020-01-05 15:48:46 +01:00
|
|
|
/// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
|
|
|
|
/// (substitution notation).
|
|
|
|
///
|
|
|
|
/// Some examples of receiver types and their required obligation:
|
|
|
|
/// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
|
|
|
|
/// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
|
|
|
|
/// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
|
|
|
|
///
|
|
|
|
/// The only case where the receiver is not dispatchable, but is still a valid receiver
|
|
|
|
/// type (just not object-safe), is when there is more than one level of pointer indirection.
|
|
|
|
/// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
|
|
|
|
/// is no way, or at least no inexpensive way, to coerce the receiver from the version where
|
|
|
|
/// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
|
|
|
|
/// contained by the trait object, because the object that needs to be coerced is behind
|
|
|
|
/// a pointer.
|
|
|
|
///
|
|
|
|
/// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result
|
|
|
|
/// in a new check that `Trait` is object safe, creating a cycle (until object_safe_for_dispatch
|
2020-11-05 14:33:23 +01:00
|
|
|
/// is stabilized, see tracking issue <https://github.com/rust-lang/rust/issues/43561>).
|
2020-01-05 15:48:46 +01:00
|
|
|
/// Instead, we fudge a little by introducing a new type parameter `U` such that
|
|
|
|
/// `Self: Unsize<U>` and `U: Trait + ?Sized`, and use `U` in place of `dyn Trait`.
|
|
|
|
/// Written as a chalk-style query:
|
2022-04-15 15:04:34 -07:00
|
|
|
/// ```ignore (not-rust)
|
|
|
|
/// forall (U: Trait + ?Sized) {
|
|
|
|
/// if (Self: Unsize<U>) {
|
|
|
|
/// Receiver: DispatchFromDyn<Receiver[Self => U]>
|
2020-01-05 15:48:46 +01:00
|
|
|
/// }
|
2022-04-15 15:04:34 -07:00
|
|
|
/// }
|
|
|
|
/// ```
|
2020-01-05 15:48:46 +01:00
|
|
|
/// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
|
|
|
|
/// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
|
|
|
|
/// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
|
|
|
|
//
|
|
|
|
// FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
|
|
|
|
// fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
|
|
|
|
// `self: Wrapper<Self>`.
|
|
|
|
#[allow(dead_code)]
|
|
|
|
fn receiver_is_dispatchable<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
2023-02-06 08:57:34 +00:00
|
|
|
method: ty::AssocItem,
|
2020-01-05 15:48:46 +01:00
|
|
|
receiver_ty: Ty<'tcx>,
|
|
|
|
) -> bool {
|
|
|
|
debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
|
|
|
|
|
|
|
|
let traits = (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait());
|
2021-10-16 03:45:14 +02:00
|
|
|
let (Some(unsize_did), Some(dispatch_from_dyn_did)) = traits else {
|
2020-01-05 15:48:46 +01:00
|
|
|
debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
|
|
|
// the type `U` in the query
|
2020-03-06 12:13:55 +01:00
|
|
|
// use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
|
2020-01-05 15:48:46 +01:00
|
|
|
// FIXME(mikeyhew) this is a total hack. Once object_safe_for_dispatch is stabilized, we can
|
|
|
|
// replace this with `dyn Trait`
|
|
|
|
let unsized_self_ty: Ty<'tcx> =
|
2020-04-06 23:09:56 +02:00
|
|
|
tcx.mk_ty_param(u32::MAX, Symbol::intern("RustaceansAreAwesome"));
|
2020-01-05 15:48:46 +01:00
|
|
|
|
|
|
|
// `Receiver[Self => U]`
|
|
|
|
let unsized_receiver_ty =
|
|
|
|
receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
|
|
|
|
|
|
|
|
// create a modified param env, with `Self: Unsize<U>` and `U: Trait` added to caller bounds
|
|
|
|
// `U: ?Sized` is already implied here
|
|
|
|
let param_env = {
|
2020-07-02 20:52:40 -04:00
|
|
|
let param_env = tcx.param_env(method.def_id);
|
2020-01-05 15:48:46 +01:00
|
|
|
|
|
|
|
// Self: Unsize<U>
|
2023-04-26 11:48:17 +00:00
|
|
|
let unsize_predicate =
|
|
|
|
ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty])
|
|
|
|
.to_predicate(tcx);
|
2020-01-05 15:48:46 +01:00
|
|
|
|
|
|
|
// U: Trait<Arg1, ..., ArgN>
|
|
|
|
let trait_predicate = {
|
2022-12-13 11:59:15 +00:00
|
|
|
let trait_def_id = method.trait_container(tcx).unwrap();
|
|
|
|
let substs = InternalSubsts::for_item(tcx, trait_def_id, |param, _| {
|
|
|
|
if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }
|
|
|
|
});
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
|
2023-04-25 16:45:08 +00:00
|
|
|
ty::TraitRef::new(tcx, trait_def_id, substs).to_predicate(tcx)
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
};
|
|
|
|
|
2023-02-17 14:33:08 +11:00
|
|
|
let caller_bounds =
|
|
|
|
param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]);
|
Implement the object-safety checks for arbitrary_self_types: part 1
For a trait method to be considered object-safe, the receiver type must
satisfy certain properties: first, we need to be able to get the vtable
to so we can look up the method, and second, we need to convert the
receiver from the version where `Self=dyn Trait`, to the version where
`Self=T`, `T` being some unknown, `Sized` type that implements `Trait`.
To check that the receiver satisfies those properties, we use the
following query:
forall (U) {
if (Self: Unsize<U>) {
Receiver[Self => U]: CoerceSized<Receiver>
}
}
where `Receiver` is the receiver type of the method (e.g. `Rc<Self>`),
and `Receiver[Self => U]` is the receiver type where `Self = U`, e.g.
`Rc<U>`.
forall queries like this aren’t implemented in the trait system yet, so
for now we are using a bit of a hack — see the code for explanation.
2018-09-20 03:12:00 -04:00
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
ty::ParamEnv::new(
|
2023-06-22 18:17:13 +00:00
|
|
|
tcx.mk_clauses_from_iter(caller_bounds),
|
2021-12-12 12:34:46 +08:00
|
|
|
param_env.reveal(),
|
|
|
|
param_env.constness(),
|
|
|
|
)
|
2020-01-05 15:48:46 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// Receiver: DispatchFromDyn<Receiver[Self => U]>
|
|
|
|
let obligation = {
|
2023-04-25 16:45:08 +00:00
|
|
|
let predicate =
|
|
|
|
ty::TraitRef::new(tcx, dispatch_from_dyn_did, [receiver_ty, unsized_receiver_ty]);
|
2020-01-05 15:48:46 +01:00
|
|
|
|
2022-11-09 10:49:28 +00:00
|
|
|
Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate)
|
2020-01-05 15:48:46 +01:00
|
|
|
};
|
2016-05-11 08:48:12 +03:00
|
|
|
|
2020-01-05 15:48:46 +01:00
|
|
|
let infcx = tcx.infer_ctxt().build();
|
|
|
|
// the receiver is dispatchable iff the obligation holds
|
|
|
|
infcx.predicate_must_hold_modulo_regions(&obligation)
|
|
|
|
}
|
|
|
|
|
2023-02-22 02:18:40 +00:00
|
|
|
fn contains_illegal_self_type_reference<'tcx, T: TypeVisitable<TyCtxt<'tcx>>>(
|
2020-01-05 15:48:46 +01:00
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
trait_def_id: DefId,
|
2020-10-25 18:05:37 +01:00
|
|
|
value: T,
|
2020-01-05 15:48:46 +01:00
|
|
|
) -> bool {
|
|
|
|
// This is somewhat subtle. In general, we want to forbid
|
|
|
|
// references to `Self` in the argument and return types,
|
|
|
|
// since the value of `Self` is erased. However, there is one
|
|
|
|
// exception: it is ok to reference `Self` in order to access
|
|
|
|
// an associated type of the current trait, since we retain
|
|
|
|
// the value of those associated types in the object type
|
|
|
|
// itself.
|
|
|
|
//
|
|
|
|
// ```rust
|
|
|
|
// trait SuperTrait {
|
|
|
|
// type X;
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// trait Trait : SuperTrait {
|
|
|
|
// type Y;
|
|
|
|
// fn foo(&self, x: Self) // bad
|
|
|
|
// fn foo(&self) -> Self // bad
|
|
|
|
// fn foo(&self) -> Option<Self> // bad
|
|
|
|
// fn foo(&self) -> Self::Y // OK, desugars to next example
|
|
|
|
// fn foo(&self) -> <Self as Trait>::Y // OK
|
|
|
|
// fn foo(&self) -> Self::X // OK, desugars to next example
|
|
|
|
// fn foo(&self) -> <Self as SuperTrait>::X // OK
|
|
|
|
// }
|
|
|
|
// ```
|
|
|
|
//
|
|
|
|
// However, it is not as simple as allowing `Self` in a projected
|
|
|
|
// type, because there are illegal ways to use `Self` as well:
|
|
|
|
//
|
|
|
|
// ```rust
|
|
|
|
// trait Trait : SuperTrait {
|
|
|
|
// ...
|
|
|
|
// fn foo(&self) -> <Self as SomeOtherTrait>::X;
|
|
|
|
// }
|
|
|
|
// ```
|
|
|
|
//
|
|
|
|
// Here we will not have the type of `X` recorded in the
|
|
|
|
// object type, and we cannot resolve `Self as SomeOtherTrait`
|
|
|
|
// without knowing what `Self` is.
|
|
|
|
|
2020-02-29 10:03:04 +13:00
|
|
|
struct IllegalSelfTypeVisitor<'tcx> {
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
trait_def_id: DefId,
|
2021-01-07 00:41:55 -05:00
|
|
|
supertraits: Option<Vec<DefId>>,
|
2020-02-29 10:03:04 +13:00
|
|
|
}
|
2016-05-11 08:48:12 +03:00
|
|
|
|
2023-02-09 19:38:07 +00:00
|
|
|
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalSelfTypeVisitor<'tcx> {
|
2020-11-14 21:46:39 +01:00
|
|
|
type BreakTy = ();
|
|
|
|
|
2020-11-05 17:30:39 +01:00
|
|
|
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
|
2020-08-03 00:49:11 +02:00
|
|
|
match t.kind() {
|
2020-10-21 14:24:35 +02:00
|
|
|
ty::Param(_) => {
|
|
|
|
if t == self.tcx.types.self_param {
|
2023-01-17 23:17:13 -08:00
|
|
|
ControlFlow::Break(())
|
2020-10-21 14:24:35 +02:00
|
|
|
} else {
|
2023-01-17 23:17:13 -08:00
|
|
|
ControlFlow::Continue(())
|
2020-10-21 14:24:35 +02:00
|
|
|
}
|
|
|
|
}
|
2022-11-26 21:51:55 +00:00
|
|
|
ty::Alias(ty::Projection, ref data)
|
2023-03-08 13:07:20 -03:00
|
|
|
if self.tcx.is_impl_trait_in_trait(data.def_id) =>
|
2022-09-11 09:13:55 +00:00
|
|
|
{
|
|
|
|
// We'll deny these later in their own pass
|
2023-01-17 23:17:13 -08:00
|
|
|
ControlFlow::Continue(())
|
2022-09-11 09:13:55 +00:00
|
|
|
}
|
2022-11-26 21:51:55 +00:00
|
|
|
ty::Alias(ty::Projection, ref data) => {
|
2020-02-29 10:03:04 +13:00
|
|
|
// This is a projected type `<Foo as SomeTrait>::X`.
|
|
|
|
|
|
|
|
// Compute supertraits of current trait lazily.
|
|
|
|
if self.supertraits.is_none() {
|
2023-04-26 11:59:51 +00:00
|
|
|
let trait_ref =
|
|
|
|
ty::Binder::dummy(ty::TraitRef::identity(self.tcx, self.trait_def_id));
|
2021-01-07 00:41:55 -05:00
|
|
|
self.supertraits = Some(
|
|
|
|
traits::supertraits(self.tcx, trait_ref).map(|t| t.def_id()).collect(),
|
|
|
|
);
|
2020-02-29 10:03:04 +13:00
|
|
|
}
|
2014-12-15 21:11:09 -05:00
|
|
|
|
2020-02-29 10:03:04 +13:00
|
|
|
// Determine whether the trait reference `Foo as
|
|
|
|
// SomeTrait` is in fact a supertrait of the
|
|
|
|
// current trait. In that case, this type is
|
|
|
|
// legal, because the type `X` will be specified
|
2022-11-16 20:34:16 +00:00
|
|
|
// in the object type. Note that we can just use
|
2020-02-29 10:03:04 +13:00
|
|
|
// direct equality here because all of these types
|
|
|
|
// are part of the formal parameter listing, and
|
|
|
|
// hence there should be no inference variables.
|
2021-01-07 00:41:55 -05:00
|
|
|
let is_supertrait_of_current_trait = self
|
|
|
|
.supertraits
|
|
|
|
.as_ref()
|
|
|
|
.unwrap()
|
|
|
|
.contains(&data.trait_ref(self.tcx).def_id);
|
2020-02-29 10:03:04 +13:00
|
|
|
|
|
|
|
if is_supertrait_of_current_trait {
|
2023-01-17 23:17:13 -08:00
|
|
|
ControlFlow::Continue(()) // do not walk contained types, do not report error, do collect $200
|
2020-02-29 10:03:04 +13:00
|
|
|
} else {
|
|
|
|
t.super_visit_with(self) // DO walk contained types, POSSIBLY reporting an error
|
|
|
|
}
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
2020-02-29 10:03:04 +13:00
|
|
|
_ => t.super_visit_with(self), // walk contained types, if any
|
2020-03-23 03:57:04 +02:00
|
|
|
}
|
2020-01-05 15:48:46 +01:00
|
|
|
}
|
|
|
|
|
2022-10-19 10:03:23 +02:00
|
|
|
fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
|
2022-11-24 11:09:15 +00:00
|
|
|
// Constants can only influence object safety if they are generic and reference `Self`.
|
2020-10-25 18:05:37 +01:00
|
|
|
// This is only possible for unevaluated constants, so we walk these here.
|
2022-11-24 11:09:15 +00:00
|
|
|
self.tcx.expand_abstract_consts(ct).super_visit_with(self)
|
2020-10-25 18:05:37 +01:00
|
|
|
}
|
2020-03-23 03:57:04 +02:00
|
|
|
}
|
|
|
|
|
2020-10-22 10:20:24 +02:00
|
|
|
value
|
|
|
|
.visit_with(&mut IllegalSelfTypeVisitor { tcx, trait_def_id, supertraits: None })
|
|
|
|
.is_break()
|
2016-03-17 00:15:31 +02:00
|
|
|
}
|
2017-05-11 16:01:19 +02:00
|
|
|
|
2022-09-11 09:13:55 +00:00
|
|
|
pub fn contains_illegal_impl_trait_in_trait<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
2022-11-19 02:32:55 +00:00
|
|
|
fn_def_id: DefId,
|
2022-09-11 09:13:55 +00:00
|
|
|
ty: ty::Binder<'tcx, Ty<'tcx>>,
|
2022-11-19 02:32:55 +00:00
|
|
|
) -> Option<MethodViolationCode> {
|
|
|
|
// This would be caught below, but rendering the error as a separate
|
|
|
|
// `async-specific` message is better.
|
|
|
|
if tcx.asyncness(fn_def_id).is_async() {
|
|
|
|
return Some(MethodViolationCode::AsyncFn);
|
|
|
|
}
|
|
|
|
|
2022-09-11 09:13:55 +00:00
|
|
|
// FIXME(RPITIT): Perhaps we should use a visitor here?
|
2022-11-19 02:32:55 +00:00
|
|
|
ty.skip_binder().walk().find_map(|arg| {
|
2022-09-11 09:13:55 +00:00
|
|
|
if let ty::GenericArgKind::Type(ty) = arg.unpack()
|
2022-11-26 21:51:55 +00:00
|
|
|
&& let ty::Alias(ty::Projection, proj) = ty.kind()
|
2023-03-08 13:07:20 -03:00
|
|
|
&& tcx.is_impl_trait_in_trait(proj.def_id)
|
2022-09-11 09:13:55 +00:00
|
|
|
{
|
2022-11-26 21:21:20 +00:00
|
|
|
Some(MethodViolationCode::ReferencesImplTraitInTrait(tcx.def_span(proj.def_id)))
|
2022-09-11 09:13:55 +00:00
|
|
|
} else {
|
2022-11-19 02:32:55 +00:00
|
|
|
None
|
2022-09-11 09:13:55 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-05-15 06:24:45 +02:00
|
|
|
pub fn provide(providers: &mut Providers) {
|
2023-06-05 15:57:21 +00:00
|
|
|
*providers = Providers {
|
|
|
|
object_safety_violations,
|
|
|
|
check_is_object_safe,
|
|
|
|
generics_require_sized_self,
|
|
|
|
..*providers
|
|
|
|
};
|
2017-05-11 16:01:19 +02:00
|
|
|
}
|