Skip to main content

VirtualMachine

Struct VirtualMachine 

Source
pub struct VirtualMachine {
    pub resource_usage: Option<ResourceUsage>,
    pub metrics: Option<VmMetrics>,
    /* private fields */
}
Expand description

The Shape virtual machine

Fields§

§resource_usage: Option<ResourceUsage>

Optional resource usage tracker for sandboxed execution. When set, the dispatch loop calls tick_instruction() each cycle.

§metrics: Option<VmMetrics>

Optional VM metrics collector. None when VMConfig.metrics_enabled is false (the default), giving zero per-instruction overhead.

Implementations§

Source§

impl VirtualMachine

Source

pub fn execute_function_by_name( &mut self, name: &str, args: Vec<ValueWord>, ctx: Option<&mut ExecutionContext>, ) -> Result<ValueWord, VMError>

Execute a named function with arguments, returning its result.

If the program has module-level bindings, the top-level code is executed first (once) to initialize them before calling the target function.

Source

pub fn execute_function_by_id( &mut self, func_id: u16, args: Vec<ValueWord>, ctx: Option<&mut ExecutionContext>, ) -> Result<ValueWord, VMError>

Execute a function by its ID with positional arguments.

Used by the remote execution system when the caller already knows the function index (e.g., from a RemoteCallRequest.function_id).

Source

pub fn execute_closure( &mut self, function_id: u16, upvalues: Vec<Upvalue>, args: Vec<ValueWord>, ctx: Option<&mut ExecutionContext>, ) -> Result<ValueWord, VMError>

Execute a closure with its captured upvalues and arguments.

Used by the remote execution system to run closures that were serialized with their captured values.

Source

pub fn execute_function_fast( &mut self, func_id: u16, ctx: Option<&mut ExecutionContext>, ) -> Result<ValueWord, VMError>

Fast function execution for hot loops (backtesting)

  • Uses pre-computed function ID (no name lookup)
  • Uses reset_minimal() for minimum overhead
  • Uses execute_fast() which skips debugging overhead
  • Assumes function doesn’t create GC objects or use exceptions
Source

pub fn execute_function_with_named_args( &mut self, func_id: u16, named_args: &[(String, ValueWord)], ctx: Option<&mut ExecutionContext>, ) -> Result<ValueWord, VMError>

Execute a function with named arguments Maps named args to positional based on function’s param_names

Source

pub fn resume( &mut self, value: ValueWord, ctx: Option<&mut ExecutionContext>, ) -> Result<ExecutionResult, VMError>

Resume execution after a suspension.

The resolved value is pushed onto the stack, and execution continues from where it left off (the IP is already set to the resume point).

Source

pub fn execute_with_async( &mut self, ctx: Option<&mut ExecutionContext>, ) -> Result<ValueWord, VMError>

Execute with automatic async task resolution.

Runs execute_with_suspend in a loop. Each time the VM suspends on a Future { id }, the host resolves the task via the TaskScheduler (synchronously executing the spawned callable inline) and resumes the VM with the result. This continues until execution completes or an unresolvable suspension is encountered.

Source§

impl VirtualMachine

Source

pub fn execute( &mut self, ctx: Option<&mut ExecutionContext>, ) -> Result<ValueWord, VMError>

Execute the loaded program

§Arguments
  • ctx - Optional ExecutionContext for trading operations (rows, indicators, etc.)
Source

pub fn execute_with_suspend( &mut self, ctx: Option<&mut ExecutionContext>, ) -> Result<ExecutionResult, VMError>

Execute the loaded program, returning either a completed value or suspension info.

Unlike execute(), this method distinguishes between completion and suspension, allowing the host to resume execution after resolving a future.

Source§

impl VirtualMachine

Source

pub fn snapshot(&self, store: &SnapshotStore) -> Result<VmSnapshot, VMError>

Create a serializable snapshot of VM state.

Source

pub fn from_snapshot( program: BytecodeProgram, snapshot: &VmSnapshot, store: &SnapshotStore, ) -> Result<Self, VMError>

Restore a VM from a snapshot and bytecode program.

Source§

impl VirtualMachine

Source

pub fn new(config: VMConfig) -> Self

Source

pub fn with_resource_limits(self, limits: ResourceLimits) -> Self

Attach resource limits to this VM. The dispatch loop will enforce them.

