pixelscript 0.5.11

Multi language scripting runtime
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
use std::{cell::RefCell, collections::HashMap};

use anyhow::{Result, anyhow};
use parking_lot::{ReentrantMutex, ReentrantMutexGuard};

use crate::{
    borrow_string, js::{
        func::create_callback, module::add_local_module, utils::SmartJSValue, var::{js_into_pxs, pxs_into_js}
    }, pxs_debug, shared::{
        PXS_METHOD_NAME, PixelScript, pxs_Opaque, read_file, utils::CStringSafe, var::{ObjectMethods, pxs_Var}
    }
};

// Allow for the binidngs only
#[allow(unused)]
#[allow(non_camel_case_types)]
#[allow(non_upper_case_globals)]
#[allow(dead_code)]
pub(self) mod quickjs {
    include!(concat!(env!("OUT_DIR"), "/quickjsng_bindings.rs"));
}

mod func;
mod module;
mod object;
mod var;
mod utils;

/// Holds name and Value for module methods
pub(self) struct JSModuleMethod {
    pub name: String,
    pub value: SmartJSValue
}

/// JS specific State.
struct State {
    /// The JS runtime. Each thread gets it's own runtime.
    rt: *mut quickjs::JSRuntime,
    /// The `__main__` context. Each thread gets it's own context.
    context: *mut quickjs::JSContext,
    /// Keep a list of defined PixelObject as class
    defined_objects: RefCell<HashMap<String, SmartJSValue>>,
    /// Module defined functions or variables takes a map[module_name] => map[int] => export
    module_exports: RefCell<HashMap<String, Vec<JSModuleMethod>>>,
    /// JSModules
    modules: RefCell<HashMap<String, *mut quickjs::JSModuleDef>>,
}

impl Drop for State {
    fn drop(&mut self) {
        self.defined_objects.get_mut().clear();
        self.module_exports.get_mut().clear();

        unsafe {
            if self.context != std::ptr::null_mut() {
                quickjs::JS_FreeContext(self.context);
            }
            if self.rt != std::ptr::null_mut() {
                quickjs::JS_FreeRuntime(self.rt);
            }
        }
    }
}

thread_local! {
    static JSTATE: ReentrantMutex<State> = ReentrantMutex::new(unsafe{init_state()});
}

/// JS Module loader
unsafe extern "C" fn js_module_loader(context: *mut quickjs::JSContext, module_name: *const std::ffi::c_char, _opaque: pxs_Opaque) -> *mut quickjs::JSModuleDef {
    let state = get_js_state();
    let modules = state.modules.borrow();
    unsafe {
        let name = borrow_string!(module_name);
        if let Some(module) = modules.get(name) {
            return *module;
        }

        // Otherwise try to read the file...
        let contents = read_file(name);
        if contents.len() == 0 {
            return std::ptr::null_mut();
        }

        let mut cstrsafe = CStringSafe::new();
        // We need to evalute a module
        let res = quickjs::JS_Eval(context, cstrsafe.new_string(&contents), contents.len(), module_name, (quickjs::JS_EVAL_TYPE_MODULE | quickjs::JS_EVAL_FLAG_COMPILE_ONLY) as i32);
        let smart_res = SmartJSValue::new_borrow(res, context);

        // Check exception
        if smart_res.is_exception() || smart_res.is_error() {
            pxs_debug!("Error compiling module");
            return std::ptr::null_mut();
        }

        let val_int = smart_res.value.u.ptr as isize;
        let m = ((val_int & !15) as *mut std::ffi::c_void).cast::<quickjs::JSModuleDef>();

        m
    }
}

/// Initialize the JS state.
unsafe fn init_state() -> State {
    unsafe {
        let rt = quickjs::JS_NewRuntime();
        let ctx = quickjs::JS_NewContext(rt);

        // Setup module loader!
        quickjs::JS_SetModuleLoaderFunc(rt, None, Some(js_module_loader), std::ptr::null_mut());

        // Add pxs_json.js
        let pxs_json = add_local_module(ctx, include_str!("../../core/js/pxs_json.js"), "pxs_json");

        let mut modules = HashMap::new();
        modules.insert("pxs_json".to_string(), pxs_json);

        State { 
            rt, 
            context: ctx, 
            defined_objects: RefCell::new(HashMap::new()), 
            module_exports: RefCell::new(HashMap::new()),
            modules: RefCell::new(modules),
        }
    }
}

fn get_js_state() -> ReentrantMutexGuard<'static, State> {
    JSTATE.with(|mutex| {
        let guard = mutex.lock();
        // Transmute the lifetime so the guard can be passed around the thread
        unsafe { std::mem::transmute(guard) }
    })
}

