neon/types_impl/function/
mod.rs

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
//! Types and traits for working with JavaScript functions.

use smallvec::smallvec;

use crate::{
    context::{Context, Cx},
    handle::Handle,
    object::Object,
    result::{JsResult, NeonResult},
    types::{
        extract::{TryFromJs, TryIntoJs, With},
        private::ValueInternal,
        JsFunction, JsObject, JsValue, Value,
    },
};

pub(crate) mod private;

/// A builder for making a JavaScript function call like `parseInt("42")`.
///
/// The builder methods make it convenient to assemble the call from parts:
/// ```
/// # use neon::prelude::*;
/// # fn foo(mut cx: FunctionContext) -> JsResult<JsNumber> {
/// # let parse_int: Handle<JsFunction> = cx.global("parseInt")?;
/// let x: f64 = parse_int
///     .bind(&mut cx)
///     .arg("42")?
///     .call()?;
/// # Ok(cx.number(x))
/// # }
/// ```
pub struct BindOptions<'a, 'cx: 'a> {
    pub(crate) cx: &'a mut Cx<'cx>,
    pub(crate) callee: Handle<'cx, JsValue>,
    pub(crate) this: Option<Handle<'cx, JsValue>>,
    pub(crate) args: private::ArgsVec<'cx>,
}

impl<'a, 'cx: 'a> BindOptions<'a, 'cx> {
    /// Set the value of `this` for the function call.
    pub fn this<T: TryIntoJs<'cx>>(&mut self, this: T) -> NeonResult<&mut Self> {
        let v = this.try_into_js(self.cx)?;
        self.this = Some(v.upcast());
        Ok(self)
    }

    /// Replaces the arguments list with the given arguments.
    pub fn args<A: TryIntoArguments<'cx>>(&mut self, a: A) -> NeonResult<&mut Self> {
        self.args = a.try_into_args_vec(self.cx)?;
        Ok(self)
    }

    /// Replaces the arguments list with a list computed from a closure.
    pub fn args_with<R, F>(&mut self, f: F) -> NeonResult<&mut Self>
    where
        R: TryIntoArguments<'cx>,
        F: FnOnce(&mut Cx<'cx>) -> R,
    {
        self.args = f(self.cx).try_into_args_vec(self.cx)?;
        Ok(self)
    }

    /// Add an argument to the arguments list.
    pub fn arg<A: TryIntoJs<'cx>>(&mut self, a: A) -> NeonResult<&mut Self> {
        let v = a.try_into_js(self.cx)?;
        self.args.push(v.upcast());
        Ok(self)
    }

    /// Add an argument to the arguments list, computed from a closure.
    pub fn arg_with<R, F>(&mut self, f: F) -> NeonResult<&mut Self>
    where
        R: TryIntoJs<'cx>,
        F: FnOnce(&mut Cx<'cx>) -> R,
    {
        let v = f(self.cx).try_into_js(self.cx)?;
        self.args.push(v.upcast());
        Ok(self)
    }

    /// Make the function call. If the function returns without throwing, the result value
    /// is converted to a Rust value with `TryFromJs::from_js`.
    pub fn call<R: TryFromJs<'cx>>(&mut self) -> NeonResult<R> {
        let this = self.this.unwrap_or_else(|| self.cx.undefined().upcast());
        let v: Handle<JsValue> = unsafe { self.callee.try_call(self.cx, this, &self.args)? };
        R::from_js(self.cx, v)
    }

    /// Make the function call as a constructor. If the function returns without throwing, the
    /// result value is converted to a Rust value with `TryFromJs::from_js`.
    pub fn construct<R: TryFromJs<'cx>>(&mut self) -> NeonResult<R> {
        let v: Handle<JsValue> = unsafe { self.callee.try_construct(self.cx, &self.args)? };
        R::from_js(self.cx, v)
    }

    /// Make the function call for side effect, discarding the result value. This method is
    /// preferable to [`call()`](BindOptions::call) when the result value isn't needed,
    /// since it doesn't require specifying a result type.
    pub fn exec(&mut self) -> NeonResult<()> {
        let _ignore: Handle<JsValue> = self.call()?;
        Ok(())
    }
}

/// A builder for making a JavaScript function call like `parseInt("42")`.
///
/// The builder methods make it convenient to assemble the call from parts:
/// ```
/// # use neon::prelude::*;
/// # fn foo(mut cx: FunctionContext) -> JsResult<JsNumber> {
/// # let parse_int: Handle<JsFunction> = cx.global("parseInt")?;
/// let x: Handle<JsNumber> = parse_int
///     .call_with(&cx)
///     .arg(cx.string("42"))
///     .apply(&mut cx)?;
/// # Ok(x)
/// # }
/// ```
#[deprecated(since = "TBD", note = "use `JsFunction::bind()` instead")]
#[derive(Clone)]
pub struct CallOptions<'a> {
    pub(crate) callee: Handle<'a, JsFunction>,
    pub(crate) this: Option<Handle<'a, JsValue>>,
    pub(crate) args: private::ArgsVec<'a>,
}

