Interpreter

Struct Interpreter 

Source
pub struct Interpreter {
Show 26 fields pub heap: Heap<JsObject>, pub global: Gc<JsObject>, pub global_env: EnvRef, pub env: EnvRef, pub string_dict: StringDict, pub object_prototype: Gc<JsObject>, pub array_prototype: Gc<JsObject>, pub function_prototype: Gc<JsObject>, pub string_prototype: Gc<JsObject>, pub number_prototype: Gc<JsObject>, pub boolean_prototype: Gc<JsObject>, pub regexp_prototype: Gc<JsObject>, pub map_prototype: Gc<JsObject>, pub set_prototype: Gc<JsObject>, pub date_prototype: Gc<JsObject>, pub symbol_prototype: Gc<JsObject>, pub promise_prototype: Gc<JsObject>, pub generator_prototype: Gc<JsObject>, pub error_prototype: Gc<JsObject>, pub type_error_prototype: Gc<JsObject>, pub reference_error_prototype: Gc<JsObject>, pub range_error_prototype: Gc<JsObject>, pub syntax_error_prototype: Gc<JsObject>, pub exports: FxHashMap<JsString, ModuleExport>, pub call_stack: Vec<StackFrame>, pub well_known_symbols: WellKnownSymbols, /* private fields */
}
Expand description

The interpreter state

Fields§

§heap: Heap<JsObject>

The GC heap managing all objects

§global: Gc<JsObject>

Global object

§global_env: EnvRef

Global environment (variable bindings for global scope)

§env: EnvRef

Current execution environment

§string_dict: StringDict

String dictionary for interning strings

§object_prototype: Gc<JsObject>

Object.prototype

§array_prototype: Gc<JsObject>

Array.prototype

§function_prototype: Gc<JsObject>

Function.prototype

§string_prototype: Gc<JsObject>

String.prototype (for string primitive methods)

§number_prototype: Gc<JsObject>

Number.prototype (for number primitive methods)

§boolean_prototype: Gc<JsObject>

Boolean.prototype (for boolean primitive methods)

§regexp_prototype: Gc<JsObject>

RegExp.prototype (for regexp methods)

§map_prototype: Gc<JsObject>

Map.prototype (for Map methods)

§set_prototype: Gc<JsObject>

Set.prototype (for Set methods)

§date_prototype: Gc<JsObject>

Date.prototype (for Date methods)

§symbol_prototype: Gc<JsObject>

Symbol.prototype (for Symbol methods)

§promise_prototype: Gc<JsObject>

Promise.prototype (for Promise methods)

§generator_prototype: Gc<JsObject>

Generator.prototype (for generator methods)

§error_prototype: Gc<JsObject>

Error.prototype

§type_error_prototype: Gc<JsObject>

TypeError.prototype

§reference_error_prototype: Gc<JsObject>

ReferenceError.prototype

§range_error_prototype: Gc<JsObject>

RangeError.prototype

§syntax_error_prototype: Gc<JsObject>

SyntaxError.prototype

§exports: FxHashMap<JsString, ModuleExport>

Exported values from the module Uses ModuleExport to distinguish direct exports (with live bindings) from re-exports

§call_stack: Vec<StackFrame>

Call stack for stack traces

§well_known_symbols: WellKnownSymbols

Well-known symbols (Symbol.iterator, Symbol.toStringTag, etc.)

Implementations§

Source§

impl Interpreter

Source

pub fn new() -> Self

Create a new interpreter instance

Source

pub fn call_depth(&self) -> usize

Get the current call stack depth.

Returns the total depth combining the interpreter’s call stack and the active VM’s trampoline stack (if any).

Source

pub fn next_symbol_id(&mut self) -> u64

Generate a unique symbol ID

Source

pub fn symbol_registry_get(&self, key: &JsString) -> Option<JsSymbol>

Get a symbol from the registry by key (for Symbol.for)

Source

pub fn symbol_registry_insert(&mut self, key: JsString, symbol: JsSymbol)

Insert a symbol into the registry (for Symbol.for)

Source

pub fn symbol_registry_key_for(&self, symbol_id: u64) -> Option<JsString>

Find the key for a registered symbol (for Symbol.keyFor)

Source

pub fn console_timer_start(&mut self, label: String)

Start a console timer

Source

pub fn console_timer_end(&mut self, label: &str) -> Option<u128>

End a console timer and return elapsed milliseconds, or None if timer doesn’t exist

Source

pub fn console_counter_increment(&mut self, label: String) -> u64

Increment a console counter and return the new count

Source

pub fn console_counter_reset(&mut self, label: &str)

Reset a console counter

Source

pub fn register_internal_module(&mut self, module: InternalModule)

Register an internal module for import

Source

pub fn is_internal_module(&self, specifier: &str) -> bool

Check if a specifier is an internal module

Source

pub fn eval( &mut self, source: &str, module_path: Option<ModulePath>, ) -> Result<StepResult, JsError>

Evaluate TypeScript/JavaScript code with full runtime support.

The optional module_path is used as the base for resolving relative imports. For example, if module_path is /project/src/main.ts and the code contains import { foo } from "./utils", it will resolve to /project/src/utils.

