emscripten_val/
lib.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#![doc = include_str!("../README.md")]
#![allow(clippy::needless_doctest_main)]

use emscripten_val_sys::sys;
use std::ffi::{CStr, CString};

mod externs;
mod impls;

use crate::externs::*;

/// Emscripten's EM_VAL type
#[allow(non_camel_case_types)]
pub type EM_VAL = sys::EM_VAL;

/// A helper macro which transforms every argument into a Val object.
/// This helps reduce boilerplate for `Val::call`.
#[macro_export]
macro_rules! argv {
    ($($rest:expr),*) => {{
        &[$(&Val::from($rest)),*]
    }};
}

/// Val is a wrapper around emscripten's EM_VAL type, which itself represents javascript objects
#[repr(C)]
#[derive(Eq)]
pub struct Val {
    handle: EM_VAL,
}

impl Val {
    /// Looks up a global value represented by `name`
    pub fn global(name: &str) -> Self {
        let name = CString::new(name).unwrap();
        Self {
            handle: unsafe { sys::_emval_get_global(name.as_ptr()) },
        }
    }

    /// Creates a Val from a raw handle. This can be used for retrieving values from JavaScript, where the JavaScript side should wrap a value with Emval.toHandle, pass it to Rust, and then Rust can use take_ownership to convert it to a Val instance
    pub fn take_ownership(v: sys::EM_VAL) -> Self {
        Self { handle: v }
    }

    /// Create a Val from another Val instance
    pub fn from_val(v: &Val) -> Self {
        let handle = v.as_handle();
        if v.uses_ref_count() {
            unsafe {
                sys::_emval_incref(handle);
            }
        }
        Self { handle }
    }

    /// Create a Val that represents undefined
    pub fn undefined() -> Self {
        Self {
            handle: sys::_EMVAL_UNDEFINED as EM_VAL,
        }
    }

    /// Creates a new Object
    pub fn object() -> Self {
        Self {
            handle: unsafe { sys::_emval_new_object() },
        }
    }

    /// Create a Val that represents null
    pub fn null() -> Self {
        Self {
            handle: sys::_EMVAL_NULL as EM_VAL,
        }
    }

    /// Creates and returns a new Array
    pub fn array() -> Self {
        Self {
            handle: unsafe { sys::_emval_new_array() },
        }
    }

    /// Creates a Val from a string slice
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Self {
        let s = CString::new(s).unwrap();
        Self {
            handle: unsafe { sys::_emval_new_cstring(s.as_ptr() as _) },
        }
    }

    /// Looks up a value by the provided name on the Emscripten Module object.
    pub fn module_property(s: &str) -> Self {
        let s = CString::new(s).unwrap();
        Self {
            handle: unsafe { sys::_emval_get_module_property(s.as_ptr() as _) },
        }
    }

    /// Creates a Val from an array
    pub fn from_array<T: Clone + Into<Val>>(arr: &[T]) -> Self {
        let v = Val::array();
        for elem in arr {
            v.call("push", argv![elem.clone().into()]);
        }
        v
    }

    /// Get the EM_VAL handle of a Val object
    pub fn as_handle(&self) -> EM_VAL {
        self.handle
    }

    /// Call a method associated with the JS object represented by the Val object
    pub fn call(&self, f: &str, args: &[&Val]) -> Val {
        unsafe {
            let typeids = vec![sys::EmvalType; args.len() + 1];
            let f = CString::new(f).unwrap();
            let caller =
                sys::_emval_get_method_caller(typeids.len() as u32, typeids.as_ptr() as _, 0);
            for arg in args {
                sys::_emval_incref(arg.handle);
            }
            let ret = sys::_emval_call_method(
                caller,
                self.handle,
                f.as_ptr() as _,
                std::ptr::null_mut(),
                *(args.as_ptr() as *const *const ()) as _,
            );
            let ret = ret as u32 as EM_VAL;
            Val::take_ownership(ret)
        }
    }

    /// Get a property
    pub fn get<T: Clone + Into<Val>>(&self, prop: &T) -> Val {
        let prop: Val = prop.clone().into();
        Val {
            handle: unsafe { sys::_emval_get_property(self.handle, prop.handle) },
        }
    }

    /// Set a property
    pub fn set<T: Clone + Into<Val>, U: Clone + Into<Val>>(&self, prop: &T, val: &U) {
        let prop: Val = prop.clone().into();
        let val: Val = val.clone().into();
        unsafe { sys::_emval_set_property(self.handle, prop.handle, val.handle) };
    }

    /// Generate a Val object from an i32
    pub fn from_i32(i: i32) -> Self {
        Self {
            handle: unsafe { sys::_emval_take_value(sys::IntType, [i as *const ()].as_ptr() as _) },
        }
    }

    /// Generate a Val object from an u32
    pub fn from_u32(i: u32) -> Self {
        Self {
            handle: unsafe { sys::_emval_take_value(sys::IntType, [i as *const ()].as_ptr() as _) },
        }
    }

    /// Generate a Val object from an f32
    pub fn from_f32(i: f32) -> Self {
        let i = i as i32 as *const ();
        Self {
            handle: unsafe { sys::_emval_take_value(sys::FloatType, [i].as_ptr() as _) },
        }
    }

