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
use super::{FromInput, Input};
use crate::{
    Ctx, Error, FromJs, Function, IntoJs, Method, MutFn, OnceFn, ParallelSend, Result, This, Value,
};
use std::ops::Range;

#[cfg(feature = "classes")]
use crate::{Class, ClassDef, Constructor};

#[cfg(feature = "futures")]
use crate::{Async, Promised};
#[cfg(feature = "futures")]
use std::future::Future;

/// The trait to wrap rust function to JS directly
pub trait AsFunction<'js, A, R> {
    /// The possible range of function arguments
    fn num_args() -> Range<usize>;

    /// Call as JS function
    fn call(&self, input: &Input<'js>) -> Result<Value<'js>>;

    /// Post-processing the function
    fn post<'js_>(_ctx: Ctx<'js_>, _func: &Function<'js_>) -> Result<()> {
        Ok(())
    }
}

impl<'js> Input<'js> {
    #[doc(hidden)]
    #[inline]
    pub fn check_num_args<F: AsFunction<'js, A, R>, A, R>(&self) -> Result<()> {
        let expected = F::num_args();
        let given = self.len();
        // We can't simply use Range::contains() because actually we operates with Range as with RangeInclusive
        if expected.start <= given && given <= expected.end {
            Ok(())
        } else {
            Err(Error::new_num_args(expected, given))
        }
    }
}