If no path is provided, relative imports will be treated as bare specifiers.

Returns StepResult which may indicate:

  • Complete: execution finished with a value
  • NeedImports: modules need to be provided before continuing
  • Suspended: waiting for orders to be fulfilled
Source

pub fn step(&mut self) -> Result<StepResult, JsError>

Execute a single bytecode instruction.

Returns StepResult::Continue if more instructions remain, or a terminal result if execution completed or needs input.

Call prepare() to set up execution before using step().

Source

pub fn prepare( &mut self, source: &str, module_path: Option<ModulePath>, ) -> Result<StepResult, JsError>

Prepare code for step-based execution without running it.

After calling this, use step() to execute one instruction at a time. Returns Ok(()) if setup succeeded, or an error if parsing/compilation failed or if imports are needed.

Source

pub fn provide_module( &mut self, resolved_path: ModulePath, source: &str, ) -> Result<(), JsError>

Provide a module source for a pending import.

The resolved_path should be the normalized path from ImportRequest.resolved_path. The module is parsed and stored, but not executed until continue_eval is called. This allows collecting all needed imports before execution.

Source

pub fn fulfill_orders(&mut self, responses: Vec<OrderResponse>)

Fulfill orders with responses from the host

Stores responses for later consumption when VM resumes via step(). The response value becomes the return value of order().

Source

pub fn resolve_module_specifier(&self, specifier: &str) -> ModulePath

Resolve a module specifier to a normalized path.

Uses the current module path (or main module path) as the base for resolving relative imports like ./foo or ../bar.

Source

pub fn env_define(&mut self, name: JsString, value: JsValue, mutable: bool)

Define a variable in the current environment

Source

pub fn env_define_import( &mut self, name: JsString, module_obj: Gc<JsObject>, property_key: PropertyKey, )

Define an import binding in the current environment (for live bindings)

Source

pub fn env_get(&self, name: &JsString) -> Result<JsValue, JsError>

Get a variable from the environment chain

Source

pub fn get_export(&self, name: &str) -> Option<JsValue>

Get an exported value from the main module by name.

This resolves the export through the module namespace object, handling live bindings correctly. Returns None if no main module has been evaluated or if the export doesn’t exist.

§Example
// After evaluating: export const processor = { ... }
let processor = interp.get_export("processor");
Source

pub fn get_export_names(&self) -> Vec<String>

Get all export names from the main module.

Returns an empty vector if no main module has been evaluated.

Source

pub fn env_set( &mut self, name: &JsString, value: JsValue, ) -> Result<(), JsError>

Set a variable in the environment chain

Source

pub fn push_scope(&mut self) -> EnvRef

Push a new scope and return the saved environment

Source

pub fn pop_scope(&mut self, saved_env: EnvRef)

Pop scope by restoring saved environment

Source

pub fn push_env_guard(&mut self, guard: Guard<JsObject>)

Push an environment guard (for env changes without push_scope)

Source

pub fn pop_env_guard(&mut self)

Pop an environment guard

Source

pub fn create_object(&mut self, guard: &Guard<JsObject>) -> Gc<JsObject>

Create a new plain object with object_prototype. Caller provides the guard to control object lifetime.

Source

pub fn create_object_raw(&mut self, guard: &Guard<JsObject>) -> Gc<JsObject>

Create a new plain object without prototype. Caller provides the guard to control object lifetime.

Source

pub fn create_object_with_capacity( &mut self, guard: &Guard<JsObject>, capacity: usize, ) -> Gc<JsObject>

Create an object with pre-allocated property capacity. Use this when you know the number of properties upfront to avoid hashmap resizing.

Source

pub fn create_array_from( &mut self, guard: &Guard<JsObject>, elements: Vec<JsValue>, ) -> Gc<JsObject>

Create a new array with elements and array_prototype. Caller provides the guard to control object lifetime.

Source

pub fn create_empty_array(&mut self, guard: &Guard<JsObject>) -> Gc<JsObject>

Create a new empty array with array_prototype. Caller provides the guard to control object lifetime.

Source

pub fn create_native_fn( &mut self, guard: &Guard<JsObject>, name: &str, func: NativeFn, arity: usize, ) -> Gc<JsObject>

Create a native function object. Caller provides the guard to control object lifetime.

Source

pub fn create_bytecode_function( &mut self, guard: &Guard<JsObject>, bc_func: BytecodeFunction, ) -> Gc<JsObject>

Create a bytecode function object. Caller provides the guard to control object lifetime.

Source

pub fn create_bytecode_generator_function( &mut self, guard: &Guard<JsObject>, bc_func: BytecodeFunction, ) -> Gc<JsObject>

Create a bytecode generator function object. Caller provides the guard to control object lifetime.

Source

pub fn create_bytecode_async_function( &mut self, guard: &Guard<JsObject>, bc_func: BytecodeFunction, ) -> Gc<JsObject>

Create a bytecode async function object. Caller provides the guard to control object lifetime.

Source

pub fn create_bytecode_async_generator_function( &mut self, guard: &Guard<JsObject>, bc_func: BytecodeFunction, ) -> Gc<JsObject>