    /// Generate a Val object from an f64
    pub fn from_f64(i: f64) -> Self {
        let i = i as f32 as i32 as *const ();
        Self {
            handle: unsafe { sys::_emval_take_value(sys::FloatType, [i].as_ptr() as _) },
        }
    }

    /// Generate a Val object from a bool
    pub fn from_bool(i: bool) -> Self {
        Self {
            handle: if i {
                sys::_EMVAL_TRUE as EM_VAL
            } else {
                sys::_EMVAL_FALSE as EM_VAL
            },
        }
    }

    /// Checks whether the underlying type uses ref counting
    fn uses_ref_count(&self) -> bool {
        self.handle > sys::_EMVAL_LAST_RESERVED_HANDLE as EM_VAL
    }

    /// Get and release ownership of the internal handle
    pub fn release_ownership(&mut self) -> EM_VAL {
        let h = self.handle;
        self.handle = std::ptr::null_mut();
        h
    }

    /// Checks if the JavaScript object has own (non-inherited) property with the specified name.
    pub fn has_own_property(&self, key: &str) -> bool {
        Val::global("Object")
            .get(&"prototype")
            .get(&"hasOwnProperty")
            .call("call", argv![self.clone(), key])
            .as_bool()
    }

    /// Converts current value to an f64
    pub fn as_f64(&self) -> f64 {
        unsafe { sys::_emval_as(self.handle, sys::FloatType, std::ptr::null_mut()) }
    }

    /// Converts current value to an f32
    pub fn as_f32(&self) -> f32 {
        unsafe { sys::_emval_as(self.handle, sys::FloatType, std::ptr::null_mut()) as f32 }
    }

    /// Converts current value to an i32
    pub fn as_i32(&self) -> i32 {
        unsafe { sys::_emval_as(self.handle, sys::IntType, std::ptr::null_mut()) as i32 }
    }

    /// Converts current value to a u32
    pub fn as_u32(&self) -> u32 {
        unsafe { sys::_emval_as(self.handle, sys::IntType, std::ptr::null_mut()) as u32 }
    }

    /// Converts current value to a bool. This can be useful also to check if a returned object is valid
    pub fn as_bool(&self) -> bool {
        unsafe { sys::_emval_as(self.handle, sys::BoolType, std::ptr::null_mut()) as i32 != 0 }
    }

    /// Converts current value to a string
    pub fn as_string(&self) -> String {
        unsafe {
            let ptr = _emval_as_str(self.handle);
            let ret = CStr::from_ptr(ptr).to_string_lossy().to_string();
            free(ptr as _);
            ret
        }
    }

    /// Checks whether a value is null
    pub fn is_null(&self) -> bool {
        self.handle == sys::_EMVAL_NULL as EM_VAL
    }

    /// Checks whether a value is undefined
    pub fn is_undefined(&self) -> bool {
        self.handle == sys::_EMVAL_UNDEFINED as EM_VAL
    }

    /// Checks whether a value is true
    pub fn is_true(&self) -> bool {
        self.handle == sys::_EMVAL_TRUE as EM_VAL
    }

    /// Checks whether a value is false
    pub fn is_false(&self) -> bool {
        self.handle == sys::_EMVAL_FALSE as EM_VAL
    }

    /// Checks whether a value is a number
    pub fn is_number(&self) -> bool {
        unsafe { sys::_emval_is_number(self.handle) }
    }

    /// Checks whether a value is a string
    pub fn is_string(&self) -> bool {
        unsafe { sys::_emval_is_string(self.handle) }
    }

    /// Checks whether the object is an instanceof another object
    pub fn instanceof(&self, v: &Val) -> bool {
        unsafe { sys::_emval_instanceof(self.as_handle(), v.as_handle()) }
    }

    /// Checks whether a value is an Array
    pub fn is_array(&self) -> bool {
        self.instanceof(&Val::global("Array"))
    }

    /// Checks if the specified property is in the specified object
    pub fn is_in(&self, v: &Val) -> bool {
        unsafe { sys::_emval_in(self.as_handle(), v.as_handle()) }
    }

    /// Returns the typeof the object
    pub fn type_of(&self) -> Val {
        Val {
            handle: unsafe { sys::_emval_typeof(self.handle) },
        }
    }

    /// Throw the object as a JS exception
    pub fn throw(&self) -> bool {
        unsafe { sys::_emval_throw(self.as_handle()) }
    }

    /// Pauses the Rust code to await the Promise / thenable. This requires [ASYNCIFY](https://emscripten.org/docs/tools_reference/settings_reference.html#asyncify) to be enabled
    pub fn await_(&self) -> Val {
        Val {
            handle: unsafe { sys::_emval_await(self.handle) },
        }
    }

    /// Removes a property from an object
    pub fn delete<T: Clone + Into<Val>>(&self, prop: &T) -> bool {
        unsafe { sys::_emval_delete(self.as_handle(), prop.clone().into().as_handle()) }
    }

