1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use core::mem;
use core::mem::ManuallyDrop;
use core::ptr::NonNull;

use crate::rc::{Id, Owned, Ownership};
use crate::runtime::{Class, Imp, Object, Sel};
use crate::{Encode, EncodeArguments, RefEncode};

#[cfg(feature = "catch-all")]
#[track_caller]
unsafe fn conditional_try<R: Encode>(f: impl FnOnce() -> R) -> R {
    let f = core::panic::AssertUnwindSafe(f);
    match unsafe { crate::exception::catch(f) } {
        Ok(r) => r,
        Err(exception) => {
            if let Some(exception) = exception {
                panic!("uncaught {:?}", exception)
            } else {
                panic!("uncaught exception nil")
            }
        }
    }
}

#[cfg(not(feature = "catch-all"))]
#[inline]
#[track_caller]
unsafe fn conditional_try<R: Encode>(f: impl FnOnce() -> R) -> R {
    f()
}

#[cfg(feature = "verify_message")]
#[track_caller]
fn panic_verify(cls: &Class, sel: Sel, err: crate::VerificationError) -> ! {
    panic!(
        "invalid message send to {}[{:?} {:?}]: {}",
        if cls.is_metaclass() { "+" } else { "-" },
        cls,
        sel,
        err
    )
}

#[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};

/// Types that can be sent Objective-C messages.
///
/// Implementing this provides [`MessageReceiver`] implementations for common
/// pointer types and references to the type, which allows using them as the
/// receiver (first argument) in the [`msg_send!`][`crate::msg_send`] macro.
///
/// This trait also allows the object to be used in [`rc::Id`][`Id`].
///
/// This is a subtrait of [`RefEncode`], meaning the type must also implement
/// that, almost always as [`Encoding::Object`].
///
/// [`Encoding::Object`]: crate::Encoding::Object
///
///
/// # Safety
///
/// The type must represent an Objective-C object, meaning it:
/// - Must be valid to reinterpret as [`runtime::Object`][`Object`].
/// - Must be able to be the receiver of an Objective-C message sent with
///   [`objc_msgSend`] or similar.
/// - Must respond to the standard memory management `retain`, `release` and
///   `autorelease` messages.
///
/// [`objc_msgSend`]: https://developer.apple.com/documentation/objectivec/1456712-objc_msgsend
///
///
/// # Example
///
/// ```
/// use objc2::runtime::Object;
/// use objc2::{Encoding, Message, RefEncode};
///
/// #[repr(C)]
/// struct MyObject {
///     // This has the exact same layout as `Object`
///     inner: Object
/// }
///
/// unsafe impl RefEncode for MyObject {
///     const ENCODING_REF: Encoding<'static> = Encoding::Object;
/// }
///
/// unsafe impl Message for MyObject {}
///
/// // `*mut MyObject` and other pointer/reference types to the object can
/// // now be used in `msg_send!`
/// //
/// // And `Id<MyObject, O>` can now be constructed.
/// ```
pub unsafe trait Message: RefEncode {}

unsafe impl Message for Object {}

// TODO: Make this fully private
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 {}
}

/// Types that can directly be used as the receiver of Objective-C messages.
///
/// Examples include objects, classes, and blocks.
///
/// This is a sealed trait (for now) that is automatically implemented for
/// pointers to types implementing [`Message`], so that code can be generic
/// over the message receiver.
///
/// This is mostly an implementation detail; you'll want to implement
/// [`Message`] for your type instead.
///
/// # Safety
///
/// This is a sealed trait, and should not need to be implemented. Open an
/// issue if you know a use-case where this restrition should be lifted!
pub unsafe trait MessageReceiver: private::Sealed + Sized {
    #[doc(hidden)]
    fn __as_raw_receiver(self) -> *mut Object;

    /// Sends a message to self with the given selector and arguments.
    ///
    /// The correct version of `objc_msgSend` will be chosen based on the
    /// return type. For more information, see the section on "Sending
    /// Messages" in Apple's [documentation][runtime].
    ///
    /// If the selector is known at compile-time, it is recommended to use the
    /// [`msg_send!`][`crate::msg_send`] macro rather than this method.
    ///
    /// [runtime]: https://developer.apple.com/documentation/objectivec/objective-c_runtime?language=objc
    ///
    /// # Safety
    ///
    /// This shares the same safety requirements as [`msg_send!`][`msg_send`].
    ///
    /// The added invariant is that the selector must take the same number of
    /// arguments as is given.
    #[inline]
    #[track_caller]
    unsafe fn send_message<A, R>(self, sel: Sel, args: A) -> R
    where
        A: MessageArguments,
        R: Encode,
    {
        let this = self.__as_raw_receiver();
        // TODO: Always enable this when `debug_assertions` are on.
        #[cfg(feature = "verify_message")]
        {
            // SAFETY: Caller ensures only valid or NULL pointers.
            let this = unsafe { this.as_ref() };
            let cls = if let Some(this) = this {
                this.class()
            } else {
                panic!("messsaging {:?} to nil", sel);
            };

            if let Err(err) = cls.verify_sel::<A, R>(sel) {
                panic_verify(cls, sel, err);
            }
        }
        unsafe { send_unverified(this, sel, args) }
    }

