use std::iter::{self};
use syntax::ast::{self};
use syntax::symbol::InternedString;
-use syntax_pos::Span;
+use syntax_pos::{Span, DUMMY_SP};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum ObjectSafetyViolation {
SupertraitSelf,
/// Method has something illegal.
- Method(ast::Name, MethodViolationCode),
+ Method(ast::Name, MethodViolationCode, Span),
/// Associated const.
- AssocConst(ast::Name),
+ AssocConst(ast::Name, Span),
}
impl ObjectSafetyViolation {
ObjectSafetyViolation::SupertraitSelf =>
"the trait cannot use `Self` as a type parameter \
in the supertraits or where-clauses".into(),
- ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod) =>
- format!("method `{}` has no receiver", name).into(),
- ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf) =>
- format!("method `{}` references the `Self` type \
- in its arguments or return type", name).into(),
- ObjectSafetyViolation::Method(name,
- MethodViolationCode::WhereClauseReferencesSelf(_)) =>
- format!("method `{}` references the `Self` type in where clauses", name).into(),
- ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
+ ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod, _) =>
+ format!("associated function `{}` has no `self` parameter", name).into(),
+ ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelf, _) => format!(
+ "method `{}` references the `Self` type in its parameters or return type",
+ name,
+ ).into(),
+ ObjectSafetyViolation::Method(
+ name,
+ MethodViolationCode::WhereClauseReferencesSelf,
+ _,
+ ) => format!("method `{}` references the `Self` type in where clauses", name).into(),
+ ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) =>
format!("method `{}` has generic type parameters", name).into(),
- ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver) =>
- format!("method `{}`'s receiver cannot be dispatched on", name).into(),
- ObjectSafetyViolation::AssocConst(name) =>
+ ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) =>
+ format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(),
+ ObjectSafetyViolation::AssocConst(name, _) =>
format!("the trait cannot contain associated consts like `{}`", name).into(),
}
}
+
+ pub fn span(&self) -> Option<Span> {
+ // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
+ // diagnostics use a `note` instead of a `span_label`.
+ match *self {
+ ObjectSafetyViolation::AssocConst(_, span) |
+ ObjectSafetyViolation::Method(_, _, span) if span != DUMMY_SP => Some(span),
+ _ => None,
+ }
+ }
}
/// Reasons a method might not be object-safe.
ReferencesSelf,
/// e.g., `fn foo(&self) where Self: Clone`
- WhereClauseReferencesSelf(Span),
+ WhereClauseReferencesSelf,
/// e.g., `fn foo<A>()`
Generic,
/// 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(self, trait_def_id: DefId)
- -> Vec<ObjectSafetyViolation>
- {
+ pub fn astconv_object_safety_violations(
+ self,
+ trait_def_id: DefId,
+ ) -> Vec<ObjectSafetyViolation> {
+ debug_assert!(self.generics_of(trait_def_id).has_self);
let violations = traits::supertrait_def_ids(self, trait_def_id)
.filter(|&def_id| self.predicates_reference_self(def_id, true))
.map(|_| ObjectSafetyViolation::SupertraitSelf)
pub fn object_safety_violations(self, trait_def_id: DefId)
-> Vec<ObjectSafetyViolation>
{
+ debug_assert!(self.generics_of(trait_def_id).has_self);
debug!("object_safety_violations: {:?}", trait_def_id);
traits::supertrait_def_ids(self, trait_def_id)
.collect()
}
- fn object_safety_violations_for_trait(self, trait_def_id: DefId)
- -> Vec<ObjectSafetyViolation>
- {
+ /// 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`.
+ pub fn is_vtable_safe_method(self, trait_def_id: DefId, method: &ty::AssocItem) -> bool {
+ debug_assert!(self.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.
+ if self.generics_require_sized_self(method.def_id) {
+ return false;
+ }
+
+ match self.virtual_call_violation_for_method(trait_def_id, method) {
+ None | Some(MethodViolationCode::WhereClauseReferencesSelf) => true,
+ Some(_) => false,
+ }
+ }
+
+ fn object_safety_violations_for_trait(self, trait_def_id: DefId) -> Vec<ObjectSafetyViolation> {
// Check methods for violations.
let mut violations: Vec<_> = self.associated_items(trait_def_id)
.filter(|item| item.kind == ty::AssocKind::Method)
.filter_map(|item|
- self.object_safety_violation_for_method(trait_def_id, &item)
- .map(|code| ObjectSafetyViolation::Method(item.ident.name, code))
+ self.object_safety_violation_for_method(trait_def_id, &item).map(|code| {
+ ObjectSafetyViolation::Method(item.ident.name, code, item.ident.span)
+ })
).filter(|violation| {
- if let ObjectSafetyViolation::Method(_,
- MethodViolationCode::WhereClauseReferencesSelf(span)) = violation
- {
+ if let ObjectSafetyViolation::Method(
+ _,
+ MethodViolationCode::WhereClauseReferencesSelf,
+ span,
+ ) = violation {
// 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.
self.lint_node_note(
violations.extend(self.associated_items(trait_def_id)
.filter(|item| item.kind == ty::AssocKind::Const)
- .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name)));
+ .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name, item.ident.span)));
debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
trait_def_id,
fn predicates_reference_self(
self,
trait_def_id: DefId,
- supertraits_only: bool) -> bool
- {
+ supertraits_only: bool,
+ ) -> bool {
let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(self, trait_def_id));
let predicates = if supertraits_only {
self.super_predicates_of(trait_def_id)
} else {
self.predicates_of(trait_def_id)
};
+ let self_ty = self.types.self_param;
+ let has_self_ty = |t: Ty<'tcx>| t.walk().any(|t| t == self_ty);
predicates
.predicates
.iter()
match predicate {
ty::Predicate::Trait(ref data) => {
// In the case of a trait predicate, we can skip the "self" type.
- data.skip_binder().input_types().skip(1).any(|t| t.has_self_ty())
+ data.skip_binder().input_types().skip(1).any(has_self_ty)
}
ty::Predicate::Projection(ref data) => {
// And similarly for projections. This should be redundant with
.trait_ref(self)
.input_types()
.skip(1)
- .any(|t| t.has_self_ty())
+ .any(has_self_ty)
}
ty::Predicate::WellFormed(..) |
ty::Predicate::ObjectSafe(..) |
let predicates = predicates.instantiate_identity(self).predicates;
elaborate_predicates(self, predicates)
.any(|predicate| match predicate {
- ty::Predicate::Trait(ref trait_pred) if trait_pred.def_id() == sized_def_id => {
- trait_pred.skip_binder().self_ty().is_self()
+ ty::Predicate::Trait(ref trait_pred) => {
+ trait_pred.def_id() == sized_def_id
+ && trait_pred.skip_binder().self_ty().is_param(0)
}
ty::Predicate::Projection(..) |
- ty::Predicate::Trait(..) |
ty::Predicate::Subtype(..) |
ty::Predicate::RegionOutlives(..) |
ty::Predicate::WellFormed(..) |
}
/// Returns `Some(_)` if this method makes the containing trait not object safe.
- fn object_safety_violation_for_method(self,
- trait_def_id: DefId,
- method: &ty::AssocItem)
- -> Option<MethodViolationCode>
- {
+ fn object_safety_violation_for_method(
+ self,
+ trait_def_id: DefId,
+ method: &ty::AssocItem,
+ ) -> Option<MethodViolationCode> {
debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method);
// Any method that has a `Self : Sized` requisite is otherwise
// exempt from the regulations.
self.virtual_call_violation_for_method(trait_def_id, method)
}
- /// 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`.
- pub fn is_vtable_safe_method(self,
- trait_def_id: DefId,
- method: &ty::AssocItem)
- -> bool
- {
- debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
- // Any method that has a `Self : Sized` requisite can't be called.
- if self.generics_require_sized_self(method.def_id) {
- return false;
- }
-
- match self.virtual_call_violation_for_method(trait_def_id, method) {
- None | Some(MethodViolationCode::WhereClauseReferencesSelf(_)) => true,
- Some(_) => false,
- }
- }
-
/// 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(self,
- trait_def_id: DefId,
- method: &ty::AssocItem)
- -> Option<MethodViolationCode>
- {
+ fn virtual_call_violation_for_method(
+ self,
+ trait_def_id: DefId,
+ method: &ty::AssocItem,
+ ) -> Option<MethodViolationCode> {
// The method's first parameter must be named `self`
if !method.method_has_self_argument {
return Some(MethodViolationCode::StaticMethod);
.collect::<Vec<_>>()
// Do a shallow visit so that `contains_illegal_self_type_reference`
// may apply it's custom visiting.
- .visit_tys_shallow(|t| self.contains_illegal_self_type_reference(trait_def_id, t)) {
- let span = self.def_span(method.def_id);
- return Some(MethodViolationCode::WhereClauseReferencesSelf(span));
+ .visit_tys_shallow(|t| {
+ self.contains_illegal_self_type_reference(trait_def_id, t)
+ }) {
+ return Some(MethodViolationCode::WhereClauseReferencesSelf);
}
let receiver_ty = self.liberate_late_bound_regions(
&sig.map_bound(|sig| sig.inputs()[0]),
);
- // until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
+ // 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 != self.mk_self_type() {
+ // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
+ if receiver_ty != self.types.self_param {
if !self.receiver_is_dispatchable(method, receiver_ty) {
return Some(MethodViolationCode::UndispatchableReceiver);
} else {
- // sanity check to make sure the receiver actually has the layout of a pointer
+ // Do sanity check to make sure the receiver actually has the layout of a pointer.
use crate::ty::layout::Abi;
match self.layout_of(param_env.and(ty)) {
Ok(layout) => &layout.abi,
Err(err) => bug!(
- "Error: {}\n while computing layout for type {:?}", err, ty
+ "error: {}\n while computing layout for type {:?}", err, ty
)
}
};
- // e.g., Rc<()>
+ // e.g., `Rc<()>`
let unit_receiver_ty = self.receiver_for_self_ty(
receiver_ty, self.mk_unit(), method.def_id
);
self.sess.delay_span_bug(
self.def_span(method.def_id),
&format!(
- "Receiver when Self = () should have a Scalar ABI, found {:?}",
+ "receiver when `Self = ()` should have a Scalar ABI; found {:?}",
abi
),
);
trait_def_id, self.mk_region(ty::ReStatic)
);
- // e.g., Rc<dyn Trait>
+ // e.g., `Rc<dyn Trait>`
let trait_object_receiver = self.receiver_for_self_ty(
receiver_ty, trait_object_ty, method.def_id
);
self.sess.delay_span_bug(
self.def_span(method.def_id),
&format!(
- "Receiver when Self = {} should have a ScalarPair ABI, found {:?}",
+ "receiver when `Self = {}` should have a ScalarPair ABI; \
+ found {:?}",
trait_object_ty, abi
),
);
None
}
- /// Performs a type substitution to produce the version of receiver_ty when `Self = self_ty`
- /// e.g., for receiver_ty = `Rc<Self>` and self_ty = `Foo`, returns `Rc<Foo>`.
+ /// 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(
- self, receiver_ty: Ty<'tcx>, self_ty: Ty<'tcx>, method_def_id: DefId
+ self,
+ 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(self, method_def_id, |param, _| {
// Self: Unsize<U>
let unsize_predicate = ty::TraitRef {
def_id: unsize_did,
- substs: self.mk_substs_trait(self.mk_self_type(), &[unsized_self_ty.into()]),
+ substs: self.mk_substs_trait(self.types.self_param, &[unsized_self_ty.into()]),
}.to_predicate();
// U: Trait<Arg1, ..., ArgN>
})
}
- fn contains_illegal_self_type_reference(self,
- trait_def_id: DefId,
- ty: Ty<'tcx>)
- -> bool
- {
+ fn contains_illegal_self_type_reference(
+ self,
+ trait_def_id: DefId,
+ ty: Ty<'tcx>,
+ ) -> 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
let mut supertraits: Option<Vec<ty::PolyTraitRef<'tcx>>> = None;
let mut error = false;
+ let self_ty = self.types.self_param;
ty.maybe_walk(|ty| {
match ty.sty {
- ty::Param(ref param_ty) => {
- if param_ty.is_self() {
+ ty::Param(_) => {
+ if ty == self_ty {
error = true;
}