Source

pub fn set_interrupt(&mut self, flag: Arc<AtomicU8>)

Set the interrupt flag (shared with Ctrl+C handler).

Source

pub fn enable_time_travel(&mut self, mode: CaptureMode, max_entries: usize)

Enable time-travel debugging with the given capture mode and history limit.

Source

pub fn disable_time_travel(&mut self)

Disable time-travel debugging and discard history.

Source

pub fn enable_tiered_compilation( &mut self, ) -> (Receiver<CompilationRequest>, Sender<CompilationResult>)

Enable tiered compilation for this VM.

Must be called after load_program() so the function count is known. The caller is responsible for spawning a background compilation thread that reads from the request channel and sends results back.

Returns (request_rx, result_tx) that the background thread should use.

Source

pub fn tier_manager(&self) -> Option<&TierManager>

Get a reference to the tier manager, if tiered compilation is enabled.

Source

pub fn feedback_vectors(&self) -> &[Option<FeedbackVector>]

Access the feedback vectors (for JIT compilation).

Source

pub fn program(&self) -> &BytecodeProgram

Get a reference to the loaded program (for external JIT compilation).

Source

pub fn time_travel(&self) -> Option<&TimeTravel>

Get a reference to the time-travel debugger, if enabled.

Source

pub fn time_travel_mut(&mut self) -> Option<&mut TimeTravel>

Get a mutable reference to the time-travel debugger, if enabled.

Source

pub fn module_registry(&self) -> &ModuleExportRegistry

Get a reference to the extension module registry.

Source

pub fn get_function_id(&self, name: &str) -> Option<u16>

Get function ID for fast repeated calls (avoids name lookup in hot loops)

Source§

impl VirtualMachine

Source

pub fn register_stdlib_module(&mut self, module: ModuleExports)

Register a built-in stdlib module into the VM’s module registry. Delegates to register_extension — this is a semantic alias to distinguish VM-native stdlib modules from user-installed extension plugins.

Source

pub fn register_extension(&mut self, module: ModuleExports)

Register an external/user extension module (e.g. loaded from a .so plugin) into the VM’s module registry. Also merges any method intrinsics for fast Object dispatch.

Source

pub fn register_module_fn(&mut self, f: ModuleFn) -> usize

Register a ModuleFn in the table and return its ID (for ValueWord::ModuleFunction).

Source

pub fn populate_module_objects(&mut self)

Populate extension module objects as module_bindings (json, duckdb, etc.). These are used by extension Shape code (e.g., duckdb.query(...)). Call this after load_program().

Source§

impl VirtualMachine

Source

pub fn enable_output_capture(&mut self)

Enable output capture for testing When enabled, print output goes to an internal buffer instead of stdout

Source

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

Get captured output (returns empty vec if capture not enabled)

Source

pub fn clear_captured_output(&mut self)

Clear captured output

Source

pub fn last_error_line(&self) -> Option<u32>

Get the line number of the last error (for LSP integration)

Source

pub fn last_error_file(&self) -> Option<&str>

Get the file path of the last error (for LSP integration)

Source

pub fn take_last_uncaught_exception(&mut self) -> Option<ValueWord>

Take the last uncaught exception payload if present.

Source§

impl VirtualMachine

Source

pub fn load_program(&mut self, program: BytecodeProgram)

Load a program into the VM

Source

pub fn load_linked_program(&mut self, linked: LinkedProgram)

Load a LinkedProgram into the VM, extracting content-addressed metadata directly from the linked function table.

This converts the LinkedProgram into the flat BytecodeProgram layout that the executor expects, then populates function_hashes and function_entry_points from the linked function metadata.

Source

pub fn patch_function( &mut self, fn_id: u16, new_blob: FunctionBlob, ) -> Result<Option<FunctionHash>, String>

Hot-patch a single function in the loaded program with a new blob.

The new blob’s instructions, constants, and strings replace the existing function’s bytecode in-place. The function’s metadata (arity, param names, locals count, etc.) is also updated. The content hash is recorded so that in-flight frames referencing the old hash remain valid (they execute from their saved IP which is now stale, but callers that resolve by function ID will pick up the new code on the next call).

Returns Ok(old_hash) on success (the previous content hash, if any), or Err(msg) if the function ID is out of range.

Source