    /// Sends a message to self's superclass with the given selector and
    /// arguments.
    ///
    /// The correct version of `objc_msgSend_super` will be chosen based on the
    /// return type. For more information, see the section on "Sending
    /// Messages" in Apple's [documentation][runtime].
    ///
    /// If the selector is known at compile-time, it is recommended to use the
    /// [`msg_send!(super)`][`crate::msg_send`] macro rather than this method.
    ///
    /// [runtime]: https://developer.apple.com/documentation/objectivec/objective-c_runtime?language=objc
    ///
    /// # Safety
    ///
    /// This shares the same safety requirements as
    /// [`msg_send!(super(...), ...)`][`msg_send`].
    ///
    /// The added invariant is that the selector must take the same number of
    /// arguments as is given.
    #[inline]
    #[track_caller]
    unsafe fn send_super_message<A, R>(self, superclass: &Class, sel: Sel, args: A) -> R
    where
        A: MessageArguments,
        R: Encode,
    {
        let this = self.__as_raw_receiver();
        #[cfg(feature = "verify_message")]
        {
            if this.is_null() {
                panic!("messsaging {:?} to nil", sel);
            }
            if let Err(err) = superclass.verify_sel::<A, R>(sel) {
                panic_verify(superclass, sel, err);
            }
        }
        unsafe { send_super_unverified(this, superclass, sel, args) }
    }
}

// Note that we implement MessageReceiver for unsized types as well, this is
// to support `extern type`s in the future, not because we want to allow DSTs.

unsafe impl<T: Message + ?Sized> MessageReceiver for *const T {
    #[inline]
    fn __as_raw_receiver(self) -> *mut Object {
        (self as *mut T).cast()
    }
}

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).cast()
    }
}

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).cast()
    }
}

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).cast()
    }
}

unsafe impl<'a> MessageReceiver for &'a Class {
    #[inline]
    fn __as_raw_receiver(self) -> *mut Object {
        let ptr: *const Class = self;
        (ptr as *mut Class).cast()
    }
}

/// Types that may be used as the arguments of an Objective-C message.
///
/// This is implemented for tuples of up to 12 arguments, where each argument
/// implements [`Encode`].
///
/// # Safety
///
/// This is a sealed trait, and should not need to be implemented. Open an
/// issue if you know a use-case where this restrition should be lifted!
pub unsafe trait MessageArguments: EncodeArguments {
    /// Invoke an [`Imp`] with the given object, selector, and arguments.
    ///
    /// This method is the primitive used when sending messages and should not
    /// be called directly; instead, use the `msg_send!` macro or, in cases
    /// with a dynamic selector, the [`MessageReceiver::send_message`] method.
    #[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 {
                // The imp must be cast to the appropriate function pointer
                // type before being called; the msgSend functions are not
                // parametric, but instead "trampolines" to the actual
                // method implementations.
                #[cfg(not(feature = "unstable-c-unwind"))]
                let imp: unsafe extern "C" fn(*mut Object, Sel $(, $t)*) -> R = unsafe {
                    mem::transmute(imp)
                };
                #[cfg(feature = "unstable-c-unwind")]
                let imp: unsafe extern "C-unwind" fn(*mut Object, Sel $(, $t)*) -> R = unsafe {
                    mem::transmute(imp)
                };
                // TODO: On x86_64 it would be more efficient to use a GOT
                // entry here (e.g. adding `nonlazybind` in LLVM).
                // Same can be said of e.g. `objc_retain` and `objc_release`.
                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
);

#[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![x, mutable2];
            let _: () = msg_send![&mut *obj, mutable1];
            let _: () = msg_send![&mut *obj, mutable2];
            #[allow(clippy::needless_borrow)]
            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);
    }

    #[test]
    #[cfg_attr(
        feature = "verify_message",
        should_panic = "messsaging description to nil"
    )]
    fn test_send_message_nil() {
        use crate::rc::Shared;

        let nil: *mut Object = ::core::ptr::null_mut();

        // This result should not be relied on
        let result: Option<Id<Object, Shared>> = unsafe { msg_send_id![nil, description] };
        assert!(result.is_none());

        // This result should not be relied on
        let result: usize = unsafe { msg_send![nil, hash] };
        assert_eq!(result, 0);

        // This result should not be relied on
        #[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);

        // This result should not be relied on
        let result: Option<Id<Object, Shared>> =
            unsafe { msg_send_id![nil, multiple: 1u32, arguments: 2i8] };
        assert!(result.is_none());

        // This result should not be relied on
        let result: Option<Id<Object, Shared>> = unsafe { msg_send_id![None, init] };
        assert!(result.is_none());
    }

    #[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);

            // The subclass is overriden to return foo + 2
            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];
        };
        // `obj` is consumed, can't use here
    }
}