Skip to main content

Interp

Struct Interp 

Source
pub struct Interp<'a> {
    pub heap: &'a Heap,
    pub realm: Realm,
    pub output: String,
    pub output_sink: Option<Box<dyn Write>>,
    pub field_cache: Vec<Option<FieldCache>>,
    pub oom_reported_at: usize,
    pub stack_limit: usize,
    pub max_frames: usize,
    pub modules: BTreeMap<String, Gc<ModuleRecord>>,
    pub module_loader: Option<Box<dyn ModuleLoader>>,
    pub main_module_name: Option<String>,
    pub module_stack: Vec<String>,
    /* private fields */
}
Expand description

The interpreter: a realm plus a frame stack.

Fields§

§heap: &'a Heap

The heap everything is allocated on.

§realm: Realm

The realm.

§output: String

Text written by print and friends, in order.

Buffered rather than streamed so a test can inspect it; the CLI flushes it once at the end, which is also when upstream’s line buffering becomes visible for the cases compared here.

§output_sink: Option<Box<dyn Write>>

Where print also writes, as it goes. output keeps the full log for crate::Context::output; this is the live copy, flushed per line.

Both exist on purpose. A host that gives a script a sink sees output when it happens — which is what a timer callback’s console.log has to do, and what the reference does with fputs + fflush — while embedders and the 595 assertions in this repository keep reading the accumulated String. Buffering only (no sink) would show a script’s output all at once when it finished.

§field_cache: Vec<Option<FieldCache>>

Where recent property reads found their value.

An inline cache, in the only form that is safe without hidden classes: a direct-mapped table remembering which object and which entry of its property table answered a given name. The entry is re-validated on every hit (the table is a Vec, so an index can move; the property can become an accessor), which is what makes a stale entry a miss rather than a wrong answer.

The object is held weakly: a cache that held it strongly would keep up to FIELD_CACHE_SLOTS objects alive for the life of the interpreter, which is a leak a program cannot see and cannot work around.

§oom_reported_at: usize

The heap total at which out of memory was last raised, or 0 when the heap is under its limit. See Interp::check_memory.

§stack_limit: usize

The most stack a JavaScript call chain may use, in bytes of frame state.

The reference rations the C stack here: each call allocas its value slots and js_check_stack_overflow compares the stack pointer against rt->stack_limit. This interpreter does not recurse in Rust — a call pushes a [Frame] instead (see the module comment) — so there is no C stack to run out of, and the C stack is the wrong thing to measure. What a deep recursion actually costs here is frame state, so that is what the budget counts: size_of::<Frame>() plus the frame’s own slots.

The numbers come out close for the same reason a C frame and a heap frame of this shape cost about the same (both are a few hundred bytes, dominated by the value slots): qjs --stack-size 1M bottoms out at depth 1985 on function f(){ d++; f() } and this engine lands in the same neighbourhood — measured, not fudged, by crates/quickjs-cli/tests/limits.rs.

§max_frames: usize

The most frames that may be live at once, whatever the byte budget says.

A second bound for a reason the reference does not have: our frames cost less than its C frames, so a large --stack-size would otherwise buy an unbounded number of them and a Vec<Frame> in the hundreds of megabytes. This cap is what keeps --stack-size 1G from being a memory bomb.

§modules: BTreeMap<String, Gc<ModuleRecord>>

The module registry, keyed by canonical name.

§module_loader: Option<Box<dyn ModuleLoader>>

How the host turns a specifier into bytes.

§main_module_name: Option<String>

The module the host was asked to run, for import.meta.main.

§module_stack: Vec<String>

Module bodies currently running, innermost last.

A dynamic import() resolves its specifier relative to the module that ran it, and this is the only place that knows which module that is.

Implementations§

Source§

impl<'a> Interp<'a>

Source

pub fn new(heap: &'a Heap) -> Interp<'a>

Build an interpreter over heap, with a fresh realm.

Source

pub fn bigint(&self, value: BigInt) -> Value

A new string value. A BigInt value from a computed big integer.

Source

pub fn string_wtf8(&self, text: Wtf8) -> Value

A string value from bytes that are already WTF-8, which is how a string with an unpaired surrogate reaches a Value.

Source

pub fn string(&self, text: impl Into<String>) -> Value

A new string value, from text that is valid UTF-8.

Source

pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject>

A new ordinary object with the given prototype.

Source

pub fn new_iterator_prototype( &mut self, tag: &str, next: NativeFn, ) -> Gc<JsObject>

A prototype for a built-in iterator, inheriting from Iterator.prototype.

Every built-in iterator has one — %ArrayIteratorPrototype%, %StringIteratorPrototype% and so on — and the whole point of the chain is that such an iterator is an Iterator: [1,2].values().map(f) resolves map by walking up to Iterator.prototype. These used to be plain objects hanging off Object.prototype, so .map was undefined and Object.prototype.toString said [object Object] instead of [object Array Iterator].

The prototype carries next, [Symbol.iterator] answering this, and the @@toStringTag that names it. next is passed in because each iterator kind has its own.

Source

pub fn object_own_property_keys( &mut self, object: &Gc<JsObject>, ) -> JsResult<Vec<PropertyKey>>

[[OwnPropertyKeys]], with the ownKeys trap when there is one.

A trap’s list is used as returned: unlike an ordinary object, whose integer keys the engine sorts, a proxy is specified to hand back exactly what the handler produced. That is why the two branches are not merged.

Source

pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<PromiseRef>

The state behind a promise object, or None when object is not one.

Source

pub fn new_promise(&mut self) -> Gc<JsObject>

A new pending promise.

Source

pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value)