impl<'a> CallOptions<'a> {
    /// Set the value of `this` for the function call.
    pub fn this<V: Value>(&mut self, this: Handle<'a, V>) -> &mut Self {
        self.this = Some(this.upcast());
        self
    }

    /// Add an argument to the arguments list.
    pub fn arg<V: Value>(&mut self, arg: Handle<'a, V>) -> &mut Self {
        self.args.push(arg.upcast());
        self
    }

    /// Replaces the arguments list with the given arguments.
    pub fn args<A: Arguments<'a>>(&mut self, args: A) -> &mut Self {
        self.args = args.into_args_vec();
        self
    }

    /// Make the function call. If the function returns without throwing, the result value
    /// is downcast to the type `V`, throwing a `TypeError` if the downcast fails.
    pub fn apply<'b: 'a, V: Value, C: Context<'b>>(&self, cx: &mut C) -> JsResult<'b, V> {
        let this = self.this.unwrap_or_else(|| cx.undefined().upcast());
        let v: Handle<JsValue> = self.callee.call(cx, this, &self.args)?;
        v.downcast_or_throw(cx)
    }

    /// Make the function call for side effect, discarding the result value. This method is
    /// preferable to [`apply()`](CallOptions::apply) when the result value isn't needed,
    /// since it doesn't require specifying a result type.
    pub fn exec<'b: 'a, C: Context<'b>>(&self, cx: &mut C) -> NeonResult<()> {
        let this = self.this.unwrap_or_else(|| cx.undefined().upcast());
        self.callee.call(cx, this, &self.args)?;
        Ok(())
    }
}

/// A builder for making a JavaScript constructor call like `new Array(16)`.
///
/// The builder methods make it convenient to assemble the call from parts:
/// ```
/// # use neon::prelude::*;
/// # fn foo(mut cx: FunctionContext) -> JsResult<JsObject> {
/// # let url: Handle<JsFunction> = cx.global("URL")?;
/// let obj = url
///     .construct_with(&cx)
///     .arg(cx.string("https://neon-bindings.com"))
///     .apply(&mut cx)?;
/// # Ok(obj)
/// # }
/// ```
#[deprecated(since = "TBD", note = "use `JsFunction::bind()` instead")]
#[derive(Clone)]
pub struct ConstructOptions<'a> {
    pub(crate) callee: Handle<'a, JsFunction>,
    pub(crate) args: private::ArgsVec<'a>,
}

impl<'a> ConstructOptions<'a> {
    /// Add an argument to the arguments list.
    pub fn arg<V: Value>(&mut self, arg: Handle<'a, V>) -> &mut Self {
        self.args.push(arg.upcast());
        self
    }

    /// Replaces the arguments list with the given arguments.
    pub fn args<A: Arguments<'a>>(&mut self, args: A) -> &mut Self {
        self.args = args.into_args_vec();
        self
    }

    /// Make the constructor call. If the function returns without throwing, returns
    /// the resulting object.
    pub fn apply<'b: 'a, O: Object, C: Context<'b>>(&self, cx: &mut C) -> JsResult<'b, O> {
        let v: Handle<JsObject> = self.callee.construct(cx, &self.args)?;
        v.downcast_or_throw(cx)
    }
}

/// The trait for specifying values to be converted into arguments for a function call.
/// This trait is sealed and cannot be implemented by types outside of the Neon crate.
///
/// **Note:** This trait is implemented for tuples of up to 32 JavaScript values,
/// but for the sake of brevity, only tuples up to size 8 are shown in this documentation.
pub trait TryIntoArguments<'cx>: private::TryIntoArgumentsInternal<'cx> {}

