Set default stdout of wasm to console.log

The print function of wasm will be
	- `console.log` by default or when giving undefined or "console"
	- a dumb function when giving `null`
	- the function when giving a function

Co-Authored-By: Noah <33094578+coolreader18@users.noreply.github.com>
This commit is contained in:
yangantoandNoah committed 2019-11-27 13:53:07 +08:00
1 parent 79b65e6454
commit d058b3debf
3 files changed
+11 -15

No files matched your search

+3 -2
View File
@@ -33,8 +33,9 @@ pyEval(code, options?);
- `vars?`: `{ [key: string]: any }`: Variables passed to the VM that can be
accessed in Python with the variable `js_vars`. Functions do work, and
receive the Python kwargs as the `this` argument.
- `stdout?`: `(out: string) => void`: A function to replace the native print
function, by default `console.log`.
- `stdout?`: `"console" | ((out: string) => void) | null`: A function to replace the
native print function, and it will be `console.log` when giving `undefined`
or "console", and it will be a dumb function when giving null.
## License
+5 -12
View File
@@ -61,8 +61,10 @@ const TS_CMT_START: &'static str = "/*";
/// - `vars?`: `{ [key: string]: any }`: Variables passed to the VM that can be
/// accessed in Python with the variable `js_vars`. Functions do work, and
/// receive the Python kwargs as the `this` argument.
/// - `stdout?`: `(out: string) => void`: A function to replace the native print
/// function, by default `console.log`.
/// - `stdout?`: `"console" | ((out: string) => void) | null`: A function to replace the
/// native print native print function, and it will be `console.log` when giving
/// `undefined` or "console", and it will be a dumb function when giving null.
pub fn eval_py(source: &str, options: Option<Object>) -> Result<JsValue, JsValue> {
let options = options.unwrap_or_else(Object::new);
let js_vars = {
@@ -75,18 +77,9 @@ pub fn eval_py(source: &str, options: Option<Object>) -> Result<JsValue, JsValue
return Err(TypeError::new("vars must be an object").into());
}
};
let stdout = {
let prop = Reflect::get(&options, &"stdout".into())?;
if prop.is_undefined() {
None
} else {
Some(prop)
}
};
let vm = VMStore::init(PY_EVAL_VM_ID.into(), Some(true));
vm.set_stdout(stdout.unwrap_or(JsValue::UNDEFINED))?;
vm.set_stdout(Reflect::get(&options, &"stdout".into())?)?;
if let Some(js_vars) = js_vars {
vm.add_to_scope("js_vars".into(), js_vars.into())?;
+3 -1
View File
@@ -230,11 +230,13 @@ impl WASMVirtualMachine {
.map_err(|err| convert::js_to_py(vm, err))?;
Ok(vm.get_none())
})
} else if stdout.is_undefined() || stdout.is_null() {
} else if stdout.is_null() {
fn noop(vm: &VirtualMachine, _args: PyFuncArgs) -> PyResult {
Ok(vm.get_none())
}
vm.ctx.new_rustfunc(noop)
} else if stdout.is_undefined() {
vm.ctx.new_rustfunc(wasm_builtins::builtin_print_console)
} else {
return Err(error());
};