Fulfil promise, unless it has already settled.

Settling is one-shot, and a script can see that: resolve called twice, or called after reject, changes nothing.

Source

pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value)

Reject promise, unless it has already settled.

Source

pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value)

NewPromiseCapability as the executor receives it: the promise plus its resolve/reject pair.

The pair are callable objects rather than Rust closures, because the script gets them and may stash them for later.

Source

pub fn eval_in_global_async( &mut self, source: &str, barrier: bool, ) -> JsResult<Value>

std.evalScript(source, { async: true }): the completion value delivered through a promise, as { value: completion }.

The three cases are the reference’s, and they differ on purpose:

  • a syntax error throws synchronously — JS_Eval reports a parse failure as an exception before any promise exists;
  • a runtime error rejects the returned promise;
  • success resolves it with { value }, where the value is the script’s completion value literally. It is not awaited: std.evalScript("Promise.resolve(7)", {async: true}) answers {value: <the promise>}, and only an explicit top-level await produces {value: 7}. That is the reference’s JS_Eval with JS_EVAL_FLAG_ASYNC, which stores the completion value rather than adopting it.
§What this does not do

The reference’s JS_EVAL_FLAG_ASYNC also permits top-level await: the script is evaluated in an async context, so await outside a function is legal. That needs the parser and the suspension machinery to accept a suspended top-level script, and is not implemented — such source is a syntax error here. Everything else about the flag is reproduced.

Source

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

A promise that resolves after delay_ms, which is os.sleepAsync.

Built on Interp::schedule_timer rather than a second queue, so the resolution is ordered against os.setTimeout by the same event loop. The resolver is stored in the timer table, where the collector already scans it.

Source

pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value>

PromiseResolve(value): the value itself when it is already a promise, otherwise a new promise resolved with it.

Source

pub fn resolve_promise_with( &mut self, promise: &Gc<JsObject>, value: Value, ) -> JsResult<()>

ResolvePromise: fulfil, unless the value is a thenable — then follow it.

Source

pub fn perform_then( &mut self, promise: &Gc<JsObject>, on_fulfilled: Option<Value>, on_rejected: Option<Value>, ) -> JsResult<Value>

Promise.prototype.then: register a reaction and answer the derived promise.

Source

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

The rejections nobody listened to, formatted the way the reference reports them.

Each line is Possibly unhandled promise rejection: <value> followed by the stack when there is one. The adjective is the reference’s: a rejection is only possibly unhandled at the point the queue drains, because a then may still be attached before the host acts on it.

Source

pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value>

Run the microtask queue to exhaustion.

Jobs queued while draining run in the same drain, FIFO, which is what makes Promise.resolve().then(f).then(g) call f before g. Parse text in the extended dialect that std.parseExtJSON exposes.

Comments, unquoted keys, single quotes, trailing commas, + and .1 numbers, Infinity/NaN, and 0x/0o/0b literals — the same relaxations the reference gates behind JS_PARSE_JSON_EXT. JSON.parse does not see any of them.

Source

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

Schedule callback to run after delay_ms milliseconds, returning its id.

A negative or NaN delay runs as soon as possible rather than being rejected: the reference passes the delay through JS_ToInt64, so setTimeout(f, NaN) schedules immediately, and setTimeout(f, -1) is ordinary code.

The callback is called with no arguments. The reference stores only the function (th->func = JS_DupValue(ctx, func)) and calls it bare, so the setTimeout(f, 0, a, b) passthrough that browsers offer does not exist here — verified against qjs: extra arguments arrive as undefined.

Source

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

Cancel a pending timer. false when the id is unknown or already fired, which is not an error — clearTimeout on a stale id is a no-op in the reference too.

Source

pub fn next_timeout(&self) -> Option<Duration>

How long until the earliest pending timer, or None when none is pending.

Source

pub fn run_one_turn(&mut self) -> JsResult<Turn>