impl<'cx> private::TryIntoArgumentsInternal<'cx> for () {
    fn try_into_args_vec(self, _cx: &mut Cx<'cx>) -> NeonResult<private::ArgsVec<'cx>> {
        Ok(smallvec![])
    }
}

impl<'cx, F, O> private::TryIntoArgumentsInternal<'cx> for With<F, O>
where
    F: FnOnce(&mut Cx) -> O,
    O: private::TryIntoArgumentsInternal<'cx>,
{
    fn try_into_args_vec(self, cx: &mut Cx<'cx>) -> NeonResult<private::ArgsVec<'cx>> {
        (self.0)(cx).try_into_args_vec(cx)
    }
}

impl<'cx, F, O> TryIntoArguments<'cx> for With<F, O>
where
    F: FnOnce(&mut Cx) -> O,
    O: TryIntoArguments<'cx>,
{
}

impl<'cx, T, E> private::TryIntoArgumentsInternal<'cx> for Result<T, E>
where
    T: private::TryIntoArgumentsInternal<'cx>,
    E: TryIntoJs<'cx>,
{
    fn try_into_args_vec(self, cx: &mut Cx<'cx>) -> NeonResult<private::ArgsVec<'cx>> {
        match self {
            Ok(v) => v.try_into_args_vec(cx),
            Err(err) => err.try_into_js(cx).and_then(|err| cx.throw(err)),
        }
    }
}

impl<'cx, T, E> TryIntoArguments<'cx> for Result<T, E>
where
    T: TryIntoArguments<'cx>,
    E: TryIntoJs<'cx>,
{
}

macro_rules! impl_into_arguments_expand {
    {
        $(#[$attrs:meta])?
        [ $($prefix:ident ),* ];
        [];
    } => {};

    {
        $(#[$attrs:meta])?
        [ $($prefix:ident),* ];
        [ $head:ident $(, $tail:ident)* ];
    } => {
        $(#[$attrs])?
        impl<'cx, $($prefix: TryIntoJs<'cx> + 'cx, )* $head: TryIntoJs<'cx> + 'cx> private::TryIntoArgumentsInternal<'cx> for ($($prefix, )* $head, ) {
            #[allow(non_snake_case)]
            fn try_into_args_vec(self, cx: &mut Cx<'cx>) -> NeonResult<private::ArgsVec<'cx>> {
                let ($($prefix, )* $head, ) = self;
                Ok(smallvec![ $($prefix.try_into_js(cx)?.upcast(),)* $head.try_into_js(cx)?.upcast() ])
             }
         }

         $(#[$attrs])?
         impl<'cx, $($prefix: TryIntoJs<'cx> + 'cx, )* $head: TryIntoJs<'cx> + 'cx> TryIntoArguments<'cx> for ($($prefix, )* $head, ) {}

        impl_into_arguments_expand! {
            $(#[$attrs])?
            [ $($prefix, )* $head ];
            [ $($tail),* ];
        }
   }
}

macro_rules! impl_into_arguments {
    {
        [ $($show:ident),* ];
        [ $($hide:ident),* ];
    } => {
        impl_into_arguments_expand! { []; [ $($show),* ]; }
        impl_into_arguments_expand! { #[doc(hidden)] [ $($show),* ]; [ $($hide),* ]; }
    }
}

impl_into_arguments! {
    // Tuples up to length 8 are included in the docs.
    [V1, V2, V3, V4, V5, V6, V7, V8];

    // Tuples up to length 32 are not included in the docs.
    [
        V9, V10, V11, V12, V13, V14, V15, V16,
        V17, V18, V19, V20, V21, V22, V23, V24,
        V25, V26, V27, V28, V29, V30, V31, V32
    ];
}

/// The trait for specifying arguments for a function call. This trait is sealed and cannot
/// be implemented by types outside of the Neon crate.
///
/// **Note:** This trait is implemented for tuples of up to 32 JavaScript values,
/// but for the sake of brevity, only tuples up to size 8 are shown in this documentation.
pub trait Arguments<'a>: private::ArgumentsInternal<'a> {}

impl<'a> private::ArgumentsInternal<'a> for () {
    fn into_args_vec(self) -> private::ArgsVec<'a> {
        smallvec![]
    }
}

impl<'a> Arguments<'a> for () {}

macro_rules! impl_arguments_expand {
    {
        $(#[$attrs:meta])?
        [ $($prefix:ident),* ];
        [];
    } => {};

    {
        $(#[$attrs:meta])?
        [ $($prefix:ident),* ];
        [ $head:ident $(, $tail:ident)* ];
    } => {
        $(#[$attrs])?
        impl<'a, $($prefix: Value, )* $head: Value> private::ArgumentsInternal<'a> for ($(Handle<'a, $prefix>, )* Handle<'a, $head>, ) {
            #[allow(non_snake_case)]
            fn into_args_vec(self) -> private::ArgsVec<'a> {
                let ($($prefix, )* $head, ) = self;
                smallvec![$($prefix.upcast(),)* $head.upcast()]
             }
         }

         $(#[$attrs])?
         impl<'a, $($prefix: Value, )* $head: Value> Arguments<'a> for ($(Handle<'a, $prefix>, )* Handle<'a, $head>, ) {}

         impl_arguments_expand! {
            $(#[$attrs])?
            [ $($prefix, )* $head ];
            [ $($tail),* ];
         }
    };
}

macro_rules! impl_arguments {
    {
        [ $($show:ident),* ];
        [ $($hide:ident),* ];
    } => {
        impl_arguments_expand! { []; [ $($show),* ]; }
        impl_arguments_expand! { #[doc(hidden)] [ $($show),* ]; [ $($hide),* ]; }
    }
}

impl_arguments! {
    // Tuples up to length 8 are included in the docs.
    [V1, V2, V3, V4, V5, V6, V7, V8];

    // Tuples up to length 32 are not included in the docs.
    [
        V9, V10, V11, V12, V13, V14, V15, V16,
        V17, V18, V19, V20, V21, V22, V23, V24,
        V25, V26, V27, V28, V29, V30, V31, V32
    ];
}