/// Run JS code
fn run_js(code: &str, file_name: &str, eval_type: i32) -> SmartJSValue {
    let mut cstrsafe = CStringSafe::new();
    let state = get_js_state();
    unsafe {
        let val = quickjs::JS_Eval(state.context, cstrsafe.new_string(code), code.len(), cstrsafe.new_string(file_name), eval_type);

        // Check for exception
        let exception = SmartJSValue::current_exception(state.context);
        if exception.is_undefined() {
            let smart = SmartJSValue::new_owned(val, state.context);
            if smart.is_promise() {
                smart.await_value()
            } else {
                smart
            }
        } else {
            exception
        }
    }
}

/// Get JS Name (runs code without global this)
fn get_js_name(name: &str) -> SmartJSValue {
    run_js(name, "<get_js_name>", quickjs::JS_EVAL_TYPE_GLOBAL as i32)
}

// /// Add pxs_Map to globalThis
// fn add_map_to_global_this(map: &pxs_VarMap, global_this: &SmartJSValue) -> Result<()> {
//     for key in map.keys() {
//         let js_key = pxs_into_js(global_this.context, key)?;
//         let mut js_val = pxs_into_js(global_this.context, map.get_item(key).unwrap())?;
//         global_this.set_prop_value(&js_key, &mut js_val);
//     }

//     Ok(())
// }

// /// Remove pxs_Map from globalThis
// fn remove_map_from_global_this(map: &pxs_VarMap, global_this: &SmartJSValue) -> Result<()> {
//     for key in map.keys() {
//         let js_key = pxs_into_js(global_this.context, key)?;
//         global_this.del_prop(&js_key);
//     }

//     Ok(())
// }

/// Add main.js
fn add_main_js() {
    run_js(include_str!("../../core/js/main.js"), "main.js", quickjs::JS_EVAL_TYPE_MODULE as i32);
}

pub struct JSScripting;

impl PixelScript for JSScripting {
    fn start() {
        let _state = get_js_state();
        add_main_js();
    }

    fn stop() {
        Self::clear_state(false);
    }

    fn add_module(source: std::sync::Arc<crate::shared::module::pxs_Module>) {
        let state = get_js_state();
        module::add_module(state.context, &source);
    }

    fn execute(code: &str, file_name: &str) -> anyhow::Result<crate::shared::var::pxs_Var> {
        let res = run_js(code, file_name, (quickjs::JS_EVAL_TYPE_MODULE | quickjs::JS_EVAL_FLAG_ASYNC) as i32);
        let pxs_res = js_into_pxs(&res);
        if let Err(err) = pxs_res {
            Ok(pxs_Var::new_exception(err.to_string()))
        } else {
            let val = pxs_res.unwrap();
            if val.is_exception() {
                Ok(val)
            } else {
                Ok(pxs_Var::new_null())
            }
        }
    }

    fn eval(code: &str) -> anyhow::Result<crate::shared::var::pxs_Var> {
        let res = run_js(code, "<eval>", (quickjs::JS_EVAL_TYPE_GLOBAL | quickjs::JS_EVAL_FLAG_ASYNC) as i32);
        js_into_pxs(&res)
    }

    fn start_thread() {
        // Not needed for JS.
    }

    fn stop_thread() {
        // Not needed for JS.
    }

    fn clear_state(call_gc: bool) {
        let state = get_js_state();
        // Clear state stuff first.
        state.defined_objects.borrow_mut().clear();
        if call_gc {
            unsafe {
                quickjs::JS_RunGC(state.rt);
            }
        }
    }

    fn compile(
        code: &str,
        global_scope: crate::shared::var::pxs_Var,
    ) -> anyhow::Result<crate::shared::var::pxs_Var> {
        // Compile object
        let mod_obj = run_js(code, "<code_object>", (quickjs::JS_EVAL_FLAG_COMPILE_ONLY | quickjs::JS_EVAL_TYPE_MODULE) as i32);
        if mod_obj.is_exception() || mod_obj.is_error() {
            return Err(anyhow!("{}", mod_obj.get_error_exception().unwrap()));
        }

        // Execute it for the first time (there needs to be a specific function).
        let res = SmartJSValue::new_owned(unsafe {
            quickjs::JS_EvalFunction(mod_obj.context, mod_obj.value)
        }, mod_obj.context);
        
        if res.is_exception() || res.is_error() {
            return Err(anyhow!("{}", res.get_error_exception().unwrap()));
        }

        // Save the `mod_obj` as pxs
        let pxs_val = js_into_pxs(&mod_obj)?;

        // Now lets convert global_scope into a JS object, then into a PXS object
        let global_scope_js_object = pxs_into_js(mod_obj.context, &global_scope)?;
        // Now back to pxs
        let global_scope_pxs = js_into_pxs(&global_scope_js_object)?;

        // Now lets return our [CodeObject, Global Scope reference]
        let result = pxs_Var::new_list();
        let list = result.get_list().unwrap();

        // Code object
        list.add_item(pxs_val);
        // Global object
        list.add_item(global_scope_pxs);

        Ok(result)
    }

