vm

package
v0.4.24 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

pkg/vm/builtins.go Builtin function support for the VM

pkg/vm/closure.go

pkg/vm/inline_cache.go Inline caching for property access and method calls

pkg/vm/instructions.go Instruction decoder for register-based VM

pkg/vm/reg_frame.go

pkg/vm/reg_vm.go Register-based Virtual Machine implementation

pkg/vm/runcode.go Support for dynamic code execution via runCode builtin

pkg/vm/value.go NaN Boxing implementation for efficient value representation

NaN boxing uses the IEEE 754 NaN representation to encode multiple types in a single 64-bit value without heap allocation.

Memory layout: - Floats: stored as native IEEE 754 double (no NaN boxing needed) - Integers: stored in NaN payload (48 bits) - Booleans: stored in NaN payload - Null: special NaN value - Objects: stored as pointer in NaN payload

OPTIMIZED: Removed global mutex for single-threaded VM execution. Uses atomic operations for thread-safe object registration.

pkg/vm/value_ops.go Value operations for NaN-boxed values These methods work directly with Value type, avoiding heap allocation

Index

Constants

View Source
const (
	GlobalsSize = 65536 // Size of global variables array
	MaxFrames   = 1024  // Maximum call frames
)

VM constants

View Source
const CacheSize = 1024

CacheSize is the number of cache entries

View Source
const ValueStackSize = 2048

ValueStackSize is the maximum number of elements on the stack

Variables

View Source
var (
	ValueNull  = Value(tagNullValue)
	ValueTrue  = Value(tagBoolValue | 1)
	ValueFalse = Value(tagBoolValue)
)

Special values - pre-computed for fast access

Functions

func ClearRegistry added in v0.4.22

func ClearRegistry()

ClearRegistry clears the global object registry

func ComputeCacheIndex added in v0.4.23

func ComputeCacheIndex(typeTag objects.TypeTag, class *objects.Class, nameHash uint32) int

ComputeCacheIndex computes the cache index from type tag/class and name hash

func DecodeBuiltin added in v0.4.21

func DecodeBuiltin(code []byte, ip int) (builtinIdx byte, numArgs byte)

DecodeBuiltin decodes a builtin call instruction

func DecodeCall added in v0.4.21

func DecodeCall(code []byte, ip int) (funcReg byte, numArgs byte)

DecodeCall decodes a call instruction

func DecodeClosure added in v0.4.21

func DecodeClosure(code []byte, ip int) (dstReg byte, funcIdx int, numFree byte)

DecodeClosure decodes a closure creation instruction

func DecodeConst added in v0.4.21

func DecodeConst(code []byte, ip int) (reg byte, constIdx int)

DecodeConst decodes an instruction with register and constant index

func DecodeField added in v0.4.21

func DecodeField(code []byte, ip int) (reg byte, objReg byte, nameIdx int)

DecodeField decodes a field access instruction

func DecodeJump added in v0.4.21

func DecodeJump(code []byte, ip int) (offset int)

DecodeJump decodes a jump instruction with signed 16-bit offset

func DecodeJumpCond added in v0.4.21

func DecodeJumpCond(code []byte, ip int) (condReg byte, offset int)

DecodeJumpCond decodes a conditional jump instruction with signed 16-bit offset

func DecodeMethodCall added in v0.4.21

func DecodeMethodCall(code []byte, ip int) (objReg byte, nameIdx int, numArgs byte)

DecodeMethodCall decodes a method call instruction

func DecodeReg1 added in v0.4.21

func DecodeReg1(code []byte, ip int) (reg byte)

DecodeReg1 decodes a 1-operand register instruction: reg

func DecodeReg2 added in v0.4.21

func DecodeReg2(code []byte, ip int) (dst, src byte)

DecodeReg2 decodes a 2-operand register instruction: dst, src

func DecodeReg3 added in v0.4.21

func DecodeReg3(code []byte, ip int) (dst, src1, src2 byte)

DecodeReg3 decodes a 3-operand register instruction: dst, src1, src2

func ExecuteRunCode added in v0.4.19

func ExecuteRunCode(code string, args *objects.Map) (objects.Object, error)

ExecuteRunCode is called by the runCode builtin

func GetBuiltinByIndex added in v0.4.23

func GetBuiltinByIndex(index int) *objects.Builtin

GetBuiltinByIndex returns a builtin function by index (exported for JIT)

func InstructionLen added in v0.4.21

func InstructionLen(op compiler.Opcode) int

InstructionLen returns the length of an instruction in bytes