macro_rules! as_function_impls {
    ($($(#[$meta:meta])* $($arg:ident)*,)*) => {
        $(
            // for Fn()
            $(#[$meta])*
            impl<'js, F, R $(, $arg)*> AsFunction<'js, ($($arg,)*), R> for F
            where
                F: Fn($($arg),*) -> R + ParallelSend + 'static,
                R: IntoJs<'js>,
                $($arg: FromInput<'js>,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    $(let $arg = $arg::num_args();)*
                    0usize $(+ $arg.start)* .. 0usize $(.saturating_add($arg.end))*
                }

                #[allow(unused_mut)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;
                    let mut accessor = input.access();
                    self(
                        $($arg::from_input(&mut accessor)?,)*
                    ).into_js(accessor.ctx())
                }
            }

            // for async Fn() via Async wrapper
            #[cfg(feature = "futures")]
            $(#[$meta])*
            impl<'js, F, R $(, $arg)*> AsFunction<'js, ($($arg,)*), Promised<R>> for Async<F>
            where
                F: Fn($($arg),*) -> R + ParallelSend + 'static,
                R: Future + ParallelSend + 'static,
                R::Output: for<'js_> IntoJs<'js_>,
                $($arg: FromInput<'js>,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    $(let $arg = $arg::num_args();)*
                    0usize $(+ $arg.start)* .. 0usize $(.saturating_add($arg.end))*
                }

                #[allow(unused_mut)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;
                    let mut accessor = input.access();
                    Promised(self(
                        $($arg::from_input(&mut accessor)?,)*
                    )).into_js(accessor.ctx())
                }
            }

            // for FnMut() via MutFn wrapper
            $(#[$meta])*
            impl<'js, F, R $(, $arg)*> AsFunction<'js, ($($arg,)*), R> for MutFn<F>
            where
                F: FnMut($($arg),*) -> R + ParallelSend + 'static,
                R: IntoJs<'js>,
                $($arg: FromInput<'js>,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    $(let $arg = $arg::num_args();)*
                    0usize $(+ $arg.start)* .. 0usize $(.saturating_add($arg.end))*
                }

                #[allow(unused_mut)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;
                    let mut func = self.try_borrow_mut()
                        .expect("Mutable function callback is already in use! Could it have been called recursively?");
                    let mut accessor = input.access();
                    func(
                        $($arg::from_input(&mut accessor)?,)*
                    ).into_js(accessor.ctx())
                }
            }

            // for async FnMut() via MutFn wrapper
            #[cfg(feature = "futures")]
            $(#[$meta])*
            impl<'js, F, R $(, $arg)*> AsFunction<'js, ($($arg,)*), Promised<R>> for Async<MutFn<F>>
            where
                F: FnMut($($arg),*) -> R + ParallelSend + 'static,
                R: Future + ParallelSend + 'static,
                R::Output: for<'js_> IntoJs<'js_>,
                $($arg: FromInput<'js>,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    $(let $arg = $arg::num_args();)*
                    0usize $(+ $arg.start)* .. 0usize $(.saturating_add($arg.end))*
                }

                #[allow(unused_mut)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;
                    let mut func = self.try_borrow_mut()
                        .expect("Mutable function callback is already in use! Could it have been called recursively?");
                    let mut accessor = input.access();
                    Promised(func(
                        $($arg::from_input(&mut accessor)?,)*
                    )).into_js(accessor.ctx())
                }
            }

            // for FnOnce() via OnceFn wrapper
            $(#[$meta])*
            impl<'js, F, R $(, $arg)*> AsFunction<'js, ($($arg,)*), R> for OnceFn<F>
            where
                F: FnOnce($($arg),*) -> R + ParallelSend + 'static,
                R: IntoJs<'js>,
                $($arg: FromInput<'js>,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    $(let $arg = $arg::num_args();)*
                    0usize $(+ $arg.start)* .. 0usize $(.saturating_add($arg.end))*
                }

                #[allow(unused_mut)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;
                    let mut func = self.try_borrow_mut()
                        .expect("Once function callback is already in use! Could it have been called recursively?");
                    let func = func.take()
                        .expect("Once function callback is already was used! Could it have been called twice?");
                    let mut accessor = input.access();
                    func(
                        $($arg::from_input(&mut accessor)?,)*
                    ).into_js(accessor.ctx())
                }
            }

            // for async FnOnce() via OnceFn wrapper
            #[cfg(feature = "futures")]
            $(#[$meta])*
            impl<'js, F, R $(, $arg)*> AsFunction<'js, ($($arg,)*), Promised<R>> for Async<OnceFn<F>>
            where
                F: FnOnce($($arg),*) -> R + ParallelSend + 'static,
                R: Future + ParallelSend + 'static,
                R::Output: for<'js_> IntoJs<'js_>,
                $($arg: FromInput<'js>,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    $(let $arg = $arg::num_args();)*
                    0usize $(+ $arg.start)* .. 0usize $(.saturating_add($arg.end))*
                }

                #[allow(unused_mut)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;
                    let mut func = self.try_borrow_mut()
                        .expect("Once function callback is already in use! Could it have been called recursively?");
                    let func = func.take()
                        .expect("Once function callback is already was used! Could it have been called twice?");
                    let mut accessor = input.access();
                    Promised(func(
                        $($arg::from_input(&mut accessor)?,)*
                    )).into_js(accessor.ctx())
                }
            }

            // for methods via Method wrapper
            $(#[$meta])*
            impl<'js, F, R, T $(, $arg)*> AsFunction<'js, (T, $($arg),*), R> for Method<F>
            where
                F: Fn(T, $($arg),*) -> R + ParallelSend + 'static,
                R: IntoJs<'js>,
                T: FromJs<'js>,
                $($arg: FromInput<'js>,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    $(let $arg = $arg::num_args();)*
                    0usize $(+ $arg.start)* .. 0usize $(.saturating_add($arg.end))*
                }

                #[allow(unused_mut)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;
                    let mut accessor = input.access();
                    self(
                        This::<T>::from_input(&mut accessor)?.0,
                        $($arg::from_input(&mut accessor)?,)*
                    ).into_js(accessor.ctx())
                }
            }

            // for async methods via Method wrapper
            #[cfg(feature = "futures")]
            $(#[$meta])*
            impl<'js, F, R, T $(, $arg)*> AsFunction<'js, (T, $($arg),*), Promised<R>> for Async<Method<F>>
            where
                F: Fn(T, $($arg),*) -> R + ParallelSend + 'static,
                R: Future + ParallelSend + 'static,
                R::Output: for<'js_> IntoJs<'js_>,
                T: FromJs<'js>,
                $($arg: FromInput<'js>,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    $(let $arg = $arg::num_args();)*
                    0usize $(+ $arg.start)* .. 0usize $(.saturating_add($arg.end))*
                }

                #[allow(unused_mut)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;
                    let mut accessor = input.access();
                    Promised(self(
                        This::<T>::from_input(&mut accessor)?.0,
                        $($arg::from_input(&mut accessor)?,)*
                    )).into_js(accessor.ctx())
                }
            }
        )*
    };
}