    fn exec_object(
        code: crate::shared::var::pxs_Var,
        local_scope: crate::shared::var::pxs_Var,
    ) -> anyhow::Result<crate::shared::var::pxs_Var> {
        let state = get_js_state();
        let list = code.get_list().unwrap();

        let code_object_pxs = list.get_item(1).unwrap();
        let global_scope = list.get_item(2).unwrap();

        // Convert code object to JS
        let code_object_js = pxs_into_js(state.context, &code_object_pxs)?;
        if !code_object_js.is_module() {
            return Err(anyhow!("Expected module, found: {}", code_object_js.type_string()));
        }

        // Get namespace and __pxs__ method
        let ns = code_object_js.get_module_namespace();
        let pxs_method = ns.get_prop(PXS_METHOD_NAME);
        if !pxs_method.is_function() {
            return Err(anyhow!("Expected function for __pxs__, found: {}", pxs_method.type_string()));
        }

        let args = vec![
            pxs_into_js(state.context, &global_scope)?,
            pxs_into_js(state.context, &local_scope)?
        ];

        // Call method
        let res = pxs_method.call_as_source(&args);

        if res.is_exception() {
            Ok(pxs_Var::new_exception(res.get_error_exception().unwrap()))
        } else {
            js_into_pxs(&res)
        }
    }
}

impl ObjectMethods for JSScripting {
    fn object_call(
        var: &crate::shared::var::pxs_Var,
        method: &str,
        args: &mut crate::shared::var::pxs_VarList,
    ) -> Result<crate::shared::var::pxs_Var, anyhow::Error> {
        let state = get_js_state();
        let js_var = pxs_into_js(state.context, var)?;
        let mut argv = vec![];

        for a in args.vars.iter() {
            argv.push(pxs_into_js(state.context, a)?);
        }

        let res = js_var.call(method, &argv);

        js_into_pxs(&res)
    }

    fn call_method(
        method: &str,
        args: &mut crate::shared::var::pxs_VarList,
    ) -> Result<crate::shared::var::pxs_Var, anyhow::Error> {
        // globalThis.`method`(args)
        let state = get_js_state();
        let mut argv = vec![];
        for arg in args.vars.iter() {
            argv.push(pxs_into_js(state.context, arg)?);
        }

        // Look for method in global_this or eval
        let cbk = get_js_name(method);

        if !cbk.is_function() {
            // js_into_pxs(&cbk)
            Ok(pxs_Var::new_exception(format!("{method} is not a Function")))
        } else {
            let res = cbk.call_as_source(&argv);
            js_into_pxs(&res)
        }
    }

    fn var_call(
        method: &crate::shared::var::pxs_Var,
        args: &mut crate::shared::var::pxs_VarList,
    ) -> Result<crate::shared::var::pxs_Var, anyhow::Error> {
        let state = get_js_state();
        let smart_val = pxs_into_js(state.context, method)?;
        let mut argv = vec![];
        for arg in args.vars.iter() {
            argv.push(pxs_into_js(state.context, arg)?);
        }

        let res = smart_val.call_as_source(&argv);
        js_into_pxs(&res)
    }

    fn get(
        var: &crate::shared::var::pxs_Var,
        key: &str,
    ) -> Result<crate::shared::var::pxs_Var, anyhow::Error> {
        let state = get_js_state();
        let this = pxs_into_js(state.context, var)?;
        let res = this.get_prop(key);

        js_into_pxs(&res)
    }

    fn set(
        var: &crate::shared::var::pxs_Var,
        key: &str,
        value: &crate::shared::var::pxs_Var,
    ) -> Result<crate::shared::var::pxs_Var, anyhow::Error> {
        let state = get_js_state();
        let this = pxs_into_js(state.context, var)?;
        let mut value = pxs_into_js(state.context, value)?;
        
        this.set_prop(key, &mut value);

        Ok(pxs_Var::new_bool(true))
    }

    fn get_from_name(name: &str) -> Result<crate::shared::var::pxs_Var, anyhow::Error> {
        js_into_pxs(&get_js_name(name))
    }
}