Create a bytecode async generator function object. Caller provides the guard to control object lifetime.

Source

pub fn intern(&mut self, s: &str) -> JsString

Intern a string

Source

pub fn to_js_string(&mut self, value: &JsValue) -> JsString

Convert a JsValue to its string representation using interned strings for common values (undefined, null, true, false).

Source

pub fn type_of(&mut self, value: &JsValue) -> JsString

Get the typeof result for a value as an interned string.

Source

pub fn property_key(&mut self, s: &str) -> PropertyKey

Create a PropertyKey from a string, using interned strings.

Source

pub fn property_key_from_js_string(&mut self, s: JsString) -> PropertyKey

Create a PropertyKey from an already-interned JsString.

Source

pub fn property_key_from_value(&mut self, value: &JsValue) -> PropertyKey

Create a PropertyKey from a JsValue.

Source

pub fn create_native_function( &mut self, name: &str, func: NativeFn, arity: usize, ) -> Gc<JsObject>

Create a native function object, permanently rooted via root_guard. Use this for builtin constructors and methods during initialization. The function is permanently rooted and never collected.

Source

pub fn create_js_function( &mut self, guard: &Guard<JsObject>, func: JsFunction, ) -> Gc<JsObject>

Create a function object from any JsFunction variant. Caller provides the guard to control object lifetime.

Source

pub fn register_method( &mut self, obj: &Gc<JsObject>, name: &str, func: NativeFn, arity: usize, )

Register a method on an object (for builtin initialization). Uses root_guard internally - functions are permanently rooted. Per ECMAScript spec, builtin methods are: writable, non-enumerable, configurable

Source

pub fn register_species_getter(&mut self, constructor: &Gc<JsObject>)

Register Symbol.species getter on a constructor. Per ECMAScript spec, Symbol.species is a getter that returns this. Uses root_guard internally - the getter is permanently rooted. The property is non-enumerable and configurable.

Source

pub fn guard_value(&mut self, value: &JsValue) -> Option<Guard<JsObject>>

Create a guard for a value to prevent it from being garbage collected. Returns Some(guard) if the value is an object, None for primitives.

Use this to guard input values before operations that may trigger GC. The returned guard must be kept alive for the duration needed.

Source

pub fn resume_bytecode_generator( &mut self, gen_state: &Rc<RefCell<BytecodeGeneratorState>>, ) -> Result<Guarded, JsError>

Resume a bytecode generator from a suspended state

Source

pub fn run_bytecode( &mut self, chunk: Rc<BytecodeChunk>, ) -> Result<Guarded, JsError>

Run bytecode using the bytecode VM

This is the bytecode execution entry point. It compiles the program to bytecode and then executes it using the bytecode VM.

Source

pub fn eval_bytecode(&mut self, source: &str) -> Result<JsValue, JsError>

Compile and run source code using bytecode VM

Source

pub fn execute_program_for_eval( &mut self, program: &Program, ) -> Result<JsValue, JsError>

Execute a program (AST) for eval with proper completion value tracking

Source

pub fn execute_program_for_eval_with_this( &mut self, program: &Program, this_value: JsValue, ) -> Result<JsValue, JsError>

Execute a program (AST) for eval with a specific this value

Source

pub fn resolve_module( &mut self, specifier: &str, ) -> Result<Gc<JsObject>, JsError>

Resolve a module specifier to a module namespace object.

The specifier is resolved relative to the current module path before looking up in the loaded modules cache.

Source

pub fn coerce_to_number(&mut self, value: &JsValue) -> Result<f64, JsError>

Convert value to number, handling ToPrimitive for objects (ToNumber abstract operation). This properly calls the object’s valueOf/toString methods per ECMAScript spec.

Source

pub fn coerce_to_string(&mut self, value: &JsValue) -> Result<JsString, JsError>

Convert value to string, handling ToPrimitive for objects (ToString abstract operation). This properly calls the object’s toString/valueOf methods per ECMAScript spec.

Source

pub fn to_object(&mut self, value: JsValue) -> Result<Guarded, JsError>

ToObject abstract operation (ES2015+). Converts primitives to their wrapper objects. Throws TypeError for null/undefined. Returns a Guarded to keep wrapper objects alive until the caller is done with them.

Source

pub fn call_function( &mut self, callee: JsValue, this_value: JsValue, args: &[JsValue], ) -> Result<Guarded, JsError>

Source

pub fn call_function_with_new_target( &mut self, callee: JsValue, this_value: JsValue, args: &[JsValue], new_target: JsValue, ) -> Result<Guarded, JsError>

Call a function with an explicit new.target value (for constructor calls)

Source

pub fn collect_iterator_values( &mut self, value: &JsValue, ) -> Result<Option<Vec<JsValue>>, JsError>

Collect all values from an iterable using the Symbol.iterator protocol. Returns a Vec of values if the object is iterable, or None if it doesn’t have Symbol.iterator. For arrays, this falls back to directly reading array elements for efficiency.

Trait Implementations§

Source§

impl Default for Interpreter

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.