pub struct Context<'rt> { /* private fields */ }Expand description
An execution context: a global object plus the builtins installed on it.
Mirrors the role of JSContext in the QuickJS C API.
Implementations§
Source§impl<'rt> Context<'rt>
impl<'rt> Context<'rt>
Sourcepub fn set_module_loader(&mut self, loader: Box<dyn ModuleLoader>)
pub fn set_module_loader(&mut self, loader: Box<dyn ModuleLoader>)
Install how module specifiers are resolved and read.
Without one, importing is a clear error rather than a silent failure: the engine
cannot guess whether ./x.js means a file, and the host is what knows.
Sourcepub fn set_script_name(&mut self, name: impl Into<String>)
pub fn set_script_name(&mut self, name: impl Into<String>)
Name the scripts this context evaluates, for stack traces.
Mirrors what qjs passes to JS_Eval: -e code is <cmdline>, a script file
is its own path. Without a name, frames print <input>, which is what the
reference uses for code with no file behind it.
Sourcepub fn set_script_args(&mut self, args: Vec<String>)
pub fn set_script_args(&mut self, args: Vec<String>)
Set the arguments scriptArgs should hold.
Element 0 is the script itself, matching qjs: qjs f.js a b gives
["f.js", "a", "b"]. With -e there is no script, so the array is just the
trailing arguments and -e’s own text never appears in it.
This was parsed by the CLI and then dropped on the floor: opts.script_args was
assigned in two places and read in none, so scriptArgs was simply undeclared.
An ordinary script’s if (typeof scriptArgs != "undefined") branch therefore never
ran, and examples/pi_bigint.js printed a thousand digits of pi where the
reference printed usage: pi n_digits.
Works whether or not the interpreter exists yet. The realm is built on first use,
so a host that installs something else first (an output sink, a host function)
would otherwise create it early and have these arguments silently dropped — which
is exactly what print(JSON.stringify(scriptArgs)) caught.
Sourcepub fn eval_module(&mut self, specifier: &str) -> Result<Value>
pub fn eval_module(&mut self, specifier: &str) -> Result<Value>
Evaluate specifier as the entry module, the way qjs -m does.
The microtask queue is drained afterwards, so a module whose top level launched an async task has finished it by the time this returns.
Sourcepub fn eval(&mut self, source: &str) -> Result<Value>
pub fn eval(&mut self, source: &str) -> Result<Value>
Evaluate source as a global script and return its completion value.
The value is reported the way qjs -e reports it: a string for anything the
script leaves on the stack, and nothing at all for undefined.
Sourcepub fn eval_strict(&mut self, source: &str) -> Result<Value>
pub fn eval_strict(&mut self, source: &str) -> Result<Value>
Context::eval with the whole script strict from its first token.
This is qjs --strict, and the reason it is a parse mode rather than a prepended
"use strict": a directive shifts every column on the first line, and those
columns are what a stack trace reports. The reference does the same thing one level
down, with JS_EVAL_FLAG_STRICT.
Sourcepub fn last_value(&self) -> &Value
pub fn last_value(&self) -> &Value
The value of the script that ran last.
Sourcepub fn new_host_function_value(
&mut self,
name: &str,
length: u32,
f: HostFn,
) -> Result<Value>
pub fn new_host_function_value( &mut self, name: &str, length: u32, f: HostFn, ) -> Result<Value>
A host function as a value, for putting on an object rather than the global.
Context::set_global_function is this plus the install; a host module needs the
function first and the install second, on its own object.
Sourcepub fn set_global(&mut self, name: &str, value: Value) -> Result<()>
pub fn set_global(&mut self, name: &str, value: Value) -> Result<()>
Install value on the global object as name.
A host module is one object with functions on it, so mounting std is a single
set_global rather than a function per name — which is what
Context::set_global_function does.
Sourcepub fn set_global_function(
&mut self,
name: &str,
length: u32,
f: HostFn,
) -> Result<()>
pub fn set_global_function( &mut self, name: &str, length: u32, f: HostFn, ) -> Result<()>
Install f on the global object as name.
This is how a host module is built: std.loadFile is a global function the host
registers before the script runs. The closure may capture Rust state but must
not capture a Gc — see crate::object::HostFn.
Sourcepub fn set_global_constructor(
&mut self,
name: &str,
length: u32,
f: HostFn,
) -> Result<Value>
pub fn set_global_constructor( &mut self, name: &str, length: u32, f: HostFn, ) -> Result<Value>
Install f on the global object as the constructor name.
Unlike Context::set_global_function this one gets a prototype object, which
it owns and which new uses — the shape a host class like std.File needs.
Returns the constructor so the host can put methods on its prototype.
Sourcepub fn call(
&mut self,
function: Value,
this: Value,
args: Vec<Value>,
) -> Result<Value>
pub fn call( &mut self, function: Value, this: Value, args: Vec<Value>, ) -> Result<Value>
Call a JavaScript function from Rust.
A thrown value comes back as Error::Exception, so a host callback can report
the script’s own error rather than swallowing it.
Sourcepub fn new_object(&mut self) -> Value
pub fn new_object(&mut self) -> Value
A fresh empty object, for the host to hand back to a script.
Sourcepub fn set_property(
&mut self,
object: &Value,
name: &str,
value: Value,
) -> Result<()>
pub fn set_property( &mut self, object: &Value, name: &str, value: Value, ) -> Result<()>
Set name on object to value, as a plain writable property.
Define name on object as a non-enumerable data property.
Context::set_property writes an enumerable property, which is right for the
members of a host module — Object.keys(std) should list them. A method on a host
class prototype is the opposite: quickjs-libc.c defines the seventeen FILE
methods with JS_CFUNC_DEF, whose flags leave enumerable off, so
Object.keys(std.out) is [] in the reference. A host class needs the same.
Sourcepub fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value>
pub fn new_object_with_prototype(&mut self, proto: &Value) -> Result<Value>
A new ordinary object whose prototype is proto.
Context::new_object gives an object whose prototype is Object.prototype; a
host class needs instances that inherit from its own prototype instead.
Sourcepub fn global(&mut self) -> Value
pub fn global(&mut self) -> Value
The global object, for a host module that has to keep something reachable from every host function it installs.
A HostFn closure may not hold a Gc — the collector
cannot see into it — so a shared JavaScript value (a class prototype, say) has to
live where the collector already scans. The global object is the one object every
interpreter has.
Sourcepub fn new_string(&mut self, text: &str) -> Value
pub fn new_string(&mut self, text: &str) -> Value
A string value.
Sourcepub fn new_number(&mut self, number: f64) -> Value
pub fn new_number(&mut self, number: f64) -> Value
A number value.
Sourcepub fn new_boolean(&mut self, value: bool) -> Value
pub fn new_boolean(&mut self, value: bool) -> Value
A boolean value.
Sourcepub fn set_output_sink(&mut self, sink: Box<dyn Write>)
pub fn set_output_sink(&mut self, sink: Box<dyn Write>)
Route print’s output to sink as it happens, in addition to the buffer
Context::output reads.
Without a sink a script’s output appears only when it finishes. A timer callback
printing after earlier output has to be observably later, which needs the write
to go out at the moment print runs.
Sourcepub fn parse_ext_json(&mut self, text: &str) -> Result<Value>
pub fn parse_ext_json(&mut self, text: &str) -> Result<Value>
Parse text in the extended JSON dialect: comments, unquoted keys, single quotes,
trailing commas, +1/.1/0o10/0xa0, and Infinity/NaN.
This is what backs std.parseExtJSON. It is a separate entry point rather than a
flag on JSON.parse because the two must never share behaviour: a relaxed
JSON.parse would silently accept documents the standard rejects.
Sourcepub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32
pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32
Schedule callback to run after delay_ms milliseconds; returns the timer id.
Sourcepub fn sleep_async(&mut self, delay_ms: f64) -> Result<Value>
pub fn sleep_async(&mut self, delay_ms: f64) -> Result<Value>
A promise that resolves after delay_ms — os.sleepAsync.
Sourcepub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>)
pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>)
Register or clear an os.signal handler.
Sourcepub fn fire_signal(&mut self, signal: i32) -> Result<bool>
pub fn fire_signal(&mut self, signal: i32) -> Result<bool>
Run the handler for signal. false when none is registered.
Sourcepub fn set_fd_handler(
&mut self,
fd: i32,
readable: bool,
callback: Option<Value>,
)
pub fn set_fd_handler( &mut self, fd: i32, readable: bool, callback: Option<Value>, )
Register or clear an os.setReadHandler/os.setWriteHandler callback.
Sourcepub fn pending_fds(&self) -> Vec<FdInterest>
pub fn pending_fds(&self) -> Vec<FdInterest>
The descriptors the host must poll, and in which direction.
Sourcepub fn fire_fd(
&mut self,
fd: i32,
readable: bool,
writable: bool,
) -> Result<bool>
pub fn fire_fd( &mut self, fd: i32, readable: bool, writable: bool, ) -> Result<bool>
Report descriptor readiness, calling the handler. false when none was registered.
Sourcepub fn cancel_timer(&mut self, id: i32) -> bool
pub fn cancel_timer(&mut self, id: i32) -> bool
Cancel a pending timer. false when the id is unknown or already fired.
Sourcepub fn run_one_turn(&mut self) -> Result<Turn>
pub fn run_one_turn(&mut self) -> Result<Turn>
Run one turn of the event loop, reporting what the caller should do next.
crate::Turn::Wait carries the delay to block for; this method never blocks, so
an embedder decides what “wait” means (a thread sleep, a tokio timer, a test clock).
Sourcepub fn has_pending_work(&self) -> bool
pub fn has_pending_work(&self) -> bool
Whether any microtask or timer is still pending.
Sourcepub fn has_pending_timers_or_jobs(&self) -> bool
pub fn has_pending_timers_or_jobs(&self) -> bool
Whether a timer or a microtask is pending, ignoring registered descriptors.
A REPL whose stdin is at end of file still has a read handler registered, and that
handler will keep firing without ever producing another line — so “there is work”
has to mean something narrower than Context::has_pending_work there.
Sourcepub fn take_unhandled_rejections(&mut self) -> Vec<String>
pub fn take_unhandled_rejections(&mut self) -> Vec<String>
Rejections nobody handled, drained.
Context::eval turns these into an error, but an event loop needs them after
every turn rather than at the end of one script: a promise may only become
unhandled later.
Sourcepub fn take_timer_errors(&mut self) -> Vec<String>
pub fn take_timer_errors(&mut self) -> Vec<String>
Errors that timer callbacks threw, drained.
Sourcepub fn take_output(&mut self) -> String
pub fn take_output(&mut self) -> String
Take the buffered output, leaving the buffer empty.
For a host that keeps running turns: Context::output grows without bound, so
draining after each turn bounds the memory without changing what any one
assertion sees.