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
use crate::{AsFunction, Ctx, Function, IntoJs, ParallelSend, Result, Value};
use std::{
    cell::RefCell,
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

/// The wrapper for method functions
///
/// The method-like functions is functions which get `this` as the first argument. This wrapper allows receive `this` directly as first argument and do not requires using [`This`] for that purpose.
///
/// ```
/// # use rquickjs::{Runtime, Context, Result, Method, Function, This};
/// # let rt = Runtime::new().unwrap();
/// # let ctx = Context::full(&rt).unwrap();
/// # ctx.with(|ctx| -> Result<()> {
/// #
/// let func = Function::new(ctx, Method(|this: i32, factor: i32| {
///     this * factor
/// }))?;
/// assert_eq!(func.call::<_, i32>((This(3), 2))?, 6);
/// #
/// # Ok(())
/// # }).unwrap();
/// ```
#[repr(transparent)]
pub struct Method<F>(pub F);

/// The wrapper for function to convert is into JS
///
/// The Rust functions should be wrapped to convert it to JS using [`IntoJs`] trait.
///
/// ```
/// # use rquickjs::{Runtime, Context, Result, Func};
/// # let rt = Runtime::new().unwrap();
/// # let ctx = Context::full(&rt).unwrap();
/// # ctx.with(|ctx| -> Result<()> {
/// #
/// // Anonymous function
/// ctx.globals().set("sum", Func::from(|a: i32, b: i32| a + b))?;
/// assert_eq!(ctx.eval::<i32, _>("sum(3, 2)")?, 5);
/// assert_eq!(ctx.eval::<usize, _>("sum.length")?, 2);
/// assert!(ctx.eval::<Option<String>, _>("sum.name")?.is_none());
///
/// // Named function
/// ctx.globals().set("prod", Func::new("multiply", |a: i32, b: i32| a * b))?;
/// assert_eq!(ctx.eval::<i32, _>("prod(3, 2)")?, 6);
/// assert_eq!(ctx.eval::<usize, _>("prod.length")?, 2);
/// assert_eq!(ctx.eval::<String, _>("prod.name")?, "multiply");
/// #
/// # Ok(())
/// # }).unwrap();
/// ```
#[repr(transparent)]
pub struct Func<F>(pub F);

/// The wrapper for async functons
///
/// This type wraps returned future into [`Promised`](crate::Promised)
///
/// ```
/// # use rquickjs::{Runtime, Context, Result, Function, Async};
/// # let rt = Runtime::new().unwrap();
/// # let ctx = Context::full(&rt).unwrap();
/// # ctx.with(|ctx| -> Result<()> {
/// #
/// async fn my_func() {}
/// let func = Function::new(ctx, Async(my_func));
/// #
/// # Ok(())
/// # }).unwrap();
/// ```
#[cfg(feature = "futures")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
#[repr(transparent)]
pub struct Async<F>(pub F);

/// The wrapper for mutable functions
///
/// This wrapper is useful for closures which encloses mutable state.
#[repr(transparent)]
pub struct MutFn<F>(RefCell<F>);

impl<F> From<F> for MutFn<F> {
    fn from(func: F) -> Self {
        Self(RefCell::new(func))
    }
}

/// The wrapper for once functions
///
/// This wrapper is useful for callbacks which can be invoked only once.
#[repr(transparent)]
pub struct OnceFn<F>(RefCell<Option<F>>);

impl<F> From<F> for OnceFn<F> {
    fn from(func: F) -> Self {
        Self(RefCell::new(Some(func)))
    }
}

/// The wrapper to get `this` from input
///
/// ```
/// # use rquickjs::{Runtime, Context, Result, This, Function};
/// # let rt = Runtime::new().unwrap();
/// # let ctx = Context::full(&rt).unwrap();
/// # ctx.with(|ctx| -> Result<()> {
/// #
/// // Get the `this` value via arguments
/// let func = Function::new(ctx, |this: This<i32>, factor: i32| {
///     this.into_inner() * factor
/// })?;
/// // Pass the `this` value to a function
/// assert_eq!(func.call::<_, i32>((This(3), 2))?, 6);
/// #
/// # Ok(())
/// # }).unwrap();
/// ```
#[derive(Clone, Copy, Debug, Default)]
#[repr(transparent)]
pub struct This<T>(pub T);

/// The wrapper to get optional argument from input
///
/// The [`Option`] type cannot be used for that purpose because it implements [`FromJs`](crate::FromJs) trait and requires the argument which may be `undefined`.
///
/// ```
/// # use rquickjs::{Runtime, Context, Result, Opt, Function};
/// # let rt = Runtime::new().unwrap();
/// # let ctx = Context::full(&rt).unwrap();
/// # ctx.with(|ctx| -> Result<()> {
/// #
/// let func = Function::new(ctx, |required: i32, optional: Opt<i32>| {
///     required * optional.into_inner().unwrap_or(1)
/// })?;
/// assert_eq!(func.call::<_, i32>((3,))?, 3);
/// assert_eq!(func.call::<_, i32>((3, 1))?, 3);
/// assert_eq!(func.call::<_, i32>((3, 2))?, 6);
/// #
/// # Ok(())
/// # }).unwrap();
/// ```
#[derive(Clone, Copy, Debug, Default)]
#[repr(transparent)]
pub struct Opt<T>(pub Option<T>);

/// The wrapper the rest arguments from input
///
/// The [`Vec`] type cannot be used for that purpose because it implements [`FromJs`](crate::FromJs) and already used to convert JS arrays.
///
/// ```
/// # use rquickjs::{Runtime, Context, Result, Rest, Function};
/// # let rt = Runtime::new().unwrap();
/// # let ctx = Context::full(&rt).unwrap();
/// # ctx.with(|ctx| -> Result<()> {
/// #
/// let func = Function::new(ctx, |required: i32, optional: Rest<i32>| {
///     optional.into_inner().into_iter().fold(required, |prod, arg| prod * arg)
/// })?;
/// assert_eq!(func.call::<_, i32>((3,))?, 3);
/// assert_eq!(func.call::<_, i32>((3, 2))?, 6);
/// assert_eq!(func.call::<_, i32>((3, 2, 1))?, 6);
/// assert_eq!(func.call::<_, i32>((3, 2, 1, 4))?, 24);
/// #
/// # Ok(())
/// # }).unwrap();
/// ```
#[derive(Clone, Default)]
pub struct Rest<T>(pub Vec<T>);

macro_rules! type_impls {
	  ($($type:ident <$($params:ident),*>($($fields:tt)*): $($impls:ident)*;)*) => {
        $(type_impls!{@impls $type [$($params)*]($($fields)*) $($impls)*})*
	  };

    (@impls $type:ident[$($params:ident)*]($($fields:tt)*) $impl:ident $($impls:ident)*) => {
        type_impls!{@impl $impl($($fields)*) $type $($params)*}
        type_impls!{@impls $type[$($params)*]($($fields)*) $($impls)*}
    };

    (@impls $type:ident[$($params:ident)*]($($fields:tt)*)) => {};

    (@impl into_inner($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => {
        impl<$param $(, $params)*> $type<$param $(, $params)*> {
            pub fn into_inner(self) -> $field {
                self.0
            }
        }
    };

    (@impl Into($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => {
        impl<$param $(, $params)*> From<$type<$param $(, $params)*>> for $field {
            fn from(this: $type<$param $(, $params)*>) -> Self {
                this.0
            }
        }
    };

    (@impl From($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => {
        impl<$param $(, $params)*> From<$field> for $type<$param $(, $params)*> {
            fn from(value: $field) -> Self {
                Self(value $(, type_impls!(@def $fields))*)
            }
        }
    };

    (@impl AsRef($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => {
        impl<$param $(, $params)*> AsRef<$field> for $type<$param $(, $params)*> {
            fn as_ref(&self) -> &$field {
                &self.0
            }
        }
    };

    (@impl AsMut($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => {
        impl<$param $(, $params)*> AsMut<$field> for $type<$param $(, $params)*> {
            fn as_mut(&mut self) -> &mut $field {
                &mut self.0
            }
        }
    };

    (@impl Deref($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => {
        impl<$param $(, $params)*> Deref for $type<$param $(, $params)*> {
            type Target = $field;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }
    };

    (@impl DerefMut($field:ty $(, $fields:tt)*) $type:ident $param:ident $($params:ident)*) => {
        impl<$param $(, $params)*> DerefMut for $type<$param $(, $params)*> {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.0
            }
        }
    };

    (@def $($t:tt)*) => { Default::default() };
}

impl<F, A, R> From<F> for Func<(F, PhantomData<(A, R)>)> {
    fn from(func: F) -> Self {
        Self((func, PhantomData))
    }
}

impl<'js, F, A, R> IntoJs<'js> for Func<(F, PhantomData<(A, R)>)>
where
    F: AsFunction<'js, A, R> + ParallelSend + 'static,
{
    fn into_js(self, ctx: Ctx<'js>) -> Result<Value<'js>> {
        let data = self.0;
        Function::new(ctx, data.0)?.into_js(ctx)
    }
}

impl<N, F, A, R> Func<(N, F, PhantomData<(A, R)>)> {
    pub fn new(name: N, func: F) -> Self {
        Self((name, func, PhantomData))
    }
}

impl<'js, N, F, A, R> IntoJs<'js> for Func<(N, F, PhantomData<(A, R)>)>
where
    N: AsRef<str>,
    F: AsFunction<'js, A, R> + ParallelSend + 'static,
{
    fn into_js(self, ctx: Ctx<'js>) -> Result<Value<'js>> {
        let data = self.0;
        let func = Function::new(ctx, data.1)?;
        func.set_name(data.0)?;
        func.into_js(ctx)
    }
}

type_impls! {
    Func<F>(F): AsRef Deref;
    MutFn<F>(RefCell<F>): AsRef Deref;
    OnceFn<F>(RefCell<Option<F>>): AsRef Deref;
    Method<F>(F): AsRef Deref;
    This<T>(T): into_inner From AsRef AsMut Deref DerefMut;
    Opt<T>(Option<T>): into_inner Into From AsRef AsMut Deref DerefMut;
    Rest<T>(Vec<T>): into_inner Into From AsRef AsMut Deref DerefMut;
}

#[cfg(feature = "futures")]
type_impls! {
    Async<F>(F): AsRef Deref;
}

impl<T> Rest<T> {
    pub fn new() -> Self {
        Self(Vec::new())
    }
}