Skip to content

Commit

Permalink
Forbid static methods in object safe traits
Browse files Browse the repository at this point in the history
Closes rust-lang#19949 and rust-lang/rfcs#428

[breaking change]

If you have traits used with objects with static methods, you'll need to move
the static methods to a different trait.
  • Loading branch information
nrc committed Dec 30, 2014
1 parent fea5aa6 commit cd31e6f
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/librustc_typeck/check/vtable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,13 @@ fn check_object_safety_inner<'tcx>(tcx: &ty::ctxt<'tcx>,
}
}

/// Returns a vec of error messages. If hte vec is empty - no errors!
/// Returns a vec of error messages. If the vec is empty - no errors!
///
/// There are some limitations to calling functions through an object, because (a) the self
/// type is not known (that's the whole point of a trait instance, after all, to obscure the
/// self type) and (b) the call must go through a vtable and hence cannot be monomorphized.
/// self type), (b) the call must go through a vtable and hence cannot be monomorphized and
/// (c) the trait contains static methods which can't be called because we don't know the
/// concrete type.
fn check_object_safety_of_method<'tcx>(tcx: &ty::ctxt<'tcx>,
method: &ty::Method<'tcx>)
-> Vec<String> {
Expand All @@ -185,9 +187,11 @@ fn check_object_safety_inner<'tcx>(tcx: &ty::ctxt<'tcx>,
}

ty::StaticExplicitSelfCategory => {
// Static methods are always object-safe since they
// can't be called through a trait object
return msgs
// Static methods are never object safe (reason (c)).
msgs.push(format!("cannot call a static method (`{}`) \
through a trait object",
method_name));
return msgs;
}
ty::ByReferenceExplicitSelfCategory(..) |
ty::ByBoxExplicitSelfCategory => {}
Expand Down

0 comments on commit cd31e6f

Please sign in to comment.