use alloc::string::String;
use core::fmt;
use core::mem;
use core::mem::ManuallyDrop;
use core::ptr::NonNull;
use std::error::Error;
use crate::rc::{Id, Owned, Ownership};
use crate::runtime::{Class, Imp, Object, Sel};
use crate::{Encode, EncodeArguments, RefEncode};
#[cfg(feature = "catch_all")]
unsafe fn conditional_try<R: Encode>(f: impl FnOnce() -> R) -> Result<R, MessageError> {
use alloc::borrow::ToOwned;
unsafe { crate::exception::catch(f) }.map_err(|exception| {
if let Some(exception) = exception {
MessageError(alloc::format!("Uncaught exception {:?}", exception))
} else {
MessageError("Uncaught exception nil".to_owned())
}
})
}
#[cfg(not(feature = "catch_all"))]
#[inline(always)]
unsafe fn conditional_try<R: Encode>(f: impl FnOnce() -> R) -> Result<R, MessageError> {
Ok(f())
}
#[cfg(feature = "malloc")]
mod verify;
#[cfg(feature = "apple")]
#[path = "apple/mod.rs"]
mod platform;
#[cfg(feature = "gnustep-1-7")]
#[path = "gnustep.rs"]
mod platform;
use self::platform::{send_super_unverified, send_unverified};
#[cfg(feature = "malloc")]
use self::verify::{verify_message_signature, VerificationError};
pub unsafe trait Message: RefEncode {}
unsafe impl Message for Object {}
pub(crate) mod private {
use super::*;
pub trait Sealed {}
impl<T: Message + ?Sized> Sealed for *const T {}
impl<T: Message + ?Sized> Sealed for *mut T {}
impl<T: Message + ?Sized> Sealed for NonNull<T> {}
impl<'a, T: Message + ?Sized> Sealed for &'a T {}
impl<'a, T: Message + ?Sized> Sealed for &'a mut T {}
impl<'a, T: Message + ?Sized, O: Ownership> Sealed for &'a Id<T, O> {}
impl<'a, T: Message + ?Sized> Sealed for &'a mut Id<T, Owned> {}
impl<T: Message + ?Sized, O: Ownership> Sealed for ManuallyDrop<Id<T, O>> {}
impl Sealed for *const Class {}
impl<'a> Sealed for &'a Class {}
}
pub unsafe trait MessageReceiver: private::Sealed + Sized {
#[doc(hidden)]
fn __as_raw_receiver(self) -> *mut Object;
#[cfg_attr(not(feature = "verify_message"), inline(always))]
unsafe fn send_message<A, R>(self, sel: Sel, args: A) -> Result<R, MessageError>
where
A: MessageArguments,
R: Encode,
{
let this = self.__as_raw_receiver();
#[cfg(feature = "verify_message")]
{
let this = unsafe { this.as_ref() };
let cls = if let Some(this) = this {
this.class()
} else {
return Err(VerificationError::NilReceiver(sel).into());
};
verify_message_signature::<A, R>(cls, sel)?;
}
unsafe { send_unverified(this, sel, args) }
}
#[cfg_attr(not(feature = "verify_message"), inline(always))]
unsafe fn send_super_message<A, R>(
self,
superclass: &Class,
sel: Sel,
args: A,
) -> Result<R, MessageError>
where
A: MessageArguments,
R: Encode,
{
let this = self.__as_raw_receiver();
#[cfg(feature = "verify_message")]
{
if this.is_null() {
return Err(VerificationError::NilReceiver(sel).into());
}
verify_message_signature::<A, R>(superclass, sel)?;
}
unsafe { send_super_unverified(this, superclass, sel, args) }
}
#[cfg(feature = "malloc")]
fn verify_message<A, R>(self, sel: Sel) -> Result<(), MessageError>
where
A: EncodeArguments,
R: Encode,
{
let obj = unsafe { self.__as_raw_receiver().as_ref().unwrap() };
verify_message_signature::<A, R>(obj.class(), sel).map_err(MessageError::from)
}
}
unsafe impl<T: Message + ?Sized> MessageReceiver for *const T {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
self as *mut T as *mut Object
}
}
unsafe impl<T: Message + ?Sized> MessageReceiver for *mut T {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
self.cast()
}
}
unsafe impl<T: Message + ?Sized> MessageReceiver for NonNull<T> {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
self.as_ptr().cast()
}
}
unsafe impl<'a, T: Message + ?Sized> MessageReceiver for &'a T {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
let ptr: *const T = self;
ptr as *mut T as *mut Object
}
}
unsafe impl<'a, T: Message + ?Sized> MessageReceiver for &'a mut T {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
let ptr: *mut T = self;
ptr.cast()
}
}
unsafe impl<'a, T: Message + ?Sized, O: Ownership> MessageReceiver for &'a Id<T, O> {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
Id::as_ptr(self) as *mut T as *mut Object
}
}
unsafe impl<'a, T: Message + ?Sized> MessageReceiver for &'a mut Id<T, Owned> {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
Id::as_mut_ptr(self).cast()
}
}
unsafe impl<T: Message + ?Sized, O: Ownership> MessageReceiver for ManuallyDrop<Id<T, O>> {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
Id::consume_as_ptr(self).cast()
}
}
unsafe impl MessageReceiver for *const Class {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
self as *mut Class as *mut Object
}
}
unsafe impl<'a> MessageReceiver for &'a Class {
#[inline]
fn __as_raw_receiver(self) -> *mut Object {
let ptr: *const Class = self;
ptr as *mut Class as *mut Object
}
}
pub unsafe trait MessageArguments: EncodeArguments {
#[doc(hidden)]
unsafe fn __invoke<R: Encode>(imp: Imp, obj: *mut Object, sel: Sel, args: Self) -> R;
}
macro_rules! message_args_impl {
($($a:ident : $t:ident),*) => (
unsafe impl<$($t: Encode),*> MessageArguments for ($($t,)*) {
#[inline]
unsafe fn __invoke<R: Encode>(imp: Imp, obj: *mut Object, sel: Sel, ($($a,)*): Self) -> R {
let imp: unsafe extern "C" fn(*mut Object, Sel $(, $t)*) -> R = unsafe {
mem::transmute(imp)
};
unsafe { imp(obj, sel $(, $a)*) }
}
}
);
}
message_args_impl!();
message_args_impl!(a: A);
message_args_impl!(a: A, b: B);
message_args_impl!(a: A, b: B, c: C);
message_args_impl!(a: A, b: B, c: C, d: D);
message_args_impl!(a: A, b: B, c: C, d: D, e: E);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J);
message_args_impl!(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K
);
message_args_impl!(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
l: L
);
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct MessageError(String);
impl fmt::Display for MessageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl Error for MessageError {
fn description(&self) -> &str {
&self.0
}
}
#[cfg(feature = "malloc")]
impl<'a> From<VerificationError<'a>> for MessageError {
fn from(err: VerificationError<'_>) -> MessageError {
use alloc::string::ToString;
MessageError(err.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rc::{Id, Owned};
use crate::test_utils;
#[allow(unused)]
fn test_different_receivers(mut obj: Id<Object, Owned>) {
unsafe {
let x = &mut obj;
let _: () = msg_send![x, mutable1];
let _: () = msg_send![&mut *obj, mutable1];
let _: () = msg_send![&mut *obj, mutable2];
let obj: NonNull<Object> = (&mut *obj).into();
let _: () = msg_send![obj, mutable1];
let _: () = msg_send![obj, mutable2];
let obj: *mut Object = obj.as_ptr();
let _: () = msg_send![obj, mutable1];
let _: () = msg_send![obj, mutable2];
}
}
#[test]
fn test_send_message() {
let mut obj = test_utils::custom_object();
let result: u32 = unsafe {
let _: () = msg_send![&mut obj, setFoo: 4u32];
msg_send![&obj, foo]
};
assert_eq!(result, 4);
}
#[test]
fn test_send_message_stret() {
let obj = test_utils::custom_object();
let result: test_utils::CustomStruct = unsafe { msg_send![&obj, customStruct] };
let expected = test_utils::CustomStruct {
a: 1,
b: 2,
c: 3,
d: 4,
};
assert_eq!(result, expected);
}
#[cfg(not(feature = "verify_message"))]
#[test]
fn test_send_message_nil() {
let nil: *mut Object = ::core::ptr::null_mut();
let result: *mut Object = unsafe { msg_send![nil, description] };
assert!(result.is_null());
let result: usize = unsafe { msg_send![nil, hash] };
assert_eq!(result, 0);
#[cfg(target_pointer_width = "16")]
let result: f32 = 0.0;
#[cfg(target_pointer_width = "32")]
let result: f32 = unsafe { msg_send![nil, floatValue] };
#[cfg(target_pointer_width = "64")]
let result: f64 = unsafe { msg_send![nil, doubleValue] };
assert_eq!(result, 0.0);
let result: *mut Object = unsafe { msg_send![nil, multiple: 1u32, arguments: 2i8] };
assert!(result.is_null());
}
#[test]
fn test_send_message_super() {
let mut obj = test_utils::custom_subclass_object();
let superclass = test_utils::custom_class();
unsafe {
let _: () = msg_send![&mut obj, setFoo: 4u32];
let foo: u32 = msg_send![super(&obj, superclass), foo];
assert_eq!(foo, 4);
let foo: u32 = msg_send![&obj, foo];
assert_eq!(foo, 6);
}
}
#[test]
fn test_send_message_manuallydrop() {
let obj = ManuallyDrop::new(test_utils::custom_object());
unsafe {
let _: () = msg_send![obj, release];
};
}
#[test]
#[cfg(feature = "malloc")]
fn test_verify_message() {
let obj = test_utils::custom_object();
assert!(obj.verify_message::<(), u32>(sel!(foo)).is_ok());
assert!(obj.verify_message::<(u32,), ()>(sel!(setFoo:)).is_ok());
assert!(obj.verify_message::<(), u64>(sel!(setFoo:)).is_err());
assert!(obj.verify_message::<(u32,), ()>(sel!(setFoo)).is_err());
}
}