Run one turn of the event loop.

Structurally this is js_std_loop’s body minus the blocking: drain microtasks, then run at most one due timer, then drain again. The blocking belongs to the caller because quickjs-pure has no dependencies and no platform knowledge — Turn::Wait is how it asks.

One timer per turn rather than all of them: a timer callback may schedule another timer, and running the whole batch would let a self-rescheduling setTimeout(f, 0) starve the microtask queue.

Source

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

Register or clear one direction of an os.setReadHandler/os.setWriteHandler pair.

callback of None unregisters that direction, and an entry with neither direction left is removed — the reference does the same, so a script can rely on os.setReadHandler(fd, null) stopping the loop from waiting on that descriptor.

Source

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

Register or clear an os.signal handler.

None removes it; the host separately restores the default disposition or sets ignore, because which of those happened is the script’s choice (null versus undefined) and not something this table can express.

Source

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

Run the handler for signal, reporting whether one ran.

A throwing handler is reported and the loop continues, like a timer’s.

Source

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

The descriptors the host has to poll, and in which direction.

Empty means the loop has nothing to wait for on any descriptor. The host turns each entry into a pollfd with POLLIN/POLLOUT — the same events the reference’s os_poll asks for.

Source

pub fn fire_fd( &mut self, fd: i32, readable: bool, writable: bool, ) -> JsResult<bool>

Call the handler registered for fd, reporting whether one ran.

readable/writable come from poll(2). The reference calls one handler per poll iteration and then restarts the loop, because the handler may have changed the registration list underneath it; doing the same here keeps a handler that unregisters itself from being called with stale state.

A throwing handler is reported and the loop continues — a bad handler must not stop every later one, exactly as with timers.

Source

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

Take the errors timer callbacks threw, leaving the list empty.

Source

pub fn has_pending_work(&self) -> bool

Whether anything is still pending: a microtask or a timer.

Source

pub fn has_pending_timers_or_jobs(&self) -> bool

Whether a timer or a microtask is pending, ignoring descriptor handlers.

Source

pub fn drain_jobs(&mut self) -> JsResult<()>

Run every queued microtask, including ones queued while draining.

Source

pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, FinalizationState)>

Every live FinalizationRegistry, as (handle, state) pairs.

The registry list is weak, so a registry the script dropped answers upgrade with None and is swept out here. This is also where the realm learns that a registry died, which is why it is a mutation rather than a read.

Source

pub fn new_async_function( &mut self, function: Value, this: Value, args: Vec<Value>, ) -> JsResult<Value>

Build an async function’s result: a promise whose body runs as a coroutine.

Source

pub fn run_async_body( &mut self, code: Gc<CompiledCode>, env: Gc<ClosureEnv>, this: Value, ) -> JsResult<Value>

The coroutine an async body runs in.

Generator-shaped and never exposed to the script: what makes await work is the same frame-detach-and-resume the generator protocol uses, so this reuses it rather than growing a second state machine. The difference is only in the ending — a return fulfils the caller’s promise here instead of producing {value, done}. Run code as an async function body, answering the promise it settles.

Used for a module with top-level await: its body is an async function whose caller is the host, so there is no function object to pass through Interp::new_async_function.

Source

pub fn object_get_own_property( &mut self, object: &Gc<JsObject>, key: &PropertyKey, ) -> JsResult<Option<Property>>

[[GetOwnProperty]], with the getOwnPropertyDescriptor trap when there is one.

Source

pub fn object_define_own_property( &mut self, object: &Gc<JsObject>, key: &PropertyKey, property: Property, ) -> JsResult<bool>

[[DefineOwnProperty]], with the defineProperty trap when there is one.

Source

pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject>

Build a proxy object over target, with its traps read from handler.

Source

pub fn new_revoker(&self, slots: ProxyRef) -> Gc<JsObject>

The revoke function for a proxy’s slots.

Source

pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject>

A new array.

Source

pub fn new_native_ctor( &self, name: impl Into<String>, length: u32, func: NativeFn, ) -> Gc<JsObject>

A new native function object.

The observable name and length are installed as properties here, which is what Function.prototype.name and .length read; nothing else stores them, so f.name = "x" behaves like the writable property it is. A native constructor that builds its own instance after validating its arguments.

new hands it this = undefined rather than a pre-made object, so any argument check runs before new.target.prototype is read.

Source

pub fn new_native_constructor( &self, name: impl Into<String>, length: u32, func: NativeFn, ) -> Gc<JsObject>

A native constructor that lets new build the instance first.

The ordinary case for a built-in constructor: new Array(3) has no argument validation that must precede reading new.target.prototype, so the object can be created before the implementation runs. Distinct from Interp::new_native, which makes a method and therefore not a constructor at all.

Source

