rusty_jsc 0.1.0

Rust bindings for the JavaScriptCore engine
Documentation
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! This library provides a Rust API for the <a href="https://developer.apple.com/documentation/javascriptcore">JavaScriptCore</a> engine.
//!
//! # Example
//!
//! The JavaScriptCore engine lets you evaluate JavaScript scripts from your
//! own application. You first need to create a `JSContext` object and then
//! call its `evaluate_script` method.
//!
//! ```rust
//! use rusty_jsc::JSContext;
//!
//! let mut context = JSContext::default();
//! match context.evaluate_script("'hello, world'", 1) {
//!     Ok(value) => {
//!         println!("{}", value.to_string(&context).unwrap());
//!     }
//!     Err(e) => {
//!         println!(
//!             "Uncaught: {}",
//!             e.to_string(&context).unwrap()
//!         )
//!     }
//! }
//! ```

mod internal;

// #[macro_export]
mod closure;
pub use crate::internal::JSString;
pub use rusty_jsc_macros::callback;
pub use rusty_jsc_sys::JSObjectCallAsFunctionCallback;
use rusty_jsc_sys::*;
use std::fmt;
pub mod private {
    pub use rusty_jsc_sys::*;
}

// pub use crate::closure::callback_closure;

/// A JavaScript value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JSValue {
    inner: JSValueRef,
}

impl Drop for JSValue {
    fn drop(&mut self) {
        // TODO
    }
}

impl JSValue {
    /// Wraps a `JSValue` from a `JSValueRef`.
    fn from(inner: JSValueRef) -> Self {
        Self { inner }
    }

    /// Creates an `undefined` value.
    pub fn undefined(context: &JSContext) -> JSValue {
        JSValue::from(unsafe { JSValueMakeUndefined(context.inner) })
    }

    /// Creates a `null` value.
    pub fn null(context: &JSContext) -> JSValue {
        JSValue::from(unsafe { JSValueMakeNull(context.inner) })
    }

    /// Creates a `boolean` value.
    pub fn boolean(context: &JSContext, value: bool) -> JSValue {
        JSValue::from(unsafe { JSValueMakeBoolean(context.inner, value) })
    }

    /// Creates a `number` value.
    pub fn number(context: &JSContext, value: f64) -> JSValue {
        JSValue::from(unsafe { JSValueMakeNumber(context.inner, value) })
    }

    /// Creates a `string` value.
    pub fn string(context: &JSContext, value: impl Into<JSString>) -> JSValue {
        let value = value.into();
        JSValue::from(unsafe { JSValueMakeString(context.inner, value.inner) })
    }

    pub fn callback(context: &JSContext, callback: JSObjectCallAsFunctionCallback) -> JSValue {
        let name = JSString::from_utf8("".to_string());
        let func = unsafe { JSObjectMakeFunctionWithCallback(context.inner, name.inner, callback) };
        JSValue::from(func)
    }

    /// Checks if this value is `undefined`.
    pub fn is_undefined(&self, context: &JSContext) -> bool {
        unsafe { JSValueIsUndefined(context.inner, self.inner) }
    }

    /// Checks if this value is `null`.
    pub fn is_null(&self, context: &JSContext) -> bool {
        unsafe { JSValueIsNull(context.inner, self.inner) }
    }

    /// Checks if this value is `boolean`.
    pub fn is_boolean(&self, context: &JSContext) -> bool {
        unsafe { JSValueIsBoolean(context.inner, self.inner) }
    }

    /// Checks if this value is `Array`.
    pub fn is_array(&self, context: &JSContext) -> bool {
        unsafe { JSValueIsArray(context.inner, self.inner) }
    }

    /// Checks if this value is `number`.
    pub fn is_number(&self, context: &JSContext) -> bool {
        unsafe { JSValueIsNumber(context.inner, self.inner) }
    }

    /// Checks if this value is `string`.
    pub fn is_string(&self, context: &JSContext) -> bool {
        unsafe { JSValueIsString(context.inner, self.inner) }
    }

    /// Gets this value as a `bool`.
    pub fn to_bool(&self, context: &JSContext) -> bool {
        unsafe { JSValueToBoolean(context.inner, self.inner) }
    }