pub fn load_program_with_permissions( &mut self, program: Program, granted: &PermissionSet, ) -> Result<(), PermissionError>

Load a content-addressed Program with permission checking.

Links the program, checks that total_required_permissions is a subset of granted, and loads normally if the check passes. Returns an error listing the missing permissions if the check fails.

Source

pub fn load_linked_program_with_permissions( &mut self, linked: LinkedProgram, granted: &PermissionSet, ) -> Result<(), PermissionError>

Load a LinkedProgram with permission checking.

Checks that total_required_permissions is a subset of granted, then loads normally. Returns an error listing the missing permissions if the check fails.

Source

pub fn reset(&mut self)

Reset VM state

Source

pub fn reset_stack(&mut self)

Reset stack only (for reusing compiled program across iterations) Keeps program, module_bindings, and GC state intact - only clears execution state

Source

pub fn reset_minimal(&mut self)

Minimal reset for hot loops - only clears essential state Use this when you know the function doesn’t create GC objects or use exceptions

Source

pub fn push_value(&mut self, value: ValueWord)

Push a value onto the stack (public, for testing and host integration)

Source§

impl VirtualMachine

Source

pub fn create_typed_enum( &self, enum_name: &str, variant_name: &str, payload: Vec<ValueWord>, ) -> Option<ValueWord>

Source

pub fn create_typed_enum_nb( &self, enum_name: &str, variant_name: &str, payload: Vec<ValueWord>, ) -> Option<ValueWord>

Create a TypedObject enum value using ValueWord payload directly.

Source

pub fn pop(&mut self) -> Result<ValueWord, VMError>

Pop and materialize a ValueWord from the stack (convenience for tests and legacy callers).

Trait Implementations§

Source§

impl DebuggerIntegration for VirtualMachine

Source§

fn trace_state(&self)

Trace VM state (for debugging)
Source§

fn debug_break(&self)

Trigger a debug break
Source§

fn instruction_pointer(&self) -> usize

Get current instruction pointer
Source§

fn stack_size(&self) -> usize

Get stack size
Source§

fn stack_top(&self) -> Option<ExternalValue>

Get top of stack as ExternalValue (display only)
Source§

fn stack_values_vec(&self) -> Vec<ExternalValue>

Get all stack values as ExternalValues (display only)
Source§

fn call_stack_depth(&self) -> usize

Get call stack depth
Source§

fn call_frames(&self) -> &[CallFrame]

Get call frames (for debugging)
Source§

fn local_values_vec(&self) -> Vec<ExternalValue>

Get local variables as ExternalValues (display only)
Source§

fn module_binding_values(&self) -> Vec<ValueWord>

Get module_binding variables (data-flow: values are stored back into VM)
Source§

fn set_module_binding(&mut self, index: usize, value: ValueWord)

Set a module_binding variable by index
Source§

fn set_trace_mode(&mut self, enabled: bool)

Set trace mode
Source§

fn debugger_mut(&mut self) -> Option<&mut VMDebugger>

Get mutable reference to debugger
Source§

fn has_debugger(&self) -> bool

Check if debugger is enabled
Source§

impl GCIntegration for VirtualMachine

Available on non-crate feature gc only.
Source§

fn maybe_collect_garbage(&mut self)

Maybe trigger garbage collection based on config
Source§

fn force_gc(&mut self) -> GCResult

Force garbage collection
Source§

fn gc_stats(&self) -> GCStats

Get GC statistics
Source§

fn gc_heap_size(&self) -> usize

Get GC heap size
Source§

fn gc_object_count(&self) -> usize

Get GC object count
Source§

fn gc(&self) -> &GarbageCollector

Access the garbage collector
Source§

fn gc_mut(&mut self) -> &mut GarbageCollector

Access the garbage collector mutably
Source§

impl TypedObjectOps for VirtualMachine

Source§

fn op_get_field_typed( &mut self, instruction: &Instruction, ) -> Result<(), VMError>

Get field from typed object using precomputed field type tag.

Zero-cost field access: the compiler embeds type_id, field_idx, and field_type_tag into the operand. At runtime we just read slots[field_idx] and use heap_mask + field_type_tag to interpret it. No schema lookup required.

Source§

fn op_set_field_typed( &mut self, instruction: &Instruction, ) -> Result<(), VMError>

Set field on typed object using precomputed field type tag.

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more