pub fn new_host_function( &self, name: impl Into<String>, length: u32, func: HostFn, ) -> Gc<JsObject>

A new host function object: a native closure that carries its own state.

Same observable surface as Interp::new_native — name, length and, for a constructor, prototype — but the body is a closure, so it can hold an open-file table or a timer queue. See crate::object::HostFn for the one rule that makes this safe: the closure must not capture a Gc.

Source

pub fn new_host_ctor( &self, name: impl Into<String>, length: u32, func: HostFn, ) -> Gc<JsObject>

A host constructor: new hands it this = undefined, so it validates its arguments before building an instance, exactly like Interp::new_native_ctor.

Source

pub fn new_native( &self, name: impl Into<String>, length: u32, func: NativeFn, ) -> Gc<JsObject>

A new native function object.

Source

pub fn new_bound( &self, target: Value, this: Value, args: Vec<Value>, ) -> Gc<JsObject>

A new bound function.

Source

pub fn new_cell(&self, value: Value) -> Gc<Cell>

A new reference cell.

Source

pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value>

Evaluate code as a script body and return its completion value. Compile and run source for the engine’s own use, returning its completion value.

This is how a builtin can be written in JavaScript: [crate::builtins::from_async] needs to be a real async function, and the engine already runs those as coroutines, so compiling the algorithm is cheaper than rebuilding a coroutine by hand.

Differences from Self::eval_in_global, both deliberate:

  • It does not drain the microtask queue. Install runs while the realm is still being built, and the source is an IIFE that only constructs a closure, so there is nothing to drain — and draining here would run script-queued jobs in the middle of install.
  • It reports a syntax error as an InternalError throw rather than as the usual SyntaxError with a position: a malformed builtin source is this crate’s bug, and it should not look like the user wrote something wrong.
Source

pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value>

Run an already-parsed script and drain the microtasks it queued.

The drain is what lets an async function’s body advance past its first await before the host sees the result: nothing else pumps the job queue.

Source

pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value>

Compile and run source in global scope, returning its completion value.

This is what eval and new Function use. Running it as a script means it sees the global object and nothing else, which is right for eval("1+1") and for a Function body; a direct eval that reads a local variable would need the compiler to hand its variable environment over, which is not implemented.

Source

pub fn eval_script_in_global( &mut self, source: &str, barrier: bool, ) -> JsResult<Value>

std.evalScript(source): the same evaluation, reported under its own file name.

The reference names the two separately — eval shows <input>, std.evalScript shows <evalScript> — and the name is visible in every stack trace that passes through the code, so they cannot share one constant.

Source

pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value>

Run a compiled script whose completion value is a function, returning it.

new Function(...) compiles (function(params) { body }) and this runs it to get the closure out, which keeps the constant-pool plumbing in one place.

Source

pub fn reserve(&mut self, payload: usize) -> JsResult<()>

Fail before allocating payload bytes, if they would not fit.

For the allocations whose size comes from script data — new Array(n), 'x'.repeat(n), new Uint8Array(n) — a checkpoint is too late: the request itself is what takes the machine down. The reference has the same shape, with js_malloc answering NULL for the one big request.

Source

pub fn stack_used(&self) -> usize

Bytes of frame state the live call chain accounts for.

Source

pub fn current_strict(&self) -> bool

Whether the code currently running is strict.

Read off the frame’s function, which is where the parser’s answer ended up; a native function never runs strict-only checks, and there is no frame at all before the first script.

Source

pub fn get_property( &mut self, object: &Gc<JsObject>, key: &str, ) -> JsResult<Option<Value>>

Read object[key], following the prototype chain.

An inherited accessor runs with the receiver as this, which is why the lookup returns the owner rather than just the value.

Source

pub fn get_property_key( &mut self, object: &Gc<JsObject>, key: &PropertyKey, ) -> JsResult<Option<Value>>

Interp::get_property with a key that may be a symbol.

Source

pub fn get_property_key_for( &mut self, object: &Gc<JsObject>, receiver: Option<&Value>, key: &PropertyKey, ) -> JsResult<Option<Value>>

Interp::get_property_key, with an explicit this for an inherited accessor.

The receiver matters when the property is found on a prototype: a getter has to see the object the read started from. For a primitive that is the primitive itself — Symbol("x").description runs the getter with the symbol as this, not with Symbol.prototype — which is why the receiver cannot be inferred from the owner.

Source

pub fn set_property( &mut self, object: &Gc<JsObject>, key: &str, value: Value, ) -> JsResult<()>

Store object[key] = value, honouring setters and inherited properties.

Source

pub fn set_property_with( &mut self, object: &Gc<JsObject>, key: &str, value: Value, on_failure: DeleteFailure, ) -> JsResult<()>

Store a property, choosing what to do when the object refuses.