func IsRegisterOpcode added in v0.4.21

func IsRegisterOpcode(op compiler.Opcode) bool

IsRegisterOpcode checks if an opcode is a register-based operation

func RegistryStats added in v0.4.22

func RegistryStats() (total, used int)

RegistryStats returns statistics about the object registry

func RunCodeInRegVM added in v0.4.21

func RunCodeInRegVM(code string, args *objects.Map, regVM *RegVM) (objects.Object, error)

RunCodeInRegVM executes code in the register VM context

func SetRunCodeCallback added in v0.4.19

func SetRunCodeCallback(fn RunCodeFunc)

SetRunCodeCallback registers the callback for runCode builtin

Types

type CacheResultType added in v0.4.23

type CacheResultType uint8

CacheResultType indicates what type of result is cached

const (
	CacheResultNone            CacheResultType = iota // No valid cache entry
	CacheResultMethod                                 // Cached method (builtin or function)
	CacheResultField                                  // Cached field value
	CacheResultNull                                   // Cached null (property not found)
	CacheResultPrimitiveMethod                        // Cached primitive type method
	CacheResultMapMethod                              // Cached map method
)

type Closure

type Closure struct {
	Fn        *compiler.CompiledFunction
	FreeVars  []objects.Object // Free variables for stack VM
	Constants []objects.Object // Constants from the creating VM
	Globals   []objects.Object // Globals from the creating module (for exported functions)

	// FreeVarsValues is used by register VM for shared mutable free variables
	// When set, register VM uses this instead of FreeVars
	FreeVarsValues []Value
}

Closure represents a function with captured variables

func (*Closure) HashKey

func (c *Closure) HashKey() objects.HashKey

HashKey returns the hash key

func (*Closure) Inspect

func (c *Closure) Inspect() string

Inspect returns a string representation

func (*Closure) ToBool

func (c *Closure) ToBool() *objects.Bool

ToBool returns the boolean value

func (*Closure) Type

func (c *Closure) Type() objects.ObjectType

Type returns the object type

func (*Closure) TypeTag

func (c *Closure) TypeTag() objects.TypeTag

TypeTag returns the type tag for fast type checking

type ExceptionHandler added in v0.4.19

type ExceptionHandler struct {
	// contains filtered or unexported fields
}

ExceptionHandler represents a try-catch-finally handler

type InlineCache added in v0.4.23

type InlineCache struct {
	// Key: type tag or class pointer for validation
	TypeTag  objects.TypeTag // For primitive types
	Class    *objects.Class  // For instances (pointer comparison)
	NameHash uint32          // Hash of property/method name

	// Result
	ResultType    CacheResultType // Type of cached result
	Method        objects.Object  // Cached method (if ResultType is Method or PrimitiveMethod)
	FieldIdx      int             // Cached field index (for instances)
	DefiningClass *objects.Class  // The class where the method was found (for super resolution)
}

InlineCache is a cache entry for property/method lookups

type InlineCacheTable added in v0.4.23

type InlineCacheTable struct {
	// contains filtered or unexported fields
}

InlineCacheTable is a fixed-size inline cache

func (*InlineCacheTable) Get added in v0.4.23

func (c *InlineCacheTable) Get(typeTag objects.TypeTag, class *objects.Class, nameHash uint32) *InlineCache

Get looks up the cache entry

func (*InlineCacheTable) Reset added in v0.4.23

func (c *InlineCacheTable) Reset()

Reset clears the cache

func (*InlineCacheTable) Set added in v0.4.23

func (c *InlineCacheTable) Set(typeTag objects.TypeTag, class *objects.Class, nameHash uint32, resultType CacheResultType, method objects.Object, fieldIdx int, definingClass *objects.Class)

Set stores a cache entry

func (*InlineCacheTable) Stats added in v0.4.23

func (c *InlineCacheTable) Stats() (hits, misses int)

Stats returns cache hit/miss statistics

type InstructionInfo added in v0.4.21

type InstructionInfo struct {
	Opcode   compiler.Opcode
	Dst      byte
	Src1     byte
	Src2     byte
	ConstIdx int
	Offset   int
	NumArgs  byte
}

InstructionInfo holds decoded instruction information

func DecodeInstruction added in v0.4.21

func DecodeInstruction(code []byte, ip int) (InstructionInfo, int)

DecodeInstruction decodes a single instruction from bytecode Returns the instruction info and the number of bytes consumed

type RegFrame added in v0.4.21

