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
/// Define methods on an external class.
///
/// This is a convenience macro to easily generate associated functions and
/// methods that call [`msg_send!`][crate::msg_send] appropriately.
///
///
/// # Specification
///
/// Within the `impl` block you can define two types of functions without
/// bodies; ["associated functions"] and ["methods"]. These are then mapped to
/// the Objective-C equivalents "class methods" and "instance methods", and an
/// appropriate body is created for you. In particular, if you use `self` your
/// method will assumbed to be an instance method, and if you don't it will be
/// assumed to be a class method.
///
/// The desired selector can be specified using the `#[sel(my:selector:)]`
/// attribute. The name of the function doesn't matter.
///
/// If you specify a function/method with a body, the macro will simply ignore
/// it.
///
/// ["associated functions"]: https://doc.rust-lang.org/reference/items/associated-items.html#methods
/// ["methods"]: https://doc.rust-lang.org/reference/items/associated-items.html#methods
///
///
/// # Safety
///
/// You must ensure that any methods you declare with the `#[sel(...)]`
/// attribute upholds the safety guarantees decribed in the
/// [`msg_send!`][crate::msg_send] macro, _or_ are marked `unsafe`.
///
///
/// # Examples
///
/// Let's create a quick interface to the [`NSCalendar`] class:
///
/// [`NSCalendar`]: https://developer.apple.com/documentation/foundation/nscalendar?language=objc
///
/// ```
/// use objc2::foundation::{NSObject, NSRange, NSString, NSUInteger};
/// use objc2::rc::{Id, Shared};
/// use objc2::{extern_class, extern_methods, msg_send_id, Encode, Encoding, ClassType};
/// #
/// # #[cfg(feature = "gnustep-1-7")]
/// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
///
/// extern_class!(
///     #[derive(PartialEq, Eq, Hash)]
///     pub struct NSCalendar;
///
///     unsafe impl ClassType for NSCalendar {
///         type Super = NSObject;
///     }
/// );
///
/// pub type NSCalendarIdentifier = NSString;
///
/// #[repr(usize)] // NSUInteger
/// pub enum NSCalendarUnit {
///     Hour = 32,
///     Minute = 64,
///     Second = 128,
///     // TODO: More units
/// }
///
/// unsafe impl Encode for NSCalendarUnit {
///     const ENCODING: Encoding = usize::ENCODING;
/// }
///
/// extern_methods!(
///     /// Creation methods.
///     // TODO: Support methods returning `Id`
///     unsafe impl NSCalendar {
///         pub fn current() -> Id<Self, Shared> {
///             unsafe { msg_send_id![Self::class(), currentCalendar] }
///         }
///
///         pub fn new(identifier: &NSCalendarIdentifier) -> Id<Self, Shared> {
///             unsafe {
///                 msg_send_id![
///                     msg_send_id![Self::class(), alloc],
///                     initWithCalendarIdentifier: identifier,
///                 ]
///             }
///         }
///     }
///
///     /// Accessor methods.
///     // SAFETY: `first_weekday` is correctly defined
///     unsafe impl NSCalendar {
///         #[sel(firstWeekday)]
///         pub fn first_weekday(&self) -> NSUInteger;
///
///         pub fn am_symbol(&self) -> Id<NSString, Shared> {
///             unsafe { msg_send_id![self, amSymbol] }
///         }
///
///         #[sel(date:matchesComponents:)]
///         // `unsafe` because we don't have definitions for `NSDate` and
///         // `NSDateComponents` yet, so the user must ensure that is what's
///         // passed.
///         pub unsafe fn date_matches(&self, date: &NSObject, components: &NSObject) -> bool;
///
///         #[sel(maximumRangeOfUnit:)]
///         pub fn max_range(&self, unit: NSCalendarUnit) -> NSRange;
///     }
/// );
/// ```
///
/// The `extern_methods!` declaration then becomes:
///
/// ```
/// # use objc2::foundation::{NSObject, NSRange, NSString, NSUInteger};
/// # use objc2::rc::{Id, Shared};
/// # use objc2::{extern_class, extern_methods, msg_send_id, Encode, Encoding, ClassType};
/// #
/// # #[cfg(feature = "gnustep-1-7")]
/// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
/// #
/// # extern_class!(
/// #     #[derive(PartialEq, Eq, Hash)]
/// #     pub struct NSCalendar;
/// #
/// #     unsafe impl ClassType for NSCalendar {
/// #         type Super = NSObject;
/// #     }
/// # );
/// #
/// # pub type NSCalendarIdentifier = NSString;
/// #
/// # #[repr(usize)] // NSUInteger
/// # pub enum NSCalendarUnit {
/// #     Hour = 32,
/// #     Minute = 64,
/// #     Second = 128,
/// #     // TODO: More units
/// # }
/// #
/// # unsafe impl Encode for NSCalendarUnit {
/// #     const ENCODING: Encoding = usize::ENCODING;
/// # }
/// #
/// # use objc2::msg_send;
/// /// Creation methods.
/// impl NSCalendar {
///     pub fn current() -> Id<Self, Shared> {
///         unsafe { msg_send_id![Self::class(), currentCalendar] }
///     }
///
///     pub fn new(identifier: &NSCalendarIdentifier) -> Id<Self, Shared> {
///         unsafe {
///             msg_send_id![
///                 msg_send_id![Self::class(), alloc],
///                 initWithCalendarIdentifier: identifier,
///             ]
///         }
///     }
/// }
///
/// /// Accessor methods.
/// impl NSCalendar {
///     pub fn first_weekday(&self) -> NSUInteger {
///         unsafe { msg_send![self, firstWeekday] }
///     }
///
///     pub fn am_symbol(&self) -> Id<NSString, Shared> {
///         unsafe { msg_send_id![self, amSymbol] }
///     }
///
///     pub unsafe fn date_matches(&self, date: &NSObject, components: &NSObject) -> bool {
///         unsafe { msg_send![self, date: date, matchesComponents: components] }
///     }
///
///     pub fn max_range(&self, unit: NSCalendarUnit) -> NSRange {
///         unsafe { msg_send![self, maximumRangeOfUnit: unit] }
///     }
/// }
/// ```
#[macro_export]
macro_rules! extern_methods {
    (
        $(
            $(#[$impl_m:meta])*
            unsafe impl<$($t:ident $(: $b:ident $(+ $rest:ident)*)?),*> $type:ty {
                $($methods:tt)*
            }
        )+
    ) => {
        $(
            $(#[$impl_m])*
            impl<$($t $(: $b $(+ $rest)*)?),*> $type {
                $crate::__inner_extern_methods! {
                    @rewrite_methods
                    $($methods)*
                }
            }
        )+
    };
    (
        $(
            $(#[$impl_m:meta])*
            unsafe impl $type:ty {
                $($methods:tt)*
            }
        )+
    ) => {
        $(
            $(#[$impl_m])*
            impl $type {
                $crate::__inner_extern_methods! {
                    @rewrite_methods
                    $($methods)*
                }
            }
        )+
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __inner_extern_methods {
    {@rewrite_methods} => {};
    {
        @rewrite_methods
        // Unsafe variant
        $(#[$($m:tt)*])*
        $v:vis unsafe fn $name:ident($($args:tt)*) $(-> $ret:ty)?;

        $($rest:tt)*
    } => {
        // Detect instance vs. class method.
        $crate::__rewrite_self_arg! {
            ($crate::__inner_extern_methods)
            ($($args)*)
            @method_out
            @($(#[$($m)*])*)
            @($v unsafe fn $name($($args)*) $(-> $ret)?)
            // Will add @(kind)
            // Will add @(args_start)
            // Will add @(args_rest)
        }

        $crate::__inner_extern_methods! {
            @rewrite_methods
            $($rest)*
        }
    };
    {
        @rewrite_methods
        // Safe variant
        $(#[$($m:tt)*])*
        $v:vis fn $name:ident($($args:tt)*) $(-> $ret:ty)?;

        $($rest:tt)*
    } => {
        $crate::__rewrite_self_arg! {
            ($crate::__inner_extern_methods)
            ($($args)*)
            @method_out
            @($(#[$($m)*])*)
            @($v fn $name($($args)*) $(-> $ret)?)
        }

        $crate::__inner_extern_methods! {
            @rewrite_methods
            $($rest)*
        }
    };
    {
        @rewrite_methods
        // Other items that people might want to put here (e.g. functions with
        // a body).
        $associated_item:item

        $($rest:tt)*
    } => {
        $associated_item

        $crate::__inner_extern_methods! {
            @rewrite_methods
            $($rest)*
        }
    };
    {
        @method_out
        @($(#[$($m:tt)*])*)
        @($($function_start:tt)*)
        @($($kind:tt)*)
        @($($args_start:tt)*)
        @($($args_rest:tt)*)
    } => {
        $crate::__attribute_helper! {
            @strip_sel
            $(@[$($m)*])*
            ($($function_start)* {
                #[allow(unused_unsafe)]
                unsafe {
                    $crate::__attribute_helper! {
                        @extract_sel
                        ($crate::__inner_extern_methods)
                        ($(#[$($m)*])*)
                        @unsafe_method_body
                        @($($kind)*)
                        @($($args_start)*)
                        @($($args_rest)*)
                    }
                }
            })
        }
    };

    {
        @unsafe_method_body
        @(instance_method)
        @(
            $self:ident: $self_ty:ty,
            _: $sel_ty:ty,
        )
        @($($args_rest:tt)*)
        @($($sel:tt)*)
    } => {
        $crate::__collect_msg_send!(
            $crate::msg_send;
            $self;
            ($($sel)*);
            ($($args_rest)*);
        )
    };
    {
        @unsafe_method_body
        @(class_method)
        @(
            _: $cls_ty:ty,
            _: $sel_ty:ty,
        )
        @($($args_rest:tt)*)
        @($($sel:tt)*)
    } => {
        $crate::__collect_msg_send!(
            $crate::msg_send;
            Self::class();
            ($($sel)*);
            ($($args_rest)*);
        )
    };
}

/// Zip selector and arguments, and forward to macro.
#[doc(hidden)]
#[macro_export]
macro_rules! __collect_msg_send {
    // Selector with no arguments
    (
        $macro:path;
        $obj:expr;
        ($sel:ident);
        ();
    ) => {{
        $macro![$obj, $sel]
    }};

    // Base case
    (
        $macro:path;
        $obj:expr;
        ();
        ();
        $($output:tt)+
    ) => {{
        $macro![$obj, $($output)+]
    }};

    // tt-munch each argument
    (
        $macro:path;
        $obj:expr;
        ($sel:ident : $($sel_rest:tt)*);
        ($arg:ident: $arg_ty:ty $(, $($args_rest:tt)*)?);
        $($output:tt)*
    ) => {{
        $crate::__collect_msg_send!(
            $macro;
            $obj;
            ($($sel_rest)*);
            ($($($args_rest)*)?);
            $($output)*
            $sel: $arg,
        )
    }};

    // If couldn't zip selector and arguments, show useful error message
    ($($_any:tt)*) => {{
        compile_error!("Number of arguments in function and selector did not match!")
    }};
}