A rejected store is a TypeError in strict mode and a silent no-op in sloppy mode, which is the one place assignment differs by mode. Native code (the array methods, JSON) always asks for the throw.

Source

pub fn set_property_with_key( &mut self, object: &Gc<JsObject>, key: &PropertyKey, value: Value, on_failure: DeleteFailure, ) -> JsResult<()>

Interp::set_property_with with a key that may be a symbol.

Source

pub fn delete_property( &mut self, object: &Gc<JsObject>, key: &str, ) -> JsResult<bool>

Delete object[key].

Source

pub fn delete_property_key( &mut self, object: &Gc<JsObject>, key: &PropertyKey, ) -> JsResult<bool>

Interp::delete_property with a key that may be a symbol.

Source

pub fn call_value( &mut self, callee: Value, this: Value, args: Vec<Value>, ) -> JsResult<Value>

Call callee with this and args.

Source

pub fn using_method_for( &mut self, value: &Value, await_form: bool, ) -> JsResult<Value>

The dispose method a using declaration should snapshot, or an error.

await-using prefers Symbol.asyncDispose and falls back to Symbol.dispose, which is what makes a resource that only knows the synchronous protocol usable in both forms.

Source

pub fn merge_dispose_error( &mut self, new_error: Value, error_state: Value, ) -> Value

Combine a disposal failure with whatever was already going wrong.

Source

pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value

A SuppressedError instance built straight from its prototype.

Not through the constructor: a script that rewrites SuppressedError.prototype.constructor must not be able to divert the engine’s own error wrapping.

Source

pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>>

Call callee, or push its frame and let the main loop run it.

This is what keeps deep JavaScript recursion off the Rust stack: a bytecode callee becomes a frame on Interp::frames and the instruction loop simply continues, so function f(){ return f() } costs heap and stops at Interp::max_frames instead of aborting the process. Only a native callee is entered directly, and natives do not re-enter JavaScript in this milestone.

Ok(None) means a frame was pushed: the caller must not push a result, because the returning frame will. The elements of an array-like value, as a call argument list.

apply accepts any array-like, not only a real array: the reference reads length and then each index, so {length: 2, 0: "a", 1: "b"} works too.

Source

pub fn new_generator( &mut self, function: Value, this: Value, args: Vec<Value>, ) -> JsResult<Value>

Turn a call to a generator function into a generator object.

The frame is built exactly as an ordinary call would build it, then detached and stored in the generator before any body instruction runs — which is what makes function* g(){ sideEffect() } inert until next(). The one thing that does run is initial_yield, the first instruction of every suspending body.

Source

pub fn resume_generator( &mut self, generator: &Gc<JsObject>, kind: ResumeKind, value: Value, ) -> JsResult<Value>

Advance a generator object, as %GeneratorPrototype%.next and friends do.

Returns the {value, done} object itself rather than the pair, because a yield* suspension already has one — the inner iterator’s own result — and the protocol says to hand that straight through rather than nest it.

Source

pub fn resume_async_generator( &mut self, generator: &Gc<JsObject>, kind: ResumeKind, value: Value, ) -> JsResult<Value>

next/return/throw on an async generator, which answer a promise.

The body is the same coroutine a sync generator runs; what changes is that an await inside it has to settle before the method can answer, so the step is driven off the job queue rather than returning inline.

Source

pub fn dispose_async_all( &mut self, resources: Vec<(Value, Value)>, ) -> JsResult<Value>

Dispose a list of (resource, disposeMethod) pairs, awaiting each disposer.

Returns the promise AsyncDisposableStack.disposeAsync hands back. The first disposer runs synchronously — the reference starts it before returning, which a test can observe by logging after the call — and the rest follow once their predecessor settles.

Source

pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value>

The {value, done} object an iterator method answers with.

Source

pub fn construct( &mut self, callee: Value, new_target: Value, args: Vec<Value>, ) -> JsResult<Value>

new callee(args).

A constructor differs from a plain call in three ways: it gets a fresh object as this whose prototype is the constructor’s prototype property, its return value is replaced by that object unless it returns an object itself, and a native constructor is expected to initialise the object it is given rather than build one.

Source

pub fn make_error(&self, name: &str, message: &str) -> Value

A TypeError/ReferenceError/RangeError object, as the value to throw.

The error classes themselves arrive with the builtins milestone; what matters here is that the thrown value stringifies the way a script printing the caught value expects.

Source

pub fn add_stack(&self, object: &Gc<JsObject>)

Give an error object its stack property, from the current frame stack.

Only objects get one — throw 42 has no stack anywhere — and an object that already has a stack keeps it, so an error caught and rethrown, or one whose stack a script set, is not rewritten.

Source

pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize)

Interp::add_stack, omitting the skip innermost frames.

