Skip to main content

Context

Struct Context 

Source
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>

Source

pub fn new(runtime: &'rt Runtime) -> Context<'rt>

Create a context on runtime.

Examples found in repository?
examples/embed.rs (line 6)
4fn main() -> Result<(), quickjs::Error> {
5    let runtime = Runtime::new();
6    let mut context = Context::new(&runtime);
7    context.eval("print([1, 2, 3].map(x => x * 2).join('-'));")?;
8    assert_eq!(context.output(), "2-4-6\n");
9    print!("{}", context.output());
10    Ok(())
11}
Source

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.

Source

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.

Source

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.

Source

pub fn runtime(&self) -> &'rt Runtime

The runtime this context belongs to.

Source

pub fn output(&self) -> &str

Everything print has written.

Examples found in repository?
examples/embed.rs (line 8)
4fn main() -> Result<(), quickjs::Error> {
5    let runtime = Runtime::new();
6    let mut context = Context::new(&runtime);
7    context.eval("print([1, 2, 3].map(x => x * 2).join('-'));")?;
8    assert_eq!(context.output(), "2-4-6\n");
9    print!("{}", context.output());
10    Ok(())
11}
Source

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.

Source

pub fn eval_bytecode(&mut self, bytes: &[u8]) -> Result<Value>

Evaluate an already-compiled bytecode blob, as an AOT binary does.

Nothing is parsed and nothing is compiled: the input is js_compile::serialize::serialize’s output, which carries the file name, the optional source text and the module tables alongside the code. A blob with module tables is run the way qjs -m runs a file — its requests are resolved through the installed module loader, so a precompiled entry module can still import ordinary source files.

A blob is only accepted when its format version matches this build. Bytecode and the opcode table are one unit, so a stale blob is rejected instead of being read as different instructions.

Source

pub fn register_module(&mut self, bytes: &[u8]) -> Result<String>

Register a module from bytecode, so an import of it never reaches the loader.

This is the second half of AOT for modules: qjsc compiles every module the program can reach into a blob, and the product registers them all before running the entry one. The name comes from the blob (qjsc stamped it), and it is the name the loader would have produced, so import "./dep.js" finds it.

Source

pub fn register_data_module( &mut self, name: &str, source: Vec<u8>, attributes: &[(String, String)], ) -> Result<()>

Register a JSON, text or bytes module from its bytes, by name.

attributes is the module’s with { type: … } list, or empty for the name’s extension to decide — the same rule the loader applies.

Source

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.

Examples found in repository?
examples/embed.rs (line 7)
4fn main() -> Result<(), quickjs::Error> {
5    let runtime = Runtime::new();
6    let mut context = Context::new(&runtime);
7    context.eval("print([1, 2, 3].map(x => x * 2).join('-'));")?;
8    assert_eq!(context.output(), "2-4-6\n");
9    print!("{}", context.output());
10    Ok(())
11}
Source

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.

Source

pub fn last_value(&self) -> &Value

The value of the script that ran last.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn new_object(&mut self) -> Value

A fresh empty object, for the host to hand back to a script.

Source

pub fn set_property( &mut self, object: &Value, name: &str, value: Value, ) -> Result<()>

Set name on object to value, as a plain writable property.

Source

pub fn define_hidden( &mut self, object: &Value, name: &str, value: Value, ) -> Result<()>

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.

Source

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.

Source

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.

Source

pub fn new_string(&mut self, text: &str) -> Value

A string value.

Source

pub fn new_number(&mut self, number: f64) -> Value

A number value.

Source

pub fn new_boolean(&mut self, value: bool) -> Value

A boolean value.

Source

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.

Source

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.

Source

pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32

Schedule callback to run after delay_ms milliseconds; returns the timer id.

Source

pub fn sleep_async(&mut self, delay_ms: f64) -> Result<Value>

A promise that resolves after delay_ms — os.sleepAsync.

Source

pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>)

Register or clear an os.signal handler.

Source

pub fn fire_signal(&mut self, signal: i32) -> Result<bool>

Run the handler for signal. false when none is registered.

Source

pub fn set_fd_handler( &mut self, fd: i32, readable: bool, callback: Option<Value>, )

Register or clear an os.setReadHandler/os.setWriteHandler callback.

Source

pub fn pending_fds(&self) -> Vec<FdInterest>

The descriptors the host must poll, and in which direction.

Source

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.

Source

pub fn cancel_timer(&mut self, id: i32) -> bool

Cancel a pending timer. false when the id is unknown or already fired.

Source

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).

Source

pub fn has_pending_work(&self) -> bool

Whether any microtask or timer is still pending.

Source

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.

Source

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.

Source

pub fn take_timer_errors(&mut self) -> Vec<String>

Errors that timer callbacks threw, drained.

Source

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.

Auto Trait Implementations§

§

impl<'rt> !Freeze for Context<'rt>

§

impl<'rt> !RefUnwindSafe for Context<'rt>

§