    /// Instantiate a new object, passes the `args` to the object's contructor
    pub fn new(&self, args: &[&Val]) -> Val {
        unsafe {
            let typeids = vec![sys::EmvalType; args.len() + 1];
            let caller =
                sys::_emval_get_method_caller(typeids.len() as u32, typeids.as_ptr() as _, 1);
            for arg in args {
                sys::_emval_incref(arg.handle);
            }
            let ret = sys::_emval_call(
                caller,
                self.handle,
                std::ptr::null_mut(),
                *(args.as_ptr() as *const *const ()) as _,
            );
            let ret = ret as u32 as EM_VAL;
            Val::take_ownership(ret)
        }
    }

    fn gt<T: Clone + Into<Val>>(&self, v: &T) -> bool {
        unsafe { sys::_emval_greater_than(self.handle, v.clone().into().handle) }
    }

    fn lt<T: Clone + Into<Val>>(&self, v: &T) -> bool {
        unsafe { sys::_emval_less_than(self.handle, v.clone().into().handle) }
    }

    fn equals<T: Clone + Into<Val>>(&self, v: &T) -> bool {
        unsafe { sys::_emval_equals(self.handle, v.clone().into().handle) }
    }

    /// Check if the current object is strictly equals to another object `===`
    pub fn strictly_equals<T: Clone + Into<Val>>(&self, v: &T) -> bool {
        unsafe { sys::_emval_strictly_equals(self.handle, v.clone().into().handle) }
    }

    /// Checks the validity of an object
    pub fn not(&self) -> bool {
        unsafe { sys::_emval_not(self.handle) }
    }

    /// Convenience method.
    /// Adds a callback to an EventTarget object
    pub fn add_event_listener<F: (FnMut(&Val) -> Val) + 'static>(&self, ev: &str, f: F) {
        unsafe {
            let a: *mut Box<dyn FnMut(&Val) -> Val> = Box::into_raw(Box::new(Box::new(f)));
            let data: *mut std::os::raw::c_void = a as *mut std::os::raw::c_void;
            let ev = CString::new(ev).unwrap();
            _emval_add_event_listener(self.handle, ev.as_ptr() as _, data as _);
        }
    }

    /// Generates a Val object from a function object which takes 0 args
    pub fn from_fn0<F: (FnMut() -> Val) + 'static>(f: F) -> Val {
        unsafe {
            let a: *mut Box<dyn FnMut() -> Val> = Box::into_raw(Box::new(Box::new(f)));
            let data: *mut std::os::raw::c_void = a as *mut std::os::raw::c_void;
            Self {
                handle: _emval_take_fn(0, data as _),
            }
        }
    }

    /// Generates a Val object from a function object which takes 1 arg
    pub fn from_fn1<F: (FnMut(&Val) -> Val) + 'static>(f: F) -> Val {
        unsafe {
            #[allow(clippy::type_complexity)]
            let a: *mut Box<dyn FnMut(&Val) -> Val> = Box::into_raw(Box::new(Box::new(f)));
            let data: *mut std::os::raw::c_void = a as *mut std::os::raw::c_void;
            Self {
                handle: _emval_take_fn(1, data as _),
            }
        }
    }

    /// Generates a Val object from a function object which takes 2 args
    pub fn from_fn2<F: (FnMut(&Val, &Val) -> Val) + 'static>(f: F) -> Val {
        unsafe {
            #[allow(clippy::type_complexity)]
            let a: *mut Box<dyn FnMut(&Val, &Val) -> Val> = Box::into_raw(Box::new(Box::new(f)));
            let data: *mut std::os::raw::c_void = a as *mut std::os::raw::c_void;
            Self {
                handle: _emval_take_fn(2, data as _),
            }
        }
    }

    /// Generates a Val object from a function object which takes 3 args
    pub fn from_fn3<F: (FnMut(&Val, &Val, &Val) -> Val) + 'static>(f: F) -> Val {
        unsafe {
            #[allow(clippy::type_complexity)]
            let a: *mut Box<dyn FnMut(&Val, &Val, &Val) -> Val> =
                Box::into_raw(Box::new(Box::new(f)));
            let data: *mut std::os::raw::c_void = a as *mut std::os::raw::c_void;
            Self {
                handle: _emval_take_fn(3, data as _),
            }
        }
    }

    /// Generates a Val object from a function object which takes 4 args
    pub fn from_fn4<F: (FnMut(&Val, &Val, &Val, &Val) -> Val) + 'static>(f: F) -> Val {
        unsafe {
            #[allow(clippy::type_complexity)]
            let a: *mut Box<dyn FnMut(&Val, &Val, &Val, &Val) -> Val> =
                Box::into_raw(Box::new(Box::new(f)));
            let data: *mut std::os::raw::c_void = a as *mut std::os::raw::c_void;
            Self {
                handle: _emval_take_fn(4, data as _),
            }
        }
    }

    /// Convert a javascript Array to a Rust Vec
    pub fn to_vec<T: Clone + From<Val>>(&self) -> Vec<T> {
        let len = self.get(&"length").as_u32();
        let mut v: Vec<T> = vec![];
        for i in 0..len {
            v.push(T::from(self.get(&i)))
        }
        v
    }
}