An Error constructor passes 1: the reference builds those traces with JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL, so new Error() does not report the constructor itself, while a RangeError raised inside toISOString does report at toISOString (native).

Source

pub fn current_callee(&self) -> Option<Gc<JsObject>>

The function object currently being called, if any.

A native function is a bare fn pointer, so it cannot capture which class it belongs to; it reads that from the callee instead. This is also what a stack trace would use.

Source

pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject>

The prototype property of a constructor, falling back to Object.prototype for anything that is not shaped like one.

Source

pub fn type_error(&self, message: impl AsRef<str>) -> Signal

Throw a TypeError carrying message.

Source

pub fn range_error(&self, message: impl AsRef<str>) -> Signal

Throw a RangeError carrying message.

Source

pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value>

ToPrimitive, which is what makes "" + obj produce obj.toString().

The order depends on the hint: the “number” order tries valueOf first and toString second, the “string” order the other way round, and the default hint uses the number order. A result that is still an object is a TypeError, because no built-in valueOf/toString returns one.

Source

pub fn to_js_string(&mut self, value: &Value) -> JsResult<String>

ToString with the object case going through ToPrimitive.

Source

pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<Wtf8>

ToString that keeps the string’s code units instead of flattening them.

This is what + needs: String.fromCharCode(0xD800) + "a" must keep the unpaired surrogate, and a lossy String in between would turn it into U+FFFD.

Source

pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64>

ToNumber with the object case going through ToPrimitive.

Source

pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey>

ToPropertyKey: what a computed member access uses as its key.

A symbol is returned as itself, never stringified — that is what keeps o[sym] and o["Symbol(a)"] apart. Everything else becomes its string form.

Source

pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value>

Read object[key], returning undefined when the property is missing.

Unlike Interp::get_property this takes a runtime Value, so it works on a primitive (looking through its prototype) as well as an object — which is what get_field/get_array_el need and what a builtin reading a property off an argument needs too.

Source

pub fn read_field_cached( &mut self, object: &Value, key: &PropertyKey, slot: usize, ) -> JsResult<Value>

Interp::read_field with a key that may be a symbol.

A symbol key never reaches the string shortcuts: a string’s length and its indices are string properties, and a symbol named length is a different property that a string primitive cannot have. Interp::read_field_key, with an inline cache in front of it.

Only own data properties of ordinary objects are cached. Everything else — a prototype hit, a getter, a proxy, a string primitive, a missing property — goes straight through, because those are the cases whose answer depends on more than “the object and the name”, and caching them would need the shape machinery this engine deliberately does not have.

A hit is re-validated: the object must still be the same one (weakly, so a collected and reallocated object is a miss, not a wrong answer) and the property table must still have this key at this index as a plain value.

Source

pub fn read_field_key( &mut self, object: &Value, key: &PropertyKey, ) -> JsResult<Value>

Read key from object, without the inline cache.

Use Interp::read_field_cached from an opcode handler: this one always walks the prototype chain, while the cached form answers an own data property from memory.

Source

pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String>

ToString, as the spec defines it: a symbol is a TypeError.

Value::to_js_string cannot fail, so it answers the descriptive form for a symbol. That is right for String(sym) and for error messages, and wrong for everything the spec routes through ToString — "" + sym, ${sym}, Number.parseInt(sym) — so those callers use this instead.

Source

pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey>

ToPropertyKey for a builtin that takes a key argument.

Fallible: a key whose toString throws has to propagate that error, both for Reflect.get({}, {toString(){ throw 1 }}) (return-abrupt-from-property-key) and for a template substitution. This used to answer "[object Object]" on a throw, which made `${o}` and the like carry on with a value nobody asked for.

Source

pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32>

ToUint32 with ArraySetLength’s refusal, for an array’s length.

ToUint32 is ToNumber then the modulo, but an object that yields a fraction or NaN falls through to ToString and is parsed as decimal digits. That is why {toString: () => "2"} is a legal length while {valueOf: () => 2.5} is a RangeError — and why this cannot be a plain ToNumber.

Source

pub fn key_value(&self, key: &PropertyKey) -> Value

A PropertyKey as the Value a script sees — what Reflect.ownKeys and Object.getOwnPropertySymbols put in their result array.

Source

pub fn object_prototype_of( &mut self, object: &Gc<JsObject>, ) -> JsResult<Option<Gc<JsObject>>>

[[GetPrototypeOf]], with the proxy trap when there is one.

Source

pub fn object_set_prototype_of( &mut self, object: &Gc<JsObject>, proto: Option<Gc<JsObject>>, ) -> JsResult<bool>

[[SetPrototypeOf]], with the proxy trap when there is one.

Source

pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool>

[[IsExtensible]], with the proxy trap when there is one.