as_function_impls! {
    ,
    A,
    A B,
    A B D,
    A B D E,
    A B D E G,
    A B D E G H,
    #[cfg(feature = "max-args-7")]
    A B C D E G H I,
    #[cfg(feature = "max-args-8")]
    A B C D E G H I J,
    #[cfg(feature = "max-args-9")]
    A B C D E G H I J K,
    #[cfg(feature = "max-args-10")]
    A B C D E G H I J K L,
    #[cfg(feature = "max-args-11")]
    A B C D E G H I J K L M,
    #[cfg(feature = "max-args-12")]
    A B C D E G H I J K L M N,
    #[cfg(feature = "max-args-13")]
    A B C D E G H I J K L M N O,
    #[cfg(feature = "max-args-14")]
    A B C D E G H I J K L M N O P,
    #[cfg(feature = "max-args-15")]
    A B C D E G H I J K L M N O P U,
    #[cfg(feature = "max-args-16")]
    A B C D E G H I J K L M N O P U V,
}

// for constructors via Constructor wrapper
#[cfg(feature = "classes")]
impl<'js, C, F, A, R> AsFunction<'js, A, R> for Constructor<C, F>
where
    C: ClassDef + ParallelSend + 'static,
    F: AsFunction<'js, A, R> + ParallelSend + 'static,
{
    fn num_args() -> Range<usize> {
        F::num_args()
    }

    #[allow(unused_mut)]
    fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
        input.check_num_args::<Self, _, _>()?;

        let mut accessor = input.access();
        let ctx = accessor.ctx();
        let this: Value = accessor.this()?;
        let proto = this
            .as_function()
            // called as a constructor (with new keyword)
            .map(|func| func.get_prototype())
            // called as a function
            .unwrap_or_else(|| Class::<C>::prototype(ctx))?;
        // call constructor
        let res = self.0.call(input)?;
        // set prototype to support inheritance
        res.as_object()
            .ok_or_else(|| Error::new_into_js(res.type_of().as_str(), C::CLASS_NAME))?
            .set_prototype(&proto)?;
        Ok(res)
    }

    fn post<'js_>(ctx: Ctx<'js_>, func: &Function<'js_>) -> Result<()> {
        func.set_constructor(true);
        let proto = Class::<C>::prototype(ctx)?;
        func.set_prototype(&proto);
        Class::<C>::static_init(ctx, func)?;
        Ok(())
    }
}

macro_rules! overloaded_impls {
    ($($(#[$meta:meta])* $func:ident<$func_args:ident, $func_res:ident> $($funcs:ident <$funcs_args:ident, $funcs_res:ident>)*,)*) => {
        $(
            $(#[$meta])*
            impl<'js, $func, $func_args, $func_res $(, $funcs, $funcs_args, $funcs_res)*> AsFunction<'js, ($func_args $(, $funcs_args)*), ($func_res $(, $funcs_res)*)> for ($func $(, $funcs)*)
            where
                $func: AsFunction<'js, $func_args, $func_res> + ParallelSend + 'static,
            $($funcs: AsFunction<'js, $funcs_args, $funcs_res> + ParallelSend + 'static,)*
            {
                #[allow(non_snake_case)]
                fn num_args() -> Range<usize> {
                    let $func = $func::num_args();
                    $(let $funcs = $funcs::num_args();)*
                    $func.start $(.min($funcs.start))* .. $func.end $(.max($funcs.end))*
                }

                #[allow(non_snake_case)]
                fn call(&self, input: &Input<'js>) -> Result<Value<'js>> {
                    input.check_num_args::<Self, _, _>()?;

                    let ($func $(, $funcs)*) = self;

                    // try the first function
                    $func.call(input)
                        $(.or_else(|error| {
                            if error.is_num_args() || error.is_from_js_to_js() {
                                // in case of mismatch args try the second funcion and so on
                                $funcs.call(input)
                            } else {
                                Err(error)
                            }
                        }))*
                }

                fn post<'js_>(ctx: Ctx<'js_>, func: &Function<'js_>) -> Result<()> {
                    $func::post(ctx, func)?;
                    $($funcs::post(ctx, func)?;)*
                    Ok(())
                }
            }
        )*
    };
}

overloaded_impls! {
    F1<A1, R1> F2<A2, R2>,
    F1<A1, R1> F2<A2, R2> F3<A3, R3>,
    F1<A1, R1> F2<A2, R2> F3<A3, R3> F4<A4, R4>,
    F1<A1, R1> F2<A2, R2> F3<A3, R3> F4<A4, R4> F5<A5, R5>,
    F1<A1, R1> F2<A2, R2> F3<A3, R3> F4<A4, R4> F5<A5, R5> F6<A6, R6>,
}