type RegFrame struct {
	Fn           *compiler.CompiledFunction
	IP           int                          // Instruction pointer
	Registers    [compiler.NumRegisters]Value // Fixed-size register array
	FreeVars     []Value                      // Closure free variables
	Constants    []Value                      // Constants for this frame
	Globals      []Value                      // Global variables reference
	This         Value                        // 'this' for method calls
	Locals       []Value                      // Local variables (for spilled values)
	CurrentClass *objects.Class               // The class whose method is executing (for super resolution)
}

RegFrame represents a call frame for the register-based VM Each frame has 256 fixed registers (R0-R255)

func NewRegFrame added in v0.4.21

func NewRegFrame(fn *compiler.CompiledFunction) *RegFrame

NewRegFrame creates a new register-based call frame

func (*RegFrame) ClearArgRegisters added in v0.4.21

func (f *RegFrame) ClearArgRegisters()

ClearArgRegisters clears the argument registers

func (*RegFrame) CopyArgRegisters added in v0.4.21

func (f *RegFrame) CopyArgRegisters(src *RegFrame, numArgs int)

CopyArgRegisters copies argument values from source frame's return registers to this frame's argument registers (R0-R7)

func (*RegFrame) GetConstant added in v0.4.21

func (f *RegFrame) GetConstant(idx int) Value

GetConstant returns a constant value

func (*RegFrame) GetFree added in v0.4.21

func (f *RegFrame) GetFree(idx int) Value

GetFree returns a free variable value

func (*RegFrame) GetGlobal added in v0.4.21

func (f *RegFrame) GetGlobal(idx int) Value

GetGlobal returns a global variable value

func (*RegFrame) GetLocal added in v0.4.21

func (f *RegFrame) GetLocal(idx int) Value

GetLocal returns a local variable value

func (*RegFrame) GetReg added in v0.4.21

func (f *RegFrame) GetReg(reg int) Value

GetReg returns the value in a register

func (*RegFrame) Instructions added in v0.4.21

func (f *RegFrame) Instructions() []byte

Instructions returns the compiled function's instructions

func (*RegFrame) Release added in v0.4.21

func (f *RegFrame) Release()

Release returns the frame to the pool for reuse

func (*RegFrame) SetFree added in v0.4.21

func (f *RegFrame) SetFree(idx int, val Value)

SetFree sets a free variable value

func (*RegFrame) SetGlobal added in v0.4.21

func (f *RegFrame) SetGlobal(idx int, val Value)

SetGlobal sets a global variable value

func (*RegFrame) SetLocal added in v0.4.21

func (f *RegFrame) SetLocal(idx int, val Value)

SetLocal sets a local variable value

func (*RegFrame) SetReg added in v0.4.21

func (f *RegFrame) SetReg(reg int, val Value)

SetReg sets the value in a register

type RegVM added in v0.4.21

type RegVM struct {
	// contains filtered or unexported fields
}

RegVM is a register-based virtual machine

func NewRegVM added in v0.4.21

func NewRegVM(bytecode *compiler.Bytecode) *RegVM

NewRegVM creates a new register-based VM

func NewRegVMWithGlobals added in v0.4.21

func NewRegVMWithGlobals(bytecode *compiler.Bytecode, globals []Value) *RegVM

NewRegVMWithGlobals creates a register VM with custom globals

func NewRegVMWithObjectGlobals added in v0.4.21

func NewRegVMWithObjectGlobals(bytecode *compiler.Bytecode, globals []objects.Object) *RegVM

NewRegVMWithObjectGlobals creates a register VM with globals as objects.Object

func (*RegVM) GetCallStack added in v0.4.21

func (vm *RegVM) GetCallStack() string

GetCallStack returns the current call stack

func (*RegVM) GetConstants added in v0.4.23

func (vm *RegVM) GetConstants() []Value

GetConstants returns the constants array (for JIT)

func (*RegVM) GetGlobals added in v0.4.23

func (vm *RegVM) GetGlobals() []Value

GetGlobals returns the globals array (for JIT, same as Globals)

func (*RegVM) Globals added in v0.4.21

func (vm *RegVM) Globals() []Value

Globals returns the globals array

func (*RegVM) GlobalsAsObjects added in v0.4.21

func (vm *RegVM) GlobalsAsObjects() []objects.Object

GlobalsAsObjects returns the globals as objects.Object slice

func (*RegVM) LastPopped added in v0.4.21

func (vm *RegVM) LastPopped() Value

LastPopped returns the last popped value from temp stack Note: For register VM, prefer LastResult() which returns from ReturnRegister

