|
1 | 1 | mod wasm_builtins;
|
2 | 2 |
|
| 3 | +extern crate js_sys; |
3 | 4 | extern crate rustpython_vm;
|
4 | 5 | extern crate wasm_bindgen;
|
5 | 6 | extern crate web_sys;
|
6 | 7 |
|
7 |
| -use rustpython_vm::VirtualMachine; |
8 | 8 | use rustpython_vm::compile;
|
9 |
| -use rustpython_vm::pyobject::AttributeProtocol; |
| 9 | +use rustpython_vm::pyobject::{self, PyObjectRef, PyResult}; |
| 10 | +use rustpython_vm::VirtualMachine; |
10 | 11 | use wasm_bindgen::prelude::*;
|
11 | 12 | use web_sys::console;
|
12 | 13 |
|
| 14 | +fn py_str_err(vm: &mut VirtualMachine, py_err: &PyObjectRef) -> String { |
| 15 | + vm.to_pystr(&py_err) |
| 16 | + .unwrap_or_else(|_| "Error, and error getting error message".into()) |
| 17 | +} |
| 18 | + |
| 19 | +fn py_to_js(vm: &mut VirtualMachine, py_obj: PyObjectRef) -> JsValue { |
| 20 | + let dumps = rustpython_vm::import::import( |
| 21 | + vm, |
| 22 | + std::path::PathBuf::default(), |
| 23 | + "json", |
| 24 | + &Some("dumps".into()), |
| 25 | + ) |
| 26 | + .expect("Couldn't get json.dumps function"); |
| 27 | + match vm.invoke(dumps, pyobject::PyFuncArgs::new(vec![py_obj], vec![])) { |
| 28 | + Ok(value) => { |
| 29 | + let json = vm.to_pystr(&value).unwrap(); |
| 30 | + js_sys::JSON::parse(&json).unwrap_or(JsValue::UNDEFINED) |
| 31 | + } |
| 32 | + Err(_) => JsValue::UNDEFINED, |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +fn js_to_py(vm: &mut VirtualMachine, js_val: JsValue) -> PyObjectRef { |
| 37 | + let json = match js_sys::JSON::stringify(&js_val) { |
| 38 | + Ok(json) => String::from(json), |
| 39 | + Err(_) => return vm.get_none(), |
| 40 | + }; |
| 41 | + |
| 42 | + let loads = rustpython_vm::import::import( |
| 43 | + vm, |
| 44 | + std::path::PathBuf::default(), |
| 45 | + "json", |
| 46 | + &Some("loads".into()), |
| 47 | + ) |
| 48 | + .expect("Couldn't get json.loads function"); |
| 49 | + |
| 50 | + let py_json = vm.new_str(json); |
| 51 | + |
| 52 | + vm.invoke(loads, pyobject::PyFuncArgs::new(vec![py_json], vec![])) |
| 53 | + // can safely unwrap because we know it's valid JSON |
| 54 | + .unwrap() |
| 55 | +} |
| 56 | + |
| 57 | +fn eval<F>(vm: &mut VirtualMachine, source: &str, setup_scope: F) -> PyResult |
| 58 | +where |
| 59 | + F: Fn(&mut VirtualMachine, &PyObjectRef), |
| 60 | +{ |
| 61 | + // HACK: if the code doesn't end with newline it crashes. |
| 62 | + let mut source = source.to_string(); |
| 63 | + if !source.ends_with('\n') { |
| 64 | + source.push('\n'); |
| 65 | + } |
| 66 | + |
| 67 | + let code_obj = compile::compile(vm, &source, compile::Mode::Exec, None)?; |
| 68 | + |
| 69 | + let builtins = vm.get_builtin_scope(); |
| 70 | + let mut vars = vm.context().new_scope(Some(builtins)); |
| 71 | + |
| 72 | + setup_scope(vm, &mut vars); |
| 73 | + |
| 74 | + vm.run_code_obj(code_obj, vars) |
| 75 | +} |
| 76 | + |
| 77 | +#[wasm_bindgen] |
| 78 | +pub fn eval_py(source: &str, js_injections: Option<js_sys::Object>) -> Result<JsValue, JsValue> { |
| 79 | + if let Some(js_injections) = js_injections.clone() { |
| 80 | + if !js_injections.is_object() { |
| 81 | + return Err(js_sys::TypeError::new("The second argument must be an object").into()); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + let mut vm = VirtualMachine::new(); |
| 86 | + |
| 87 | + vm.ctx.set_attr( |
| 88 | + &vm.builtins, |
| 89 | + "print", |
| 90 | + vm.context() |
| 91 | + .new_rustfunc(wasm_builtins::builtin_print_console), |
| 92 | + ); |
| 93 | + |
| 94 | + let res = eval(&mut vm, source, |vm, vars| { |
| 95 | + let injections = if let Some(js_injections) = js_injections.clone() { |
| 96 | + js_to_py(vm, js_injections.into()) |
| 97 | + } else { |
| 98 | + vm.new_dict() |
| 99 | + }; |
| 100 | + |
| 101 | + vm.ctx.set_item(vars, "js_vars", injections); |
| 102 | + }); |
| 103 | + |
| 104 | + res.map(|value| py_to_js(&mut vm, value)) |
| 105 | + .map_err(|err| py_str_err(&mut vm, &err).into()) |
| 106 | +} |
| 107 | + |
13 | 108 | #[wasm_bindgen]
|
14 |
| -pub fn run_code(source: &str) -> () { |
| 109 | +pub fn run_from_textbox(source: &str) -> Result<JsValue, JsValue> { |
15 | 110 | //add hash in here
|
16 | 111 | console::log_1(&"Running RustPython".into());
|
17 | 112 | console::log_1(&"Running code:".into());
|
18 | 113 | console::log_1(&source.to_string().into());
|
19 | 114 |
|
20 | 115 | let mut vm = VirtualMachine::new();
|
21 |
| - // We are monkey-patching the builtin print to use console.log |
22 |
| - // TODO: moneky-patch sys.stdout instead, after print actually uses sys.stdout |
23 |
| - vm.builtins.set_attr("print", vm.context().new_rustfunc(wasm_builtins::builtin_print)); |
24 | 116 |
|
25 |
| - let code_obj = compile::compile(&mut vm, &source.to_string(), compile::Mode::Exec, None); |
| 117 | + // We are monkey-patching the builtin print to use console.log |
| 118 | + // TODO: monkey-patch sys.stdout instead, after print actually uses sys.stdout |
| 119 | + vm.ctx.set_attr( |
| 120 | + &vm.builtins, |
| 121 | + "print", |
| 122 | + vm.context().new_rustfunc(wasm_builtins::builtin_print_html), |
| 123 | + ); |
26 | 124 |
|
27 |
| - let builtins = vm.get_builtin_scope(); |
28 |
| - let vars = vm.context().new_scope(Some(builtins)); |
29 |
| - match vm.run_code_obj(code_obj.unwrap(), vars) { |
30 |
| - Ok(_value) => console::log_1(&"Execution successful".into()), |
31 |
| - Err(_) => console::log_1(&"Execution failed".into()), |
| 125 | + match eval(&mut vm, source, |_, _| {}) { |
| 126 | + Ok(value) => { |
| 127 | + console::log_1(&"Execution successful".into()); |
| 128 | + match value.borrow().kind { |
| 129 | + pyobject::PyObjectKind::None => {} |
| 130 | + _ => { |
| 131 | + if let Ok(text) = vm.to_pystr(&value) { |
| 132 | + wasm_builtins::print_to_html(&text); |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | + Ok(JsValue::UNDEFINED) |
| 137 | + } |
| 138 | + Err(err) => { |
| 139 | + console::log_1(&"Execution failed".into()); |
| 140 | + Err(py_str_err(&mut vm, &err).into()) |
| 141 | + } |
32 | 142 | }
|
33 | 143 | }
|
0 commit comments