impl<'rt> !Send for Context<'rt>

§

impl<'rt> !Sync for Context<'rt>

§

impl<'rt> !UnwindSafe for Context<'rt>

§

impl<'rt> Forget for Context<'rt>

§

impl<'rt> Move for Context<'rt>

§

impl<'rt> Unpin for Context<'rt>
where &'rt Runtime: Unpin, &'rt Heap: Unpin, *const GcBox<JsObject> is !null: Unpin, *const LeafNode<String, Gc<Cell>> is !null: Unpin, Box<(String, Gc<Cell>)>: Unpin, *const u8 is !null: Unpin, *const LeafNode<String, SetValZST> is !null: Unpin, Box<(String, SetValZST)>: Unpin, *const LeafNode<&'static str, Gc<JsObject>> is !null: Unpin, Box<(&'static str, Gc<JsObject>)>: Unpin, *const LeafNode<&'static str, Value> is !null: Unpin, Box<(&'static str, Value)>: Unpin, *const LeafNode<String, Value> is !null: Unpin, Box<(String, Value)>: Unpin, *const LeafNode<String, Gc<JsObject>> is !null: Unpin, Box<(String, Gc<JsObject>)>: Unpin, *const GcBox<JsString> is !null: Unpin, *const GcBox<JsSymbol> is !null: Unpin, *const GcBox<BigInt> is !null: Unpin, *const GcBox<CompiledCode> is !null: Unpin, *const GcBox<ClosureEnv> is !null: Unpin, *const GcBox<Cell> is !null: Unpin, *const GcBox<LocalVars> is !null: Unpin, *const GcBox<EvalScope> is !null: Unpin, Box<dyn Write>: Unpin, *const LeafNode<i32, Value> is !null: Unpin, Box<(i32, Value)>: Unpin, *const LeafNode<i32, FdHandlers> is !null: Unpin, Box<(i32, FdHandlers)>: Unpin, *const LeafNode<String, Gc<ModuleRecord>> is !null: Unpin, Box<(String, Gc<ModuleRecord>)>: Unpin, Box<dyn ModuleLoader>: Unpin,

§

impl<'rt> UnsafeUnpin for Context<'rt>
where &'rt Runtime: UnsafeUnpin, &'rt Heap: UnsafeUnpin, *const GcBox<JsObject> is !null: UnsafeUnpin, *const LeafNode<String, Gc<Cell>> is !null: UnsafeUnpin, PhantomData<(Owned, LeafOrInternal)>: UnsafeUnpin, PhantomData<Box<(String, Gc<Cell>)>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<String>: UnsafeUnpin, *const LeafNode<String, SetValZST> is !null: UnsafeUnpin, PhantomData<Box<(String, SetValZST)>>: UnsafeUnpin, *const LeafNode<&'static str, Gc<JsObject>> is !null: UnsafeUnpin, PhantomData<Box<(&'static str, Gc<JsObject>)>>: UnsafeUnpin, *const LeafNode<&'static str, Value> is !null: UnsafeUnpin, PhantomData<Box<(&'static str, Value)>>: UnsafeUnpin, *const LeafNode<String, Value> is !null: UnsafeUnpin, PhantomData<Box<(String, Value)>>: UnsafeUnpin, PhantomData<WeakGc<JsObject>>: UnsafeUnpin, PhantomData<Gc<JsObject>>: UnsafeUnpin, *const LeafNode<String, Gc<JsObject>> is !null: UnsafeUnpin, PhantomData<Box<(String, Gc<JsObject>)>>: UnsafeUnpin, PhantomData<Value>: UnsafeUnpin, PhantomData<Frame>: UnsafeUnpin, PhantomData<EvalBinding>: UnsafeUnpin, *const GcBox<JsString> is !null: UnsafeUnpin, *const GcBox<JsSymbol> is !null: UnsafeUnpin, *const GcBox<BigInt> is !null: UnsafeUnpin, *const GcBox<EvalScope> is !null: UnsafeUnpin, PhantomData<(String, Gc<JsObject>, usize)>: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, *const dyn Write is !null: UnsafeUnpin, PhantomData<dyn Write>: UnsafeUnpin, PhantomData<Job>: UnsafeUnpin, PhantomData<Task>: UnsafeUnpin, PhantomData<usize>: UnsafeUnpin, *const LeafNode<i32, Value> is !null: UnsafeUnpin, PhantomData<Box<(i32, Value)>>: UnsafeUnpin, *const LeafNode<i32, FdHandlers> is !null: UnsafeUnpin, PhantomData<Box<(i32, FdHandlers)>>: UnsafeUnpin, *const LeafNode<String, Gc<ModuleRecord>> is !null: UnsafeUnpin, PhantomData<Box<(String, Gc<ModuleRecord>)>>: UnsafeUnpin, *const dyn ModuleLoader is !null: UnsafeUnpin, PhantomData<dyn ModuleLoader>: UnsafeUnpin, PhantomData<(Gc<JsObject>, Value)>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.