func (*RegVM) LastPoppedObject added in v0.4.21

func (vm *RegVM) LastPoppedObject() objects.Object

LastPoppedObject returns the result as objects.Object For register VM, this returns the value from ReturnRegister

func (*RegVM) LastResult added in v0.4.21

func (vm *RegVM) LastResult() Value

LastResult returns the value in the ReturnRegister This is the preferred method for getting results from the register VM

func (*RegVM) Run added in v0.4.21

func (vm *RegVM) Run() error

Run executes the bytecode in the register VM

func (*RegVM) SetCurrentModule added in v0.4.21

func (vm *RegVM) SetCurrentModule(mod *objects.Module)

SetCurrentModule sets the current module context

func (*RegVM) SetLastResult added in v0.4.23

func (vm *RegVM) SetLastResult(val Value)

SetLastResult sets the result value in the ReturnRegister This is used by JIT execution to store native execution results

func (*RegVM) SetLoader added in v0.4.21

func (vm *RegVM) SetLoader(loader *module.Loader)

SetLoader sets the module loader

func (*RegVM) SetNativeCallHook added in v0.4.23

func (vm *RegVM) SetNativeCallHook(hook func(fn *compiler.CompiledFunction, args []Value, frame *RegFrame) (Value, bool))

SetNativeCallHook sets a callback for native function execution The hook is called before executing a CompiledFunction If the hook returns true for handled, the VM skips normal execution

func (*RegVM) SetSourcePath added in v0.4.21

func (vm *RegVM) SetSourcePath(path string)

SetSourcePath sets the source file path

func (*RegVM) StackTop added in v0.4.21

func (vm *RegVM) StackTop() Value

StackTop returns the top of the temp stack

type RunCodeFunc added in v0.4.19

type RunCodeFunc func(code string, args *objects.Map) (objects.Object, error)

RunCodeFunc is the signature for the runCode callback

func GetRunCodeCallback added in v0.4.19

func GetRunCodeCallback() RunCodeFunc

GetRunCodeCallback returns the current callback

type Value added in v0.4.21

type Value uint64

Value is a NaN-boxed value that can represent multiple types efficiently

func NewBool added in v0.4.21

func NewBool(b bool) Value

NewBool creates a Value from a boolean

func NewFloat added in v0.4.21

func NewFloat(f float64) Value

NewFloat creates a Value from a float64 Normal floats are stored directly as IEEE 754 doubles

func NewInt added in v0.4.21

func NewInt(n int64) Value

NewInt creates a Value from an integer Stores up to 48 bits of integer data

func NewObject added in v0.4.21

func NewObject(obj objects.Object) Value

NewObject creates a Value from an object pointer

func NewValue added in v0.4.21

func NewValue(obj objects.Object) Value

NewValue creates a Value from any object

func ValueBool added in v0.4.21

func ValueBool(b bool) Value

ValueBool creates a Value from a boolean (alias for NewBool)

func (Value) Add added in v0.4.21

func (v Value) Add(other Value) (Value, bool)

Add adds two values OPTIMIZED: Fast path for integers avoids string checks entirely

func (Value) Div added in v0.4.21

func (v Value) Div(other Value) (Value, bool)

Div divides two values

func (Value) Equal added in v0.4.21

func (v Value) Equal(other Value) (bool, bool)

Equal compares if v == other OPTIMIZED: Fast integer comparison with direct bit manipulation

func (Value) EqualValue added in v0.4.21

func (v Value) EqualValue(other Value) Value

EqualValue returns a Value representing equality comparison

func (Value) GetBool added in v0.4.21

func (v Value) GetBool() bool

GetBool extracts the boolean value

func (Value) GetClosure added in v0.4.23

func (v Value) GetClosure() *Closure

GetClosure returns the Closure if this value is a Closure (lock-free)

func (Value) GetCompiledFunction added in v0.4.23

func (v Value) GetCompiledFunction() *compiler.CompiledFunction

GetCompiledFunction returns the CompiledFunction if this value is one (lock-free)

func (Value) GetFloat added in v0.4.21

func (v Value) GetFloat() float64

GetFloat extracts the float value

func (Value) GetInt added in v0.4.21

func (v Value) GetInt() int64

GetInt extracts the integer value

func (Value) GetObject added in v0.4.21

func (v Value) GetObject() objects.Object

GetObject extracts the object from the registry (lock-free)

func (Value) Greater added in v0.4.21

func (v Value) Greater(other Value) (bool, bool)