    /// Formats this value as a `String`.
    pub fn to_string(&self, context: &JSContext) -> Result<JSString, JSValue> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        let string = unsafe { JSValueToStringCopy(context.inner, self.inner, &mut exception) };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        Ok(JSString::from(string))
    }

    // Tries to convert the value to a number
    pub fn to_number(&self, context: &JSContext) -> Result<f64, JSValue> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        let num = unsafe { JSValueToNumber(context.inner, self.inner, &mut exception) };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        Ok(num)
    }

    // Tries to convert the value to an object
    pub fn to_object(&self, context: &JSContext) -> Result<JSObject, JSValue> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        let object_ref = unsafe { JSValueToObject(context.inner, self.inner, &mut exception) };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        let obj = JSObject::from(object_ref);
        Ok(obj)
    }
}

unsafe impl Send for JSValue {}
unsafe impl Sync for JSValue {}

/// A JavaScript object.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JSObject {
    inner: JSObjectRef,
}

unsafe impl Send for JSObject {}
unsafe impl Sync for JSObject {}

impl Drop for JSObject {
    fn drop(&mut self) {
        // TODO
    }
}

impl JSObject {
    /// Wraps a `JSObject` from a `JSObjectRef`.
    fn from(inner: JSObjectRef) -> Self {
        Self { inner }
    }

    pub fn new(context: &JSContext) -> Self {
        let null = std::ptr::null_mut();
        let o_ref = unsafe { JSObjectMake(context.inner, null, null as _) };
        Self::from(o_ref)
    }

    /// Create a new Array Object with the given arguments
    pub fn new_array(context: &JSContext, args: &[JSValue]) -> Result<Self, JSValue> {
        let args_refs = args.iter().map(|arg| arg.inner).collect::<Vec<_>>();
        let mut exception: JSValueRef = std::ptr::null_mut();
        let o_ref = unsafe {
            JSObjectMakeArray(
                context.inner,
                args.len() as _,
                args_refs.as_slice().as_ptr(),
                &mut exception,
            )
        };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        Ok(Self::from(o_ref))
    }

    pub fn new_function_with_callback(
        context: &JSContext,
        name: impl Into<JSString>,
        callback: JSObjectCallAsFunctionCallback,
    ) -> Self {
        let name = name.into();
        let o_ref =
            unsafe { JSObjectMakeFunctionWithCallback(context.inner, name.inner, callback) };
        Self::from(o_ref)
    }

    /// Calls the object constructor
    pub fn construct(&self, context: &JSContext, args: &[JSValue]) -> Result<Self, JSValue> {
        let args_refs = args.iter().map(|arg| arg.inner).collect::<Vec<_>>();
        let mut exception: JSValueRef = std::ptr::null_mut();
        let result = unsafe {
            JSObjectCallAsConstructor(
                context.inner,
                self.inner,
                args.len() as _,
                args_refs.as_slice().as_ptr(),
                &mut exception,
            )
        };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        if result.is_null() {
            return Err(JSValue::string(
                context,
                format!(
                    "Can't call constructor for {:?}: not a valid constructor",
                    self.to_jsvalue().to_string(context)
                ),
            ));
        }
        Ok(Self::from(result))
    }

    /// Call the object as if it a function
    pub fn call(
        &self,
        context: &JSContext,
        this: Option<&JSObject>,
        args: &[JSValue],
    ) -> Result<JSValue, JSValue> {
        let args_refs = args.iter().map(|arg| arg.inner).collect::<Vec<_>>();
        let mut exception: JSValueRef = std::ptr::null_mut();
        let result = unsafe {
            JSObjectCallAsFunction(
                context.inner,
                self.inner,
                this.map(|t| t.inner)
                    .unwrap_or_else(|| std::ptr::null_mut()),
                args.len() as _,
                args_refs.as_slice().as_ptr(),
                &mut exception,
            )
        };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        if result.is_null() {
            return Err(JSValue::string(
                context,
                format!(
                    "Can't call the object {:?}: not a valid function",
                    self.to_jsvalue().to_string(context)
                ),
            ));
        }
        Ok(JSValue::from(result))
    }

    /// Calls the object constructor
    pub fn to_jsvalue(&self) -> JSValue {
        JSValue::from(self.inner)
    }

    pub fn create_typed_array_with_bytes(
        context: &JSContext,
        bytes: &mut [u8],
    ) -> Result<Self, JSValue> {
        let deallocator_ctx = std::ptr::null_mut();
        let mut exception: JSValueRef = std::ptr::null_mut();
        let result = unsafe {
            JSObjectMakeTypedArrayWithBytesNoCopy(
                context.inner,
                JSTypedArrayType_kJSTypedArrayTypeUint8Array,
                bytes.as_mut_ptr() as _,
                bytes.len() as _,
                None,
                deallocator_ctx,
                &mut exception,
            )
        };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        if result.is_null() {
            return Err(JSValue::string(
                context,
                "Can't create a type array".to_string(),
            ));
        }
        Ok(Self::from(result))
    }

    pub fn create_typed_array_from_buffer(
        context: &JSContext,
        buffer: JSObject,
    ) -> Result<Self, JSValue> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        let result = unsafe {
            JSObjectMakeTypedArrayWithArrayBuffer(
                context.inner,
                JSTypedArrayType_kJSTypedArrayTypeUint8Array,
                buffer.inner,
                &mut exception,
            )
        };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        if result.is_null() {
            return Err(JSValue::string(
                context,
                "Can't create a typed array from the provided buffer".to_string(),
            ));
        }
        Ok(Self::from(result))
    }

    pub fn get_typed_array_buffer(&self, context: &JSContext) -> Result<&mut [u8], JSValue> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        let arr_ptr =
            unsafe { JSObjectGetTypedArrayBytesPtr(context.inner, self.inner, &mut exception) };
        let arr_len =
            unsafe { JSObjectGetTypedArrayLength(context.inner, self.inner, &mut exception) };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        let slice = unsafe { std::slice::from_raw_parts_mut(arr_ptr as _, arr_len as usize) };
        Ok(slice)
    }

    /// Gets the property of an object.
    pub fn get_property(&self, context: &JSContext, property_name: impl Into<JSString>) -> JSValue {
        let property_name = property_name.into();
        let mut exception: JSValueRef = std::ptr::null_mut();
        let jsvalue_ref = unsafe {
            JSObjectGetProperty(
                context.inner,
                self.inner,
                property_name.inner,
                &mut exception,
            )
        };
        JSValue::from(jsvalue_ref)
    }

    /// Gets the property of an object at a given index
    pub fn get_property_at_index(
        &self,
        context: &JSContext,
        property_index: u32,
    ) -> Result<JSValue, JSValue> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        let property = unsafe {
            JSObjectGetPropertyAtIndex(context.inner, self.inner, property_index, &mut exception)
        };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        Ok(JSValue::from(property))
    }

    pub fn get_property_names(&mut self, context: &JSContext) -> Vec<String> {
        let property_name_array = unsafe { JSObjectCopyPropertyNames(context.inner, self.inner) };
        let num_properties = unsafe { JSPropertyNameArrayGetCount(property_name_array) };
        (0..num_properties)
            .map(|property_index| {
                JSString::from(unsafe {
                    JSPropertyNameArrayGetNameAtIndex(property_name_array, property_index)
                })
                .to_string()
            })
            .collect::<Vec<_>>()
    }

    // Get the object as an array buffer
    pub fn get_array_buffer(&mut self, context: &JSContext) -> Result<&mut [u8], JSValue> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        let arr_ptr =
            unsafe { JSObjectGetArrayBufferBytesPtr(context.inner, self.inner, &mut exception) };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        let arr_len =
            unsafe { JSObjectGetArrayBufferByteLength(context.inner, self.inner, &mut exception) };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        let slice = unsafe { std::slice::from_raw_parts_mut(arr_ptr as _, arr_len as usize) };
        Ok(slice)
    }

    /// Sets the property of an object.
    pub fn set_property(
        &self,
        context: &JSContext,
        property_name: impl Into<JSString>,
        value: JSValue,
    ) -> Result<(), JSValue> {
        let property_name = property_name.into();
        let attributes = 0; // TODO
        let mut exception: JSValueRef = std::ptr::null_mut();
        unsafe {
            JSObjectSetProperty(
                context.inner,
                self.inner,
                property_name.inner,
                value.inner,
                attributes,
                &mut exception,
            )
        }
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        Ok(())
    }

    /// Sets the property of an object at a given index
    pub fn set_property_at_index(
        &self,
        context: &JSContext,
        index: u32,
        value: JSValue,
    ) -> Result<(), JSValue> {
        let mut exception: JSValueRef = std::ptr::null_mut();
        unsafe {
            JSObjectSetPropertyAtIndex(
                context.inner,
                self.inner,
                index,
                value.inner,
                &mut exception,
            )
        }
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        Ok(())
    }
}

impl From<JSObjectRef> for JSObject {
    fn from(obj: JSObjectRef) -> Self {
        JSObject::from(obj)
    }
}

impl From<JSValueRef> for JSValue {
    fn from(val: JSValueRef) -> Self {
        JSValue::from(val)
    }
}

impl From<JSValue> for JSValueRef {
    fn from(val: JSValue) -> Self {
        val.inner
    }
}

impl From<JSObject> for JSObjectRef {
    fn from(val: JSObject) -> JSObjectRef {
        val.inner
    }
}

/// A JavaScript virtual machine.
pub struct JSVirtualMachine {
    context_group: JSContextGroupRef,
    global_context: JSGlobalContextRef,
}

impl Drop for JSVirtualMachine {
    fn drop(&mut self) {
        unsafe {
            JSGlobalContextRelease(self.global_context);
            JSContextGroupRelease(self.context_group);
        }
    }
}

impl JSVirtualMachine {
    /// Creates a new `JSVirtualMachine` object from a context.
    fn from(context: JSContextRef) -> Self {
        let global_context = unsafe { JSContextGetGlobalContext(context) };
        unsafe {
            JSGlobalContextRetain(global_context);
        }
        let context_group = unsafe { JSContextGetGroup(global_context) };
        unsafe {
            JSContextGroupRetain(context_group);
        }
        Self {
            context_group,
            global_context,
        }
    }

    /// Creates a new `JSVirtualMachine` object.
    fn new() -> Self {
        let context_group = unsafe { JSContextGroupCreate() };
        let global_context =
            unsafe { JSGlobalContextCreateInGroup(context_group, std::ptr::null_mut()) };
        Self {
            context_group,
            global_context,
        }
    }
}

/// A JavaScript execution context.
pub struct JSContext {
    inner: JSContextRef,
    vm: JSVirtualMachine,
}

impl fmt::Debug for JSContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JSContext").finish()
    }
}

impl Default for JSContext {
    fn default() -> Self {
        JSContext::new()
    }
}

impl JSContext {
    /// Create a `JSContext` object from `JSContextRef`.
    pub fn from(ctx: JSContextRef) -> Self {
        let vm = JSVirtualMachine::from(ctx);
        Self { inner: ctx, vm }
    }

    /// Create a new `JSContext` object.
    ///
    /// Note that this associated function also creates a new `JSVirtualMachine`.
    /// If you want to create a `JSContext` object within an existing virtual
    /// machine, please use the `with_virtual_machine` associated function.
    pub fn new() -> Self {
        let vm = JSVirtualMachine::new();
        Self {
            inner: vm.global_context,
            vm,
        }
    }

    /// Create a new `JSContext` object within the provided `JSVirtualMachine`.
    pub fn with_virtual_machine(vm: JSVirtualMachine) -> Self {
        Self {
            inner: vm.global_context,
            vm,
        }
    }

    /// Returns the context global object.
    pub fn get_global_object(&self) -> JSObject {
        JSObject::from(unsafe { JSContextGetGlobalObject(self.inner) })
    }

    /// Evaluate the script.
    ///
    /// Returns the value the script evaluates to. If the script throws an
    /// exception, this function returns `None`. You can query the thrown
    /// exception with the `get_exception` method.
    pub fn evaluate_script(
        &mut self,
        script: &str,
        starting_line_number: i32,
    ) -> Result<JSValue, JSValue> {
        let script = JSString::from_utf8(script.to_string());
        let this_object = std::ptr::null_mut();
        let source_url = std::ptr::null_mut();
        let mut exception: JSValueRef = std::ptr::null_mut();
        let value = unsafe {
            JSEvaluateScript(
                self.vm.global_context,
                script.inner,
                this_object,
                source_url,
                starting_line_number,
                &mut exception,
            )
        };
        if !exception.is_null() {
            return Err(JSValue::from(exception));
        }
        Ok(JSValue::from(value))
    }
}