Source

pub fn object_prevent_extensions( &mut self, object: &Gc<JsObject>, ) -> JsResult<bool>

[[PreventExtensions]], with the proxy trap when there is one.

Source

pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool>

The iterator for for-of: the object and its next method.

An object that already carries a next method is used as it is — that is what arr.values() returns — and only arrays and strings get the built-in sequence iterator. Whether value has a callable Symbol.iterator, i.e. GetMethod succeeds.

Callers that must choose between the iterable and the array-like protocol — the typed-array constructor is the main one — need to ask before committing to one.

Source

pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>>

Collect everything an iterable yields, closing it if the walk is abandoned.

The cap is a guard against a generator that never ends: an unbounded collect would be an out-of-memory abort rather than a catchable error.

Source

pub fn new_ctor_instance( &mut self, default_proto: Gc<JsObject>, ) -> JsResult<Gc<JsObject>>

OrdinaryCreateFromConstructor(new.target, default_proto).

A native constructor calls this once it has validated its arguments, which is the order the spec uses for Promise, the typed arrays and DataView: a bad argument is a TypeError before new.target.prototype is read, so a throwing getter there is never reached. The prototype comes from new.target when it is an object, and from default_proto otherwise.

Source

pub fn current_native(&self) -> Option<Gc<JsObject>>

Whether this call is a construction, i.e. new.target is defined.

A native constructor receives this = undefined (it builds its own instance), so it cannot use “this is not an object” to tell Ctor() from new Ctor() — this can. The native function currently executing, if any.

Source

pub fn is_constructing(&self) -> bool

Whether this call is a construction, i.e. new.target is defined.

Source

pub fn not_a_constructor_error(&mut self) -> Signal

The TypeError a constructor too primitive to have a wrapper raises.

BigInt and Symbol are constructors as far as [[Construct]] is concerned — the reference creates both with JS_CFUNC_constructor_or_func — and the refusal happens inside the native function, which is why the trace carries an at BigInt (native) frame. The message names new.target, not the callee: a class B extends BigInt {} constructed as new B(1) reports B is not a constructor, and an unnamed one reports the leading space of " is not a constructor" because the reference formats the empty name as it is.

It is also the answer for a new.target that cannot be named at all — not a function, or a throwing name getter — where the reference falls back to the bare not a constructor.

Source

pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal

The same TypeError for an explicit target, for the callers that check IsConstructor themselves — Reflect.construct does, on its third argument.

Source

pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool

Whether the pending new.target needs its own prototype honoured by the constructor.

True whenever new.target is not the callee itself, or when it has no usable prototype — the cases where reading the property is observable at all.

Source