Greater compares if v > other OPTIMIZED: Direct bit manipulation for integer fast path

func (Value) GreaterEqual added in v0.4.21

func (v Value) GreaterEqual(other Value) Value

GreaterEqual compares if v >= other (optimized to avoid double comparison)

func (Value) GreaterValue added in v0.4.21

func (v Value) GreaterValue(other Value) Value

GreaterValue returns a Value representing greater than comparison

func (Value) IsBool added in v0.4.21

func (v Value) IsBool() bool

IsBool returns true if the value is a tagged boolean

func (Value) IsClosure added in v0.4.23

func (v Value) IsClosure() bool

IsClosure returns true if the value is a Closure (lock-free)

func (Value) IsCompiledFunction added in v0.4.23

func (v Value) IsCompiledFunction() bool

IsCompiledFunction returns true if the value is a CompiledFunction (lock-free)

func (Value) IsFloat added in v0.4.21

func (v Value) IsFloat() bool

IsFloat returns true if the value is a native float

func (Value) IsInt added in v0.4.21

func (v Value) IsInt() bool

IsInt returns true if the value is a tagged integer

func (Value) IsNull added in v0.4.21

func (v Value) IsNull() bool

IsNull returns true if the value is null

func (Value) IsNumber added in v0.4.21

func (v Value) IsNumber() bool

IsNumber returns true if the value is a number (int or float)

func (Value) IsObject added in v0.4.21

func (v Value) IsObject() bool

IsObject returns true if the value is a tagged object pointer

func (Value) IsTruthy added in v0.4.21

func (v Value) IsTruthy() bool

IsTruthy returns true if the value is truthy

func (Value) Less added in v0.4.21

func (v Value) Less(other Value) (bool, bool)

Less compares if v < other OPTIMIZED: Direct bit manipulation for integer fast path

func (Value) LessEqual added in v0.4.21

func (v Value) LessEqual(other Value) Value

LessEqual compares if v <= other (optimized to avoid double comparison)

func (Value) LessValue added in v0.4.21

func (v Value) LessValue(other Value) Value

LessValue returns a Value representing less than comparison

func (Value) Mod added in v0.4.21

func (v Value) Mod(other Value) (Value, bool)

Mod computes modulo OPTIMIZED: Direct bit manipulation for integer fast path

func (Value) Mul added in v0.4.21

func (v Value) Mul(other Value) (Value, bool)

Mul multiplies two values OPTIMIZED: Direct bit manipulation for integer fast path

func (Value) Neg added in v0.4.21

func (v Value) Neg() (Value, bool)

Neg negates a value

func (Value) NotEqual added in v0.4.21

func (v Value) NotEqual(other Value) (bool, bool)

NotEqual compares if v != other

func (Value) NotEqualValue added in v0.4.21

func (v Value) NotEqualValue(other Value) Value

NotEqualValue returns a Value representing inequality comparison

func (Value) String added in v0.4.21

func (v Value) String() string

String returns a string representation for debugging

func (Value) Sub added in v0.4.21

func (v Value) Sub(other Value) (Value, bool)

Sub subtracts two values OPTIMIZED: Direct bit manipulation for integer fast path

func (Value) ToFloat added in v0.4.21

func (v Value) ToFloat() (float64, bool)

ToFloat attempts to convert the value to a float

func (Value) ToInt added in v0.4.21

func (v Value) ToInt() (int64, bool)

ToInt attempts to convert the value to an integer

func (Value) ToObject added in v0.4.21

func (v Value) ToObject() objects.Object

ToObject converts a Value back to an objects.Object OPTIMIZED: Uses cached integer objects

type ValueStack added in v0.4.21

type ValueStack struct {
	// contains filtered or unexported fields
}

ValueStack represents the VM operand stack using NaN-boxed values

func NewValueStack added in v0.4.21

func NewValueStack() *ValueStack

NewValueStack creates a new value stack

func (*ValueStack) LastPopped added in v0.4.21

func (s *ValueStack) LastPopped() Value

LastPopped returns the last popped element

func (*ValueStack) Pop added in v0.4.21

func (s *ValueStack) Pop() Value

Pop pops a value from the stack

func (*ValueStack) Push added in v0.4.21

func (s *ValueStack) Push(v Value) error

Push pushes a value onto the stack

func (*ValueStack) Reset added in v0.4.21

func (s *ValueStack) Reset()

Reset clears the stack

func (*ValueStack) Top added in v0.4.21

func (s *ValueStack) Top() Value

Top returns the top element without removing it

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL