objc2 0.3.0-beta.4

Objective-C interface and bindings to the Cocoa Foundation framework
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
/// Create a new type to represent an Objective-C class.
///
/// This is similar to an `@interface` declaration in Objective-C.
///
/// The given struct name should correspond to a valid Objective-C class,
/// whose instances have the encoding [`Encoding::Object`]. (as an example:
/// `NSAutoreleasePool` does not have this!)
///
/// You must specify the superclass of this class, similar to how you would
/// in Objective-C.
///
/// Due to Rust trait limitations, specifying e.g. the superclass `NSData`
/// would not give you easy access to `NSObject`'s functionality. Therefore,
/// you may specify additional parts of the inheritance chain using the
/// `#[inherits(...)]` attribute.
///
/// [`Encoding::Object`]: crate::Encoding::Object
///
///
/// # Specification
///
/// The syntax is similar enough to Rust syntax that if you invoke the macro
/// with parentheses (as opposed to curly brackets), [`rustfmt` will be able to
/// format the contents][rustfmt-macros].
///
/// This creates an opaque struct containing the superclass (which means that
/// auto traits are inherited from the superclass), and implements the
/// following traits for it to allow easier usage as an Objective-C object:
///
/// - [`RefEncode`][crate::RefEncode]
/// - [`Message`][crate::Message]
/// - [`ClassType`][crate::ClassType]
/// - [`Deref<Target = $superclass>`][core::ops::Deref]
/// - [`DerefMut`][core::ops::DerefMut]
/// - [`AsRef<$inheritance_chain>`][AsRef]
/// - [`AsMut<$inheritance_chain>`][AsMut]
/// - [`Borrow<$inheritance_chain>`][core::borrow::Borrow]
/// - [`BorrowMut<$inheritance_chain>`][core::borrow::BorrowMut]
///
/// The macro allows specifying fields on the struct, but _only_ zero-sized
/// types like [`PhantomData`] and [`declare::Ivar`] are allowed here!
///
/// [rustfmt-macros]: https://github.com/rust-lang/rustfmt/discussions/5437
/// [`PhantomData`]: core::marker::PhantomData
/// [`declare::Ivar`]: crate::declare::Ivar
///
///
/// # Safety
///
/// The specified superclass must be correct. The object must also respond to
/// standard memory management messages (this is upheld if [`NSObject`] is
/// part of its inheritance chain).
///
/// [`NSObject`]: crate::runtime::NSObject
///
///
/// # Examples
///
/// Create a new type to represent the `NSFormatter` class.
///
/// ```
/// use objc2::runtime::NSObject;
/// use objc2::rc::{Id, Shared};
/// use objc2::{ClassType, extern_class, msg_send_id};
///
/// extern_class!(
///     /// An example description.
///     #[derive(PartialEq, Eq, Hash)] // Uses the superclass' implementation
///     // Specify the class and struct name to be used
///     pub struct NSFormatter;
///
///     // Specify the superclass, in this case `NSObject`
///     unsafe impl ClassType for NSFormatter {
///         type Super = NSObject;
///         // Optionally, specify the name of the class, if it differs from
///         // the struct name.
///         // const NAME: &'static str = "NSFormatter";
///     }
/// );
///
/// // Provided by the implementation of `ClassType`
/// let cls = NSFormatter::class();
///
/// // `NSFormatter` implements `Message`:
/// let obj: Id<NSFormatter, Shared> = unsafe { msg_send_id![cls, new] };
/// ```
///
/// Represent the `NSDateFormatter` class, using the `NSFormatter` type we
/// declared previously to specify as its superclass.
///
/// ```
/// use objc2::runtime::NSObject;
/// use objc2::{extern_class, ClassType};
/// #
/// # extern_class!(
/// #     #[derive(PartialEq, Eq, Hash)]
/// #     pub struct NSFormatter;
/// #
/// #     unsafe impl ClassType for NSFormatter {
/// #         type Super = NSObject;
/// #     }
/// # );
///
/// extern_class!(
///     #[derive(PartialEq, Eq, Hash)]
///     pub struct NSDateFormatter;
///
///     unsafe impl ClassType for NSDateFormatter {
///         // Specify the correct inheritance chain
///         #[inherits(NSObject)]
///         type Super = NSFormatter;
///     }
/// );
/// ```
///
/// See the source code of `icrate` for many more examples.
#[doc(alias = "@interface")]
#[macro_export]
macro_rules! extern_class {
    (
        $(#[$m:meta])*
        $v:vis struct $name:ident;

        unsafe impl ClassType for $for:ty {
            $(#[inherits($($inheritance_rest:ty),+)])?
            type Super = $superclass:ty;

            $(const NAME: &'static str = $name_const:literal;)?
        }
    ) => {
        // Just shorthand syntax for the following
        $crate::extern_class!(
            $(#[$m])*
            $v struct $name {}

            unsafe impl ClassType for $for {
                $(#[inherits($($inheritance_rest),+)])?
                type Super = $superclass;

                $(const NAME: &'static str = $name_const;)?
            }
        );
    };
    (
        $(#[$m:meta])*
        $v:vis struct $name:ident {
            $($field_vis:vis $field:ident: $field_ty:ty,)*
        }

        unsafe impl ClassType for $for:ty {
            $(#[inherits($($inheritance_rest:ty),+)])?
            type Super = $superclass:ty;

            $(const NAME: &'static str = $name_const:literal;)?
        }
    ) => {
        $crate::__inner_extern_class!(
            $(#[$m])*
            $v struct $name<> {
                $($field_vis $field: $field_ty,)*
            }

            unsafe impl<> ClassType for $for {
                $(#[inherits($($inheritance_rest),+)])?
                type Super = $superclass;

                $(const NAME: &'static str = $name_const;)?
            }
        );

        const _: () = {
            if $crate::__macro_helpers::size_of::<$name>() != 0 {
                $crate::__macro_helpers::panic!($crate::__macro_helpers::concat!(
                    "the struct ",
                    $crate::__macro_helpers::stringify!($name),
                    " is not zero-sized!",
                ))
            }
        };
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __impl_as_ref_borrow {
    {
        impl ($($t:tt)*) for $for:ty {
            fn as_ref($($self:tt)*) $ref:block
            fn as_mut($($self_mut:tt)*) $mut:block
        }

        @()
    } => {};
    {
        impl ($($t:tt)*) for $for:ty {
            fn as_ref($($self:tt)*) $ref:block
            fn as_mut($($self_mut:tt)*) $mut:block
        }

        @($item:ty, $($tail:ty,)*)
    } => {
        impl<$($t)*> $crate::__macro_helpers::AsRef<$item> for $for {
            #[inline]
            fn as_ref($($self)*) -> &$item $ref
        }

        impl<$($t)*> $crate::__macro_helpers::AsMut<$item> for $for {
            #[inline]
            fn as_mut($($self_mut)*) -> &mut $item $mut
        }

        // Borrow and BorrowMut are correct, since subclasses behaves
        // identical to the class they inherit (message sending doesn't care).
        //
        // In particular, `Eq`, `Ord` and `Hash` all give the same results
        // after borrow.

        impl<$($t)*> $crate::__macro_helpers::Borrow<$item> for $for {
            #[inline]
            fn borrow($($self)*) -> &$item $ref
        }

        impl<$($t)*> $crate::__macro_helpers::BorrowMut<$item> for $for {
            #[inline]
            fn borrow_mut($($self_mut)*) -> &mut $item $mut
        }

        $crate::__impl_as_ref_borrow! {
            impl ($($t)*) for $for {
                fn as_ref($($self)*) $ref
                fn as_mut($($self_mut)*) $mut
            }

            @($($tail,)*)
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __inner_extern_class {
    // TODO: Expose this variant of the macro.
    (
        $(#[$m:meta])*
        $v:vis struct $name:ident<$($t_struct:ident $(: $b_struct:ident $(= $default:ty)?)?),* $(,)?> {
            $($field_vis:vis $field:ident: $field_ty:ty,)*
        }

        unsafe impl<$($t_for:ident $(: $b_for:ident)?),* $(,)?> ClassType for $for:ty {
            $(#[inherits($($inheritance_rest:ty),+ $(,)?)])?
            type Super = $superclass:ty;

            $(const NAME: &'static str = $name_const:literal;)?
        }
    ) => {
        $crate::__inner_extern_class! {
            @__inner
            $(#[$m])*
            $v struct ($name<$($t_struct $(: $b_struct $(= $default)?)?),*>) {
                $($field_vis $field: $field_ty,)*
            }

            unsafe impl ($($t_for $(: $b_for)?),*) for $for {
                INHERITS = [$superclass, $($($inheritance_rest,)+)? $crate::runtime::Object];
            }
        }

        unsafe impl<$($t_for $(: $b_for)?),*> ClassType for $for {
            type Super = $superclass;
            const NAME: &'static $crate::__macro_helpers::str = $crate::__select_name!($name; $($name_const)?);

            #[inline]
            fn class() -> &'static $crate::runtime::Class {
                $crate::__class_inner!(
                    $crate::__select_name!($name; $($name_const)?),
                    $crate::__hash_idents!($name),
                )
            }

            #[inline]
            fn as_super(&self) -> &Self::Super {
                &self.__inner
            }

            #[inline]
            fn as_super_mut(&mut self) -> &mut Self::Super {
                &mut self.__inner
            }
        }
    };
    (
        @__inner

        $(#[$m:meta])*
        $v:vis struct ($($struct:tt)*) {
            $($field_vis:vis $field:ident: $field_ty:ty,)*
        }

        unsafe impl ($($t:tt)*) for $for:ty {
            INHERITS = [$superclass:ty $(, $inheritance_rest:ty)*];
        }
    ) => {
        $(#[$m])*
        // TODO: repr(transparent) when the inner pointer is no longer a ZST.
        #[repr(C)]
        $v struct $($struct)* {
            __inner: $superclass,
            // Additional fields (should only be zero-sized PhantomData or ivars).
            $($field_vis $field: $field_ty,)*
        }

        // SAFETY:
        // - The item is FFI-safe with `#[repr(C)]`.
        // - The encoding is taken from the inner item, and caller verifies
        //   that it actually inherits said object.
        // - The rest of the struct's fields are ZSTs, so they don't influence
        //   the layout.
        unsafe impl<$($t)*> $crate::RefEncode for $for {
            const ENCODING_REF: $crate::Encoding
                = <$superclass as $crate::RefEncode>::ENCODING_REF;
        }

        // SAFETY: This is essentially just a newtype wrapper over `Object`
        // (we even ensure that `Object` is always last in our inheritance
        // tree), so it is always safe to reinterpret as that.
        //
        // That the object must work with standard memory management is upheld
        // by the caller.
        unsafe impl<$($t)*> $crate::Message for $for {}

        // SAFETY: An instance can always be _used_ in exactly the same way as
        // its superclasses (though not necessarily _constructed_ in the same
        // way, but `Deref` doesn't allow this).
        //
        // Remember; while we (the Rust side) may intentionally be forgetting
        // which instance we're holding, the Objective-C side will remember,
        // and will always dispatch to the correct method implementations.
        //
        // Any lifetime information that the object may have been holding is
        // safely kept in the returned reference.
        //
        // Generics are discarded (for example in the case of `&NSArray<T, O>`
        // to `&NSObject`), but if the generic contained a lifetime, that
        // lifetime is still included in the returned reference.
        //
        // Note that you can easily have two different variables pointing to
        // the same object, `x: &T` and `y: &T::Target`, and this would be
        // perfectly safe!
        impl<$($t)*> $crate::__macro_helpers::Deref for $for {
            type Target = $superclass;

            #[inline]
            fn deref(&self) -> &Self::Target {
                &self.__inner
            }
        }

        // SAFETY: Mutability does not change anything in the above
        // consideration, the lifetime of `&mut Self::Target` is still tied to
        // `&mut self`.
        //
        // Usually we don't want to allow `&mut` of immutable objects like
        // `NSString`, because their `NSCopying` implementation returns the
        // same object, and would violate aliasing rules.
        //
        // But `&mut NSMutableString` -> `&mut NSString` safe, since the
        // `NSCopying` implementation of `NSMutableString` is used, and that
        // is guaranteed to return a different object.
        impl<$($t)*> $crate::__macro_helpers::DerefMut for $for {
            #[inline]
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.__inner
            }
        }

        impl<$($t)*> $crate::__macro_helpers::AsRef<Self> for $for {
            #[inline]
            fn as_ref(&self) -> &Self {
                self
            }
        }

        impl<$($t)*> $crate::__macro_helpers::AsMut<Self> for $for {
            #[inline]
            fn as_mut(&mut self) -> &mut Self {
                self
            }
        }

        $crate::__impl_as_ref_borrow! {
            impl ($($t)*) for $for {
                fn as_ref(&self) {
                    // Triggers Deref coercion depending on return type
                    &*self
                }
                fn as_mut(&mut self) {
                    // Triggers Deref coercion depending on return type
                    &mut *self
                }
            }

            @($superclass, $($inheritance_rest,)*)
        }
    };
}