pub fn internal_slot(&self, name: &'static str) -> PropertyKey

The symbol key for one of the engine’s own hidden slots.

Cached on the realm, so every object of a kind shares one key and a slot can be read back by name.

Source

pub fn internal_get( &self, object: &Gc<JsObject>, name: &'static str, ) -> Option<Value>

Read a hidden slot, or None when the object has none of that name.

Source

pub fn internal_set( &self, object: &Gc<JsObject>, name: &'static str, value: Value, )

Define a hidden slot.

Source

pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>>

Drain anything with a Symbol.iterator method, or answer None when the value is not iterable.

Shared so that Array.from, the Promise combinators and for…of all agree on what “iterable” means. A Map and a Set have no length, so an array-like-only reader silently produced an empty array for both — Array.from(new Set([1,2])) was [].

Source

pub fn describe_exception(&mut self, value: &Value) -> String

How an uncaught exception is reported.

The reference reports a pending exception with JS_PrintValue, the printer, not with ToString — js_std_dump_error is three lines that end in JS_PrintValue(stderr, …). The difference is visible for every value that is not already a string: throw "s" prints with its quotes, throw {a:1} prints { a: 1 }, throw [1,2] prints [ 1, 2 ], and an error prints its stack.

ToString was the wrong primitive here — it is what error.message is for, not what a reporter is for. An earlier note claimed JS_PrintValue “ends up calling toString”; it does call it, but only for objects of a class it does not know how to walk, and never for errors, arrays or plain objects.

A printer that fails must not take the reporter down with it, so that case falls back to the ToString rendering.

Source

pub fn script_or_module_name(&self) -> Option<String>

The file name of whatever is running, innermost frame first.

The reference’s JS_GetScriptOrModuleName(ctx, 0): it walks the stack and returns the innermost frame’s file name, without distinguishing a module body from a plain script. import() uses it as the base for a relative specifier, which is why import('./x.js') inside a script resolves next to the script and not next to the process’s working directory.

Source

pub fn stack_trace(&self) -> String

The current call stack, formatted the way qjs prints error.stack.

One at name (file:line:col) line per active frame, innermost first. The position is the one recorded for the instruction each frame is stopped on, which is why the compiler builds a pc-to-position table per function: without it a trace could only name the function, not the line inside it.

A frame whose code has no positions prints just (file), matching the reference’s output for stripped bytecode.

Source

pub fn declare_var_global(&mut self, name: &str)

Declare a global binding, creating its reference cell. Declare a var or function global, whose home is the global object.

Writable and enumerable but not configurable: globalThis.v reads it, for-in lists it, delete refuses. A name that is already there — a built-in such as print, or a redeclaration — is left alone.

Source

pub fn declare_global(&mut self, name: &str, is_const: bool)

Declare a lexical global binding, which starts in its dead zone.

Only let/const/class need this: a var global is a property of the global object and is created when its initialiser runs.

Source§

impl<'a> Interp<'a>

Source

pub fn module_registry(&self) -> &BTreeMap<String, Gc<ModuleRecord>>

The module registry: one entry per canonical name, so each file is compiled once.

Source

pub fn run_main_module(&mut self, specifier: &str) -> JsResult<Value>

Evaluate specifier as the entry module, the way qjs -m file.js does.

Source

pub fn run_precompiled_module( &mut self, code: CompiledFunction, ) -> JsResult<Value>

Run a module whose bytecode the caller already has.

This is qjs’s -m for an AOT binary: nothing is parsed or compiled, but the module’s requests still go through the host loader, so a precompiled entry module can import ordinary source files. The blob’s own file name is what those requests are resolved against, which is why it has to travel in the blob rather than be supplied at the call site.

Source

pub fn register_module(&mut self, code: CompiledFunction) -> JsResult<String>

Register a module from bytecode, so a later import finds it without a loader.

This is what an AOT product does with the modules it carries: the names are the ones the bundler resolved, which are the ones this interpreter would have resolved through the loader, so an import "./dep.js" lands here instead of on the filesystem.

The module is registered as Unlinked: nothing is wired up until something imports it (or it is the entry), which is what keeps a bundle’s registration order irrelevant — a cycle among precompiled modules links the same way a cycle among source files does.

Source

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

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

A data module is a value, not code, so it has no bytecode to carry: the bundle keeps the file’s bytes and the product hands them here. attributes is what decided the kind at bundle time, and passing it again keeps the two ends from disagreeing about a .json file imported as text.

Source

pub fn load_module( &mut self, specifier: &str, attributes: &[(String, String)], referrer: &str, ) -> JsResult<Gc<ModuleRecord>>

Load and compile one module.

Resolve every import of module and validate its exports, depth-first.

Source

pub fn resolve_export( &mut self, module: &Gc<ModuleRecord>, name: &str, ) -> JsResult<Gc<Cell>>

The cell behind name in module, following re-exports.

Source

pub fn module_export_names( &mut self, module: &Gc<ModuleRecord>, ) -> JsResult<Vec<String>>

The names module exports, sorted the way §16.2.1.6 requires.

Source

pub fn module_namespace(&mut self, module: &Gc<ModuleRecord>) -> JsResult<Value>

The namespace object of module, built on first use.

An ordinary object with one read-only getter per export, inserted in sorted order. The getter reads the cell, which is what makes the binding live: export let x followed by x = 1 in the exporting module is visible here without copying.

Source

pub fn evaluate_module_body( &mut self, module: &Gc<ModuleRecord>, ) -> JsResult<()>

Run module’s body, evaluating its dependencies first.

Post-order, once each: a module already evaluated is skipped, which is what §16.2.1.5.2.2’s “evaluated or evaluating” guard amounts to, and what makes a cycle terminate instead of recursing.

Source

pub fn dynamic_import(&mut self, specifier: Value) -> JsResult<Value>

import(specifier): load, link, evaluate — asynchronously.

The work happens in a job, because §13.3.10.1 makes dynamic import settle through the promise machinery: import("x").then(f) must call f after the current script finishes, never inside the import expression.

Source

pub fn run_dynamic_import( &mut self, specifier: &str, referrer: &str, promise: &Gc<JsObject>, )

Evaluate a pending dynamic import and settle its promise.

Auto Trait Implementations§

§

impl<'a> !Freeze for Interp<'a>

§

impl<'a> !RefUnwindSafe for Interp<'a>

§

impl<'a> !Send for Interp<'a>

§

impl<'a> !Sync for Interp<'a>

§

impl<'a> !UnwindSafe for Interp<'a>

§

impl<'a> Forget for Interp<'a>

§

impl<'a> Move for Interp<'a>

§

impl<'a> Unpin for Interp<'a>
where &'a 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, Rc<[u8]>: 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<'a> UnsafeUnpin for Interp<'a>
where &'a 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<Option<FieldCache>>: 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.