Skip to main content

rquickjs_core/value/function/
args.rs

1use crate::{
2    function::{Flat, Opt, Rest, This},
3    qjs, Ctx, FromJs, Function, IntoJs, Result, Value,
4};
5use alloc::vec::Vec;
6
7use super::{ffi::defer_call_job, Constructor};
8
9const ARGS_ON_STACK: usize = 4;
10
11pub enum ArgsSlice {
12    Stack {
13        slice: [qjs::JSValue; ARGS_ON_STACK],
14        offset: u8,
15    },
16    Heap(Vec<qjs::JSValue>),
17}
18
19/// Argument input for a functions
20///
21/// Arguments on the Rust side for calling into the JavaScript context.
22pub struct Args<'js> {
23    ctx: Ctx<'js>,
24    pub(crate) this: qjs::JSValue,
25    pub(crate) args: ArgsSlice,
26}
27
28impl<'js> Args<'js> {
29    /// Returns a new args with space for a give number of arguments
30    pub fn new(ctx: Ctx<'js>, args: usize) -> Args<'js> {
31        Args {
32            ctx,
33            this: qjs::JS_UNDEFINED,
34            args: if args <= ARGS_ON_STACK {
35                ArgsSlice::Stack {
36                    slice: [qjs::JS_UNDEFINED; ARGS_ON_STACK],
37                    offset: 0,
38                }
39            } else {
40                ArgsSlice::Heap(Vec::with_capacity(args))
41            },
42        }
43    }
44
45    /// Returns a new args with space for any number of arguments
46    pub fn new_unsized(ctx: Ctx<'js>) -> Args<'js> {
47        Args {
48            ctx,
49            this: qjs::JS_UNDEFINED,
50            args: ArgsSlice::Heap(Vec::new()),
51        }
52    }
53
54    /// Returns the context associated with these arguments.
55    pub fn ctx(&self) -> &Ctx<'js> {
56        &self.ctx
57    }
58
59    /// Add an argument to the list.
60    pub fn push_arg<T: IntoJs<'js>>(&mut self, arg: T) -> Result<()> {
61        let v = arg.into_js(&self.ctx)?.into_js_value();
62
63        match self.args {
64            ArgsSlice::Stack {
65                ref mut slice,
66                ref mut offset,
67            } if (*offset as usize) < ARGS_ON_STACK => {
68                slice[*offset as usize] = v;
69                *offset += 1;
70            }
71            ArgsSlice::Stack { slice, offset } => {
72                let mut heap = Vec::with_capacity(ARGS_ON_STACK * 2);
73                heap.extend_from_slice(&slice[..offset as usize]);
74                heap.push(v);
75                self.args = ArgsSlice::Heap(heap);
76            }
77            ArgsSlice::Heap(ref mut h) => h.push(v),
78        }
79
80        Ok(())
81    }
82
83    /// Add multiple arguments to the list.
84    pub fn push_args<T, I>(&mut self, iter: I) -> Result<()>
85    where
86        T: IntoJs<'js>,
87        I: IntoIterator<Item = T>,
88    {
89        for a in iter.into_iter() {
90            self.push_arg(a)?
91        }
92        Ok(())
93    }
94
95    /// Add a this arguments.
96    pub fn this<T>(&mut self, this: T) -> Result<()>
97    where
98        T: IntoJs<'js>,
99    {
100        let v = this.into_js(&self.ctx)?;
101        let v = core::mem::replace(&mut self.this, v.into_js_value());
102        unsafe { qjs::JS_FreeValue(self.ctx.as_ptr(), v) };
103        Ok(())
104    }
105
106    /// Replace the this value with 'Undefined' and return the original value.
107    pub fn take_this(&mut self) -> Value<'js> {
108        let value = core::mem::replace(&mut self.this, qjs::JS_UNDEFINED);
109        Value {
110            ctx: self.ctx().clone(),
111            value,
112        }
113    }
114
115    /// The number of arguments currently in the list.
116    fn len(&self) -> usize {
117        match self.args {
118            ArgsSlice::Stack { offset, .. } => offset as usize,
119            ArgsSlice::Heap(ref h) => h.len(),
120        }
121    }
122
123    fn as_ptr(&self) -> *const qjs::JSValue {
124        match self.args {
125            ArgsSlice::Stack { ref slice, .. } => slice.as_ptr(),
126            ArgsSlice::Heap(ref h) => h.as_ptr(),
127        }
128    }
129
130    /// Call a function with the current set of arguments.
131    pub fn apply<R>(self, func: &Function<'js>) -> Result<R>
132    where
133        R: FromJs<'js>,
134    {
135        let val = unsafe {
136            #[cfg(feature = "parallel")]
137            qjs::JS_UpdateStackTop(qjs::JS_GetRuntime(self.ctx.as_ptr()));
138
139            let val = qjs::JS_Call(
140                self.ctx.as_ptr(),
141                func.as_js_value(),
142                self.this,
143                self.len() as _,
144                self.as_ptr() as _,
145            );
146            let val = self.ctx.handle_exception(val)?;
147            Value::from_js_value(self.ctx.clone(), val)
148        };
149        R::from_js(&self.ctx, val)
150    }
151
152    pub fn defer(mut self, func: Function<'js>) -> Result<()> {
153        let this = self.take_this();
154        self.push_arg(this)?;
155        self.push_arg(func)?;
156        let ctx = self.ctx();
157        unsafe {
158            if qjs::JS_EnqueueJob(
159                ctx.as_ptr(),
160                Some(defer_call_job),
161                self.len() as _,
162                self.as_ptr() as _,
163            ) < 0
164            {
165                return Err(ctx.raise_exception());
166            }
167        }
168        Ok(())
169    }
170
171    pub fn construct<R>(self, constructor: &Constructor<'js>) -> Result<R>
172    where
173        R: FromJs<'js>,
174    {
175        let value = if unsafe { qjs::JS_VALUE_GET_TAG(self.this) != qjs::JS_TAG_UNDEFINED } {
176            unsafe {
177                #[cfg(feature = "parallel")]
178                qjs::JS_UpdateStackTop(qjs::JS_GetRuntime(self.ctx.as_ptr()));
179
180                qjs::JS_CallConstructor2(
181                    self.ctx.as_ptr(),
182                    constructor.as_js_value(),
183                    self.this,
184                    self.len() as _,
185                    self.as_ptr() as _,
186                )
187            }
188        } else {
189            unsafe {
190                #[cfg(feature = "parallel")]
191                qjs::JS_UpdateStackTop(qjs::JS_GetRuntime(self.ctx.as_ptr()));
192
193                qjs::JS_CallConstructor(
194                    self.ctx.as_ptr(),
195                    constructor.as_js_value(),
196                    self.len() as _,
197                    self.as_ptr() as _,
198                )
199            }
200        };
201        let value = unsafe { self.ctx.handle_exception(value)? };
202        let v = unsafe { Value::from_js_value(self.ctx.clone(), value) };
203        R::from_js(&self.ctx, v)
204    }
205}
206
207impl Drop for Args<'_> {
208    fn drop(&mut self) {
209        match self.args {
210            ArgsSlice::Heap(ref h) => h.iter().for_each(|v| {
211                unsafe { qjs::JS_FreeValue(self.ctx.as_ptr(), *v) };
212            }),
213            ArgsSlice::Stack { ref slice, offset } => {
214                slice[..(offset as usize)].iter().for_each(|v| {
215                    unsafe { qjs::JS_FreeValue(self.ctx.as_ptr(), *v) };
216                })
217            }
218        }
219        unsafe { qjs::JS_FreeValue(self.ctx.as_ptr(), self.this) };
220    }
221}
222
223/// A trait for converting values into arguments.
224pub trait IntoArg<'js> {
225    /// The number of arguments this value produces.
226    fn num_args(&self) -> usize;
227
228    /// Convert the value into an argument.
229    fn into_arg(self, args: &mut Args<'js>) -> Result<()>;
230}
231
232/// A trait for converting a tuple of values into a list arguments.
233pub trait IntoArgs<'js> {
234    /// The number of arguments this value produces.
235    fn num_args(&self) -> usize;
236
237    /// Convert the value into an argument.
238    fn into_args(self, args: &mut Args<'js>) -> Result<()>;
239
240    fn apply<R>(self, function: &Function<'js>) -> Result<R>
241    where
242        R: FromJs<'js>,
243        Self: Sized,
244    {
245        let mut args = Args::new(function.ctx().clone(), self.num_args());
246        self.into_args(&mut args)?;
247        args.apply(function)
248    }
249
250    fn defer<R>(self, function: Function<'js>) -> Result<()>
251    where
252        Self: Sized,
253    {
254        let mut args = Args::new(function.ctx().clone(), self.num_args());
255        self.into_args(&mut args)?;
256        args.defer(function)
257    }
258
259    fn construct<R>(self, function: &Constructor<'js>) -> Result<()>
260    where
261        Self: Sized,
262    {
263        let mut args = Args::new(function.ctx().clone(), self.num_args());
264        self.into_args(&mut args)?;
265        args.construct(function)
266    }
267}
268
269impl<'js, T: IntoJs<'js>> IntoArg<'js> for T {
270    fn num_args(&self) -> usize {
271        1
272    }
273
274    fn into_arg(self, args: &mut Args<'js>) -> Result<()> {
275        args.push_arg(self)
276    }
277}
278
279impl<'js, T: IntoJs<'js>> IntoArg<'js> for This<T> {
280    fn num_args(&self) -> usize {
281        0
282    }
283
284    fn into_arg(self, args: &mut Args<'js>) -> Result<()> {
285        args.this(self.0)
286    }
287}
288
289impl<'js, T: IntoJs<'js>> IntoArg<'js> for Opt<T> {
290    fn num_args(&self) -> usize {
291        self.0.is_some() as usize
292    }
293
294    fn into_arg(self, args: &mut Args<'js>) -> Result<()> {
295        if let Some(x) = self.0 {
296            args.push_arg(x)?
297        }
298        Ok(())
299    }
300}
301
302impl<'js, T: IntoJs<'js>> IntoArg<'js> for Rest<T> {
303    fn num_args(&self) -> usize {
304        self.0.len()
305    }
306
307    fn into_arg(self, args: &mut Args<'js>) -> Result<()> {
308        args.push_args(self.0)
309    }
310}
311
312impl<'js, T: IntoArgs<'js>> IntoArg<'js> for Flat<T> {
313    fn num_args(&self) -> usize {
314        self.0.num_args()
315    }
316
317    fn into_arg(self, args: &mut Args<'js>) -> Result<()> {
318        self.0.into_args(args)
319    }
320}
321
322macro_rules! impl_into_args {
323    ($($t:ident),*) => {
324        #[allow(non_snake_case)]
325        impl<'js $(,$t)*> IntoArgs<'js> for ($($t,)*)
326        where
327            $($t : IntoArg<'js>,)*
328        {
329            fn num_args(&self) -> usize{
330                let ($(ref $t,)*) = *self;
331                0 $(+ $t.num_args())*
332            }
333
334            fn into_args(self, _args: &mut Args<'js>) -> Result<()>{
335                let ($($t,)*) = self;
336                $($t.into_arg(_args)?;)*
337                Ok(())
338            }
339        }
340    };
341}
342
343impl_into_args!();
344impl_into_args!(A);
345impl_into_args!(A, B);
346impl_into_args!(A, B, C);
347impl_into_args!(A, B, C, D);
348impl_into_args!(A, B, C, D, E);
349impl_into_args!(A, B, C, D, E, F);
350impl_into_args!(A